code
stringlengths 2
1.05M
|
---|
angular.module('app.controllers')
.controller('tabsCtrl', function($window, $http, activeTab) {
var vm = this;
vm.tabs = [
{name: 'achievements', link: 'achievements'},
{name: 'leaderboards', link: 'leaderboards'},
{name: 'timeCard', link: 'timeCard'},
{name: 'accuracy card', link: 'accuracyCard'},
{name: 'chat', link: 'chat'},
{name: 'logout', link: 'logout'}
];
vm.isSelected = function (tabLink) {
return activeTab.getActive() === tabLink;
}
vm.setActive = function (tabLink) {
activeTab.setActive(tabLink);
}
vm.logout = function () {
$http.get('/logoutReq')
.then(hardRedirect)
.catch(errHandle);
}
function hardRedirect () {
$window.location.href = `${$window.location.origin}/`;
}
function errHandle (err) {
console.log(err);
}
});
|
'use strict';
angular.module('myApp.blog', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/blog', {
templateUrl: 'views/blog/blog.html',
controller: 'BlogCtrl as blog'
});
}])
.controller('BlogCtrl', [function() {
this.title = "Blog";
this.details = 'Capturing the new build, day-by-day. Also some ideas and current events.'
}]);
|
'use strict'
// Key codes (that will be the crappy part to maintain)
const keys = {
end: [
'\u0003', // CTRL+C
'\u0004', // CTRL+D
],
escape: [
'\u001b', // ESCAPE
],
left: [
'\u001b\u005b\u0044', // ←
],
right: [
'\u001b\u005b\u0043', // →
],
up: [
'\u001b\u005b\u0041', // ↑
],
down: [
'\u001b\u005b\u0042', // ↓
],
pgup: [
'\u001b\u005b\u0035\u007e', // ↑↑
],
pgdown: [
'\u001b\u005b\u0036\u007e', // ↓↓
],
enter: [
'\u000d', // ENTER
],
del: [
'\u001b\u005b\u0033\u007e', // SUPPR
],
back: [
'\u007f', // BACKSPACE
],
}
// key: string => expected: string => boolean
module.exports = key => expected => keys[expected].includes(key)
|
import * as React from 'react';
import loadScript from 'docs/src/modules/utils/loadScript';
import { useTheme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useNoSsrCodeVariant } from 'docs/src/modules/utils/codeVariant';
import { useUserLanguage } from 'docs/src/modules/utils/i18n';
import { pathnameToLanguage } from 'docs/src/modules/utils/helpers';
import { useRouter } from 'next/router';
// So we can write code like:
//
// <Button
// ga-event-category="demo"
// ga-event-action="expand"
// >
// Foo
// </Button>
function handleClick(event) {
let element = event.target;
while (element && element !== document) {
const category = element.getAttribute('data-ga-event-category');
// We reach a tracking element, no need to look higher in the dom tree.
if (category) {
const split = parseFloat(element.getAttribute('data-ga-event-split'));
if (split && split < Math.random()) {
return;
}
window.ga('send', {
hitType: 'event',
eventCategory: category,
eventAction: element.getAttribute('data-ga-event-action'),
eventLabel: element.getAttribute('data-ga-event-label'),
});
break;
}
element = element.parentElement;
}
}
let boundDataGaListener = false;
/**
* basically just a `useAnalytics` hook.
* However, it needs the redux store which is created
* in the same component this "hook" is used.
*/
function GoogleAnalytics() {
React.useEffect(() => {
loadScript('https://www.google-analytics.com/analytics.js', document.querySelector('head'));
if (!boundDataGaListener) {
boundDataGaListener = true;
document.addEventListener('click', handleClick);
}
}, []);
const router = useRouter();
React.useEffect(() => {
// Wait for the title to be updated.
setTimeout(() => {
const { canonicalAs } = pathnameToLanguage(window.location.pathname);
window.ga('set', { page: canonicalAs });
window.ga('send', { hitType: 'pageview' });
});
}, [router.route]);
const codeVariant = useNoSsrCodeVariant();
React.useEffect(() => {
window.ga('set', 'dimension1', codeVariant);
}, [codeVariant]);
const userLanguage = useUserLanguage();
React.useEffect(() => {
window.ga('set', 'dimension2', userLanguage);
}, [userLanguage]);
React.useEffect(() => {
/**
* Based on https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#Monitoring_screen_resolution_or_zoom_level_changes
* Adjusted to track 3 or more different ratios
*/
function trackDevicePixelRation() {
const devicePixelRatio = Math.round(window.devicePixelRatio * 10) / 10;
window.ga('set', 'dimension3', devicePixelRatio);
}
trackDevicePixelRation();
/**
* @type {MediaQueryList}
*/
const matchMedia = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
matchMedia.addEventListener('change', trackDevicePixelRation);
return () => {
matchMedia.removeEventListener('change', trackDevicePixelRation);
};
}, []);
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)', { noSsr: true });
const colorSchemeOS = prefersDarkMode ? 'dark' : 'light';
const theme = useTheme();
const colorScheme = theme.palette.mode;
React.useEffect(() => {
window.ga('set', 'dimension4', colorSchemeOS);
window.ga('set', 'dimension5', colorScheme);
}, [colorSchemeOS, colorScheme]);
return null;
}
export default React.memo(GoogleAnalytics);
|
version https://git-lfs.github.com/spec/v1
oid sha256:6fa6fdf70f93edf3c978b8c472049b8336377575598ef7b9a4e3a1767fb0e294
size 2277
|
'lang sweet.js';
// true
export syntax sach = function (ctx) {
return #`true`;
}
// false
export syntax galat = function (ctx) {
return #`false`;
}
// if
export syntax agar = function (ctx) {
let ifparam = ctx.next().value
let ifblock = ctx.next().value;
let warnas = ctx.next();
let result = #`if ${ifparam} ${ifblock}`;
while(!warnas.done){
if (warnas.value.value.token.value === "warna"){
let elseblock = ctx.next().value;
result = result.concat(#`else ${elseblock}`)
}
if (warnas.value.value.token.value === "warnaagar"){
let elseifparam = ctx.next().value;
let elseifblock = ctx.next().value;
result = result.concat(#`else if ${elseifparam} ${elseifblock}`)
}
warnas = ctx.next();
}
//console.log("warnas",warnas.value.token.value)
return result
//return #`if ${ifparam} ${ifblock}`;
}
// var
export syntax samjho = function (ctx) {
return #`var`;
}
// while
export syntax jabtak = function (ctx) {
let wparam = ctx.next().value
let wblock = ctx.next().value;
return #`while ${wparam} ${wblock}`;
}
// console.log
export syntax likho = function (ctx) {
let params = ctx.next().value
//let wblock = ctx.next().value;
return #`console.log ${params}`;
}
// function
export syntax tareeka = function (ctx) {
let fname = ctx.next().value
let fparam = ctx.next().value
let fblock = ctx.next().value;
return #`function ${fname} ${fparam} ${fblock}`;
}
// for and foreach loop
export syntax har = function (ctx) {
let fparam = ctx.next().value
if (fparam.type==="RawSyntax"){
//foreach
let fparamk = ctx.next().value;
let fparamvar = ctx.next().value;
let fblock = ctx.next().value;
//ignore 'per' or 'pe' if present
if (fblock.type==="RawSyntax"
&& fblock.value.token.value==="per"
&& fblock.value.token.value==="pe"
){
fblock = ctx.next().value;
}
return #`for (var ${fparamvar} of ${fparam}) ${fblock}`;
}
else{
let fblock = ctx.next().value;
return #`for ${fparam} ${fblock}`;
}
}
|
<-- Error 401: Access Denied -->>
|
define(['exports', 'aurelia-loader', 'aurelia-metadata'], function (exports, _aureliaLoader, _aureliaMetadata) {
'use strict';
exports.__esModule = true;
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var TextTemplateLoader = (function () {
function TextTemplateLoader() {
_classCallCheck(this, TextTemplateLoader);
this.hasTemplateElement = 'content' in document.createElement('template');
}
TextTemplateLoader.prototype.loadTemplate = function loadTemplate(loader, entry) {
var _this = this;
return loader.loadText(entry.address).then(function (text) {
entry.setTemplate(_this._createTemplateFromMarkup(text));
});
};
TextTemplateLoader.prototype._createTemplateFromMarkup = function _createTemplateFromMarkup(markup) {
var parser = document.createElement('div');
if (typeof MSApp != 'undefined') {
MSApp.execUnsafeLocalFunction(function() {
parser.innerHTML = markup;
});
} else
parser.innerHTML = markup;
var template = parser.firstElementChild;
if (this.hasTemplateElement) {
return template;
}
if (typeof MSApp != 'undefined') {
MSApp.execUnsafeLocalFunction(function () {
parser.innerHTML = parser.firstElementChild.innerHTML.trim();
});
} else
parser.innerHTML = parser.firstElementChild.innerHTML.trim();
template = parser;
template.content = document.createDocumentFragment();
while (template.firstChild) {
template.content.appendChild(template.firstChild);
}
HTMLTemplateElement.bootstrap(template);
return template;
};
return TextTemplateLoader;
})();
exports.TextTemplateLoader = TextTemplateLoader;
var polyfilled = false;
if (!window.System || !window.System['import']) {
var sys = window.System = window.System || {};
sys.polyfilled = polyfilled = true;
sys.isFake = false;
sys.map = {};
sys['import'] = function (moduleId) {
return new Promise(function (resolve, reject) {
require([moduleId], resolve, reject);
});
};
sys.normalize = function (url) {
return Promise.resolve(url);
};
sys.normalizeSync = function (url) {
return url;
};
if (window.requirejs && requirejs.s && requirejs.s.contexts && requirejs.s.contexts._ && requirejs.s.contexts._.defined) {
(function () {
var defined = requirejs.s.contexts._.defined;
sys.forEachModule = function (callback) {
for (var key in defined) {
if (callback(key, defined[key])) return;
}
};
})();
} else {
sys.forEachModule = function (callback) {};
}
} else {
(function () {
var modules = System._loader.modules;
System.isFake = false;
System.forEachModule = function (callback) {
for (var key in modules) {
if (callback(key, modules[key].module)) return;
}
};
System.set('text', System.newModule({
'translate': function translate(load) {
return 'module.exports = "' + load.source.replace(/(["\\])/g, '\\$1').replace(/[\f]/g, '\\f').replace(/[\b]/g, '\\b').replace(/[\n]/g, '\\n').replace(/[\t]/g, '\\t').replace(/[\r]/g, '\\r').replace(/[\u2028]/g, '\\u2028').replace(/[\u2029]/g, '\\u2029') + '";';
}
}));
})();
}
function ensureOriginOnExports(executed, name) {
var target = executed;
var key = undefined;
var exportedValue = undefined;
if (target.__useDefault) {
target = target['default'];
}
_aureliaMetadata.Origin.set(target, new _aureliaMetadata.Origin(name, 'default'));
for (key in target) {
exportedValue = target[key];
if (typeof exportedValue === 'function') {
_aureliaMetadata.Origin.set(exportedValue, new _aureliaMetadata.Origin(name, key));
}
}
return executed;
}
var DefaultLoader = (function (_Loader) {
_inherits(DefaultLoader, _Loader);
function DefaultLoader() {
_classCallCheck(this, DefaultLoader);
_Loader.call(this);
this.textPluginName = 'text';
this.moduleRegistry = {};
this.useTemplateLoader(new TextTemplateLoader());
var that = this;
this.addPlugin('template-registry-entry', {
'fetch': function fetch(address) {
var entry = that.getOrCreateTemplateRegistryEntry(address);
return entry.templateIsLoaded ? entry : that.templateLoader.loadTemplate(that, entry).then(function (x) {
return entry;
});
}
});
}
DefaultLoader.prototype.useTemplateLoader = function useTemplateLoader(templateLoader) {
this.templateLoader = templateLoader;
};
DefaultLoader.prototype.loadModule = function loadModule(id) {
var _this2 = this;
return System.normalize(id).then(function (newId) {
var existing = _this2.moduleRegistry[newId];
if (existing) {
return existing;
}
return System['import'](newId).then(function (m) {
_this2.moduleRegistry[newId] = m;
return ensureOriginOnExports(m, newId);
});
});
};
DefaultLoader.prototype.loadAllModules = function loadAllModules(ids) {
var loads = [];
for (var i = 0, ii = ids.length; i < ii; ++i) {
loads.push(this.loadModule(ids[i]));
}
return Promise.all(loads);
};
DefaultLoader.prototype.loadTemplate = function loadTemplate(url) {
return System['import'](this.applyPluginToUrl(url, 'template-registry-entry'));
};
DefaultLoader.prototype.loadText = function loadText(url) {
return System['import'](this.applyPluginToUrl(url, this.textPluginName));
};
DefaultLoader.prototype.applyPluginToUrl = function applyPluginToUrl(url, pluginName) {
return polyfilled ? pluginName + '!' + url : url + '!' + pluginName;
};
DefaultLoader.prototype.addPlugin = function addPlugin(pluginName, implementation) {
if (polyfilled) {
define(pluginName, [], {
'load': function load(name, req, onload) {
var address = req.toUrl(name);
var result = implementation.fetch(address);
Promise.resolve(result).then(onload);
}
});
} else {
System.set(pluginName, System.newModule({
'fetch': function fetch(load, _fetch) {
var result = implementation.fetch(load.address);
return Promise.resolve(result).then(function (x) {
load.metadata.result = x;
return '';
});
},
'instantiate': function instantiate(load) {
return load.metadata.result;
}
}));
}
};
return DefaultLoader;
})(_aureliaLoader.Loader);
exports.DefaultLoader = DefaultLoader;
window.AureliaLoader = DefaultLoader;
});
|
import React from 'react'
const Counter = ({count, boldButtons, onClick}) =>
<button
onClick={onClick}
style={{fontWeight: boldButtons ? 'bold' : 'normal'}}
>
{count}
</button>
Counter.propTypes = {
id: React.PropTypes.number.isRequired,
count: React.PropTypes.number.isRequired,
boldButtons: React.PropTypes.bool.isRequired,
onClick: React.PropTypes.func.isRequired
}
export default Counter
|
define(function() {
return function(controller) {
var login = new kony.ui.FlexContainer({
"clipBounds": true,
"isMaster": true,
"height": "100%",
"id": "login",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "0dp",
"skin": "CopyCopyslFbox4",
"top": "0dp",
"width": "100%"
}, {}, {});
login.setDefaultUnit(kony.flex.DP);
var flxLogin = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"clipBounds": false,
"height": "100%",
"id": "flxLogin",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": 0,
"skin": "CopyCopyCopysknslFbox1",
"top": "0dp",
"width": "100%",
"zIndex": 1
}, {}, {});
flxLogin.setDefaultUnit(kony.flex.DP);
var flxBottomContainer = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"bottom": "0dp",
"centerX": "50%",
"clipBounds": true,
"height": "60%",
"id": "flxBottomContainer",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"skin": "CopyCopyCopysknCopyslFbox1",
"width": "100%",
"zIndex": 8
}, {}, {});
flxBottomContainer.setDefaultUnit(kony.flex.DP);
flxBottomContainer.add();
var flxlogo = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"centerX": "50%",
"clipBounds": false,
"height": "40%",
"id": "flxlogo",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"skin": "CopyCopyCopyslFbox1",
"top": "0dp",
"width": "100%",
"zIndex": 8
}, {}, {});
flxlogo.setDefaultUnit(kony.flex.DP);
var imgLogo = new kony.ui.Image2({
"centerX": "50%",
"centerY": "40%",
"height": "30%",
"id": "imgLogo",
"isVisible": true,
"skin": "CopyCopyslImage3",
"src": "logo.png",
"width": "30%",
"zIndex": 1
}, {
"imageScaleMode": constants.IMAGE_SCALE_MODE_MAINTAIN_ASPECT_RATIO,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {});
flxlogo.add(imgLogo);
var flxTouchId = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"centerY": "78%",
"clipBounds": true,
"height": "8%",
"id": "flxTouchId",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "0%",
"onClick": controller.AS_FlexContainer_0565b74578ed4af8ba232bf0cd2b9541,
"skin": "CopyCopyslFbox5",
"width": "100%",
"zIndex": 8
}, {}, {});
flxTouchId.setDefaultUnit(kony.flex.DP);
var imgTouchId = new kony.ui.Image2({
"centerY": "50%",
"height": "40dp",
"id": "imgTouchId",
"isVisible": true,
"left": "22%",
"skin": "CopyCopyslImage3",
"src": "touch_id_icon.png",
"width": "40dp",
"zIndex": 1
}, {
"imageScaleMode": constants.IMAGE_SCALE_MODE_MAINTAIN_ASPECT_RATIO,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {});
var lblTouchId = new kony.ui.Label({
"centerY": "50%",
"id": "lblTouchId",
"isVisible": true,
"left": "37%",
"skin": "CopyCopyCopyslLabel5",
"text": "Sign in with Touch ID",
"width": kony.flex.USE_PREFFERED_SIZE,
"zIndex": 1
}, {
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"textCopyable": false,
"wrapping": constants.WIDGET_TEXT_WORD_WRAP
});
flxTouchId.add(imgTouchId, lblTouchId);
var flxSocialLogin = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"centerY": "90.50%",
"clipBounds": true,
"height": "19%",
"id": "flxSocialLogin",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "0%",
"width": "100%",
"zIndex": 8
}, {}, {});
flxSocialLogin.setDefaultUnit(kony.flex.DP);
var flxOr = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"clipBounds": true,
"height": "40%",
"id": "flxOr",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "0%",
"skin": "CopyCopyslFbox5",
"top": "0%",
"width": "100%",
"zIndex": 8
}, {}, {});
flxOr.setDefaultUnit(kony.flex.DP);
var lblLine1 = new kony.ui.Label({
"centerX": "25%",
"height": "2%",
"id": "lblLine1",
"isVisible": true,
"skin": "CopyCopyCopyslLabel3",
"top": "50%",
"width": "35%",
"zIndex": 1
}, {
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"textCopyable": false,
"wrapping": constants.WIDGET_TEXT_WORD_WRAP
});
var lblOr = new kony.ui.Label({
"centerX": "50%",
"height": "50%",
"id": "lblOr",
"isVisible": true,
"skin": "CopyCopyCopyslLabel4",
"text": "OR",
"top": "25%",
"width": kony.flex.USE_PREFFERED_SIZE,
"zIndex": 1
}, {
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"textCopyable": false,
"wrapping": constants.WIDGET_TEXT_WORD_WRAP
});
var lblLine2 = new kony.ui.Label({
"centerX": "75%",
"height": "2%",
"id": "lblLine2",
"isVisible": true,
"skin": "CopyCopyCopyslLabel3",
"top": "50%",
"width": "35%",
"zIndex": 1
}, {
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"textCopyable": false,
"wrapping": constants.WIDGET_TEXT_WORD_WRAP
});
flxOr.add(lblLine1, lblOr, lblLine2);
var flxFacebook = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"centerX": "50%",
"centerY": "60%",
"clipBounds": true,
"height": "40dp",
"id": "flxFacebook",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"onClick": controller.AS_FlexContainer_c1889801e50245af819017fdb980bed6,
"width": "40dp",
"zIndex": 8
}, {}, {});
flxFacebook.setDefaultUnit(kony.flex.DP);
var imgFaceBook = new kony.ui.Image2({
"height": "100%",
"id": "imgFaceBook",
"isVisible": true,
"left": "0%",
"src": "facebook.png",
"top": "0%",
"width": "100%",
"zIndex": 1
}, {
"imageScaleMode": constants.IMAGE_SCALE_MODE_MAINTAIN_ASPECT_RATIO,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {});
flxFacebook.add(imgFaceBook);
var flxLinkedin = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"centerX": "65%",
"centerY": "60%",
"clipBounds": true,
"height": "40dp",
"id": "flxLinkedin",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "228dp",
"onClick": controller.AS_FlexContainer_ia857350c99f4ec4b9646fc5da3a88f6,
"top": "22dp",
"width": "40dp",
"zIndex": 8
}, {}, {});
flxLinkedin.setDefaultUnit(kony.flex.DP);
var imgLinkedIn = new kony.ui.Image2({
"height": "100%",
"id": "imgLinkedIn",
"isVisible": true,
"left": "0%",
"src": "linkedin.png",
"top": "0%",
"width": "100%",
"zIndex": 1
}, {
"imageScaleMode": constants.IMAGE_SCALE_MODE_MAINTAIN_ASPECT_RATIO,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {});
flxLinkedin.add(imgLinkedIn);
var flxGoogle = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"centerX": "50%",
"centerY": "60%",
"clipBounds": true,
"height": "40dp",
"id": "flxGoogle",
"isVisible": false,
"layoutType": kony.flex.FREE_FORM,
"left": "157dp",
"onClick": controller.AS_FlexContainer_b5222b09fbad45b59f22fead2d5f5c1c,
"top": "41dp",
"width": "40dp",
"zIndex": 8
}, {}, {});
flxGoogle.setDefaultUnit(kony.flex.DP);
var imgGoogle = new kony.ui.Image2({
"height": "100%",
"id": "imgGoogle",
"isVisible": true,
"left": "0%",
"src": "google.png",
"top": "0%",
"width": "100%",
"zIndex": 1
}, {
"imageScaleMode": constants.IMAGE_SCALE_MODE_MAINTAIN_ASPECT_RATIO,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {});
flxGoogle.add(imgGoogle);
var flxOffice365 = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"centerX": "35%",
"centerY": "60%",
"clipBounds": true,
"height": "40dp",
"id": "flxOffice365",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"onClick": controller.AS_FlexContainer_e0ccf673175e48308c705f8f7b27ba5e,
"width": "40dp",
"zIndex": 8
}, {}, {});
flxOffice365.setDefaultUnit(kony.flex.DP);
var imgOffice365 = new kony.ui.Image2({
"height": "100%",
"id": "imgOffice365",
"isVisible": true,
"left": "0%",
"src": "office.png",
"top": "0%",
"width": "100%",
"zIndex": 1
}, {
"imageScaleMode": constants.IMAGE_SCALE_MODE_MAINTAIN_ASPECT_RATIO,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {});
flxOffice365.add(imgOffice365);
flxSocialLogin.add(flxOr, flxFacebook, flxLinkedin, flxGoogle, flxOffice365);
var flxCredentials = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"centerX": "50%",
"centerY": "50%",
"clipBounds": false,
"height": "43%",
"id": "flxCredentials",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"skin": "CopyCopyCopyskngenericCard1",
"width": "92%",
"zIndex": 8
}, {}, {});
flxCredentials.setDefaultUnit(kony.flex.DP);
var flxUsername = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"clipBounds": true,
"height": "15%",
"id": "flxUsername",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "5%",
"right": "5%",
"skin": "CopyCopyCopysknslFbox1",
"top": "4%",
"width": "90%",
"zIndex": 1
}, {}, {});
flxUsername.setDefaultUnit(kony.flex.DP);
var tbxUsername = new kony.ui.TextBox2({
"autoCapitalize": constants.TEXTBOX_AUTO_CAPITALIZE_NONE,
"focusSkin": "CopyCopyCopysknloginTextField1",
"height": "33dp",
"id": "tbxUsername",
"isVisible": true,
"keyBoardStyle": constants.TEXTBOX_KEY_BOARD_STYLE_DEFAULT,
"left": "0dp",
"maxTextLength": 30,
"onDone": controller.AS_TextField_f2a98e0e28fa4cf7ab5090e88380bb66,
"right": 0,
"secureTextEntry": false,
"skin": "CopyCopyCopysknloginTextField1",
"textInputMode": constants.TEXTBOX_INPUT_MODE_ANY,
"top": "15%",
"width": "100%"
}, {
"containerHeightMode": constants.TEXTBOX_FONT_METRICS_DRIVEN_HEIGHT,
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"autoCorrect": false,
"closeButtonText": "Done",
"keyboardActionLabel": constants.TEXTBOX_KEYBOARD_LABEL_DONE,
"placeholderSkin": "CopyCopysknPlaceholderKA1",
"showClearButton": true,
"showCloseButton": false,
"showProgressIndicator": false,
"viewType": constants.TEXTBOX_VIEW_TYPE_DEFAULT
});
var flxBottomUsername = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"bottom": "12%",
"clipBounds": true,
"height": "1dp",
"id": "flxBottomUsername",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "0dp",
"right": "0dp",
"skin": "CopyCopyCopyskntextFieldDivider1",
"zIndex": 1
}, {}, {});
flxBottomUsername.setDefaultUnit(kony.flex.DP);
flxBottomUsername.add();
flxUsername.add(tbxUsername, flxBottomUsername);
var flxPassword = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"clipBounds": true,
"height": "15%",
"id": "flxPassword",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "5%",
"right": "5%",
"skin": "CopyCopyCopysknslFbox1",
"top": "21%",
"width": "90%",
"zIndex": 1
}, {}, {});
flxPassword.setDefaultUnit(kony.flex.DP);
var tbxPassword = new kony.ui.TextBox2({
"autoCapitalize": constants.TEXTBOX_AUTO_CAPITALIZE_NONE,
"focusSkin": "CopyCopyCopysknloginTextField1",
"height": "36dp",
"id": "tbxPassword",
"isVisible": true,
"keyBoardStyle": constants.TEXTBOX_KEY_BOARD_STYLE_DEFAULT,
"left": "0dp",
"maxTextLength": 30,
"onDone": controller.AS_TextField_35916db09d234cef9beb1541afb1fd67,
"right": 0,
"secureTextEntry": true,
"skin": "CopyCopyCopysknloginTextField1",
"textInputMode": constants.TEXTBOX_INPUT_MODE_ANY,
"top": "15%",
"width": "100%"
}, {
"containerHeightMode": constants.TEXTBOX_FONT_METRICS_DRIVEN_HEIGHT,
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"autoCorrect": false,
"keyboardActionLabel": constants.TEXTBOX_KEYBOARD_LABEL_DONE,
"placeholderSkin": "CopyCopysknPlaceholderKA1",
"showClearButton": true,
"showCloseButton": true,
"showProgressIndicator": true,
"viewType": constants.TEXTBOX_VIEW_TYPE_DEFAULT
});
var flxBottomPassword = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"bottom": "12%",
"clipBounds": true,
"height": "1dp",
"id": "flxBottomPassword",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "0dp",
"right": "0dp",
"skin": "CopyCopyCopyskntextFieldDivider1",
"zIndex": 1
}, {}, {});
flxBottomPassword.setDefaultUnit(kony.flex.DP);
flxBottomPassword.add();
flxPassword.add(tbxPassword, flxBottomPassword);
var flxRememberMe = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"clipBounds": false,
"height": "34dp",
"id": "flxRememberMe",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "6.97%",
"onClick": controller.AS_FlexContainer_40857fa09bd74ab296b13260a335a8c6,
"right": "5%",
"skin": "CopyCopyCopysknslFbox1",
"top": "40.96%",
"width": "50%",
"zIndex": 1
}, {}, {});
flxRememberMe.setDefaultUnit(kony.flex.DP);
var lblRememberMe = new kony.ui.Label({
"centerY": "50.00%",
"id": "lblRememberMe",
"isVisible": true,
"left": "23%",
"skin": "CopyCopyCopyskn1",
"text": "Remember Me",
"width": kony.flex.USE_PREFFERED_SIZE,
"zIndex": 1
}, {
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"textCopyable": false,
"wrapping": constants.WIDGET_TEXT_WORD_WRAP
});
var imgRememberme = new kony.ui.Image2({
"centerY": "50%",
"height": "20dp",
"id": "imgRememberme",
"imageWhenFailed": "checkbox_unselected.png",
"isVisible": false,
"left": "5%",
"skin": "CopyCopyCopyslImage1",
"src": "checkbox_selected.png",
"top": "0dp",
"width": "25dp",
"zIndex": 1
}, {
"imageScaleMode": constants.IMAGE_SCALE_MODE_MAINTAIN_ASPECT_RATIO,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {});
var imgUnselected = new kony.ui.Image2({
"centerY": "50%",
"height": "20dp",
"id": "imgUnselected",
"isVisible": true,
"left": "5%",
"skin": "CopyCopyslImage4",
"src": "checkbox_unselected.png",
"width": "25dp",
"zIndex": 1
}, {
"imageScaleMode": constants.IMAGE_SCALE_MODE_MAINTAIN_ASPECT_RATIO,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {});
flxRememberMe.add(lblRememberMe, imgRememberme, imgUnselected);
var flxForgotPassword = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"centerX": "50%",
"clipBounds": true,
"height": "30dp",
"id": "flxForgotPassword",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"skin": "CopyCopyslFbox5",
"top": "80%",
"width": "90%",
"zIndex": 1
}, {}, {});
flxForgotPassword.setDefaultUnit(kony.flex.DP);
var btnForgotPassword = new kony.ui.Button({
"centerX": "50%",
"centerY": "50%",
"focusSkin": "CopyCopysknsecondaryActionFocus1",
"height": "80%",
"id": "btnForgotPassword",
"isVisible": true,
"left": "0%",
"onClick": controller.Action15048087621865613,
"skin": "CopyCopyCopysknsecondaryAction1",
"text": "Forgot password?",
"width": "90%",
"zIndex": 1
}, {
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_RIGHT,
"displayText": true,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"showProgressIndicator": false
});
var lblSknHidden = new kony.ui.Label({
"height": "0%",
"id": "lblSknHidden",
"isVisible": true,
"left": "0%",
"skin": "sknAnimate",
"top": "0%",
"width": "0%",
"zIndex": 1
}, {
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"textCopyable": false,
"wrapping": constants.WIDGET_TEXT_WORD_WRAP
});
flxForgotPassword.add(btnForgotPassword, lblSknHidden);
var lblPassword = new kony.ui.Label({
"height": "33dp",
"id": "lblPassword",
"isVisible": true,
"left": "5%",
"skin": "sknLblAnimate",
"text": "Password",
"top": "23%",
"width": "90%",
"zIndex": 1
}, {
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"textCopyable": false,
"wrapping": constants.WIDGET_TEXT_WORD_WRAP
});
var btnLogin = new kony.ui.Button({
"centerX": "50.06%",
"focusSkin": "CopyCopysknprimaryActionFocus1",
"height": "42dp",
"id": "btnLogin",
"isVisible": true,
"onClick": controller.AS_Button_deaad3576fdd45dfb7bd4cea5907d98c,
"skin": "CopyCopyCopysknprimaryAction1",
"text": "SIGN IN",
"top": "60.04%",
"width": "80%",
"zIndex": 1
}, {
"contentAlignment": constants.CONTENT_ALIGN_CENTER,
"displayText": true,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"showProgressIndicator": true
});
var lblUsername = new kony.ui.Label({
"height": "33dp",
"id": "lblUsername",
"isVisible": true,
"left": "5%",
"skin": "sknLblAnimate",
"text": "Username",
"top": "6%",
"width": "90%",
"zIndex": 1
}, {
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"textCopyable": false,
"wrapping": constants.WIDGET_TEXT_WORD_WRAP
});
var flxLblUsername = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"clipBounds": true,
"height": "33dp",
"id": "flxLblUsername",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "5%",
"onClick": controller.AS_FlexContainer_c456c5f9c50e4ba8b9897794f2d70232,
"top": "6%",
"width": "90%",
"zIndex": 1
}, {}, {});
flxLblUsername.setDefaultUnit(kony.flex.DP);
flxLblUsername.add();
var flxLblPassword = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"clipBounds": true,
"height": "33dp",
"id": "flxLblPassword",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "5%",
"onClick": controller.AS_FlexContainer_a577f20bc92e4174a07871e987f1aa3d,
"top": "23%",
"width": "90%",
"zIndex": 1
}, {}, {});
flxLblPassword.setDefaultUnit(kony.flex.DP);
flxLblPassword.add();
flxCredentials.add(flxUsername, flxPassword, flxRememberMe, flxForgotPassword, lblPassword, btnLogin, lblUsername, flxLblUsername, flxLblPassword);
var flxPopups = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"clipBounds": true,
"height": "100%",
"id": "flxPopups",
"isVisible": false,
"layoutType": kony.flex.FREE_FORM,
"left": "0%",
"skin": "CopysknflxMob1",
"top": "0%",
"width": "100%",
"zIndex": 9
}, {}, {});
flxPopups.setDefaultUnit(kony.flex.DP);
var flxEnableTouchIDPopup = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"bottom": "27%",
"centerX": "50%",
"centerY": "50%",
"clipBounds": true,
"height": "40%",
"id": "flxEnableTouchIDPopup",
"isVisible": false,
"layoutType": kony.flex.FREE_FORM,
"left": "0%",
"skin": "CopysknFlxMobFFFFFFOp1",
"width": "89%",
"zIndex": 10
}, {}, {});
flxEnableTouchIDPopup.setDefaultUnit(kony.flex.DP);
var flxButtons = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"bottom": "0%",
"clipBounds": true,
"height": "20%",
"id": "flxButtons",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "0dp",
"skin": "CopyslFbox2",
"width": "100%",
"zIndex": 1
}, {}, {});
flxButtons.setDefaultUnit(kony.flex.DP);
var btnEnable = new kony.ui.Button({
"focusSkin": "CopyCopyslButtonGlossRed1",
"height": "100%",
"id": "btnEnable",
"isVisible": true,
"left": "50%",
"onClick": controller.AS_Button_d06dd8aa54a846a7866d73b869fa9829,
"skin": "CopysknBtn1",
"text": "Enable",
"top": "0%",
"width": "50%",
"zIndex": 10
}, {
"contentAlignment": constants.CONTENT_ALIGN_CENTER,
"displayText": true,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"showProgressIndicator": true
});
var btnCancel = new kony.ui.Button({
"focusSkin": "CopyCopyslButtonGlossRed1",
"height": "100%",
"id": "btnCancel",
"isVisible": true,
"left": "0%",
"onClick": controller.AS_Button_bc85595f24bd43e0af7a39e8aadda3c4,
"skin": "CopysknBtnFA1",
"text": "Cancel",
"top": "0%",
"width": "50%",
"zIndex": 10
}, {
"contentAlignment": constants.CONTENT_ALIGN_CENTER,
"displayText": true,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"showProgressIndicator": true
});
flxButtons.add(btnEnable, btnCancel);
var flxPopUpTitle = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"clipBounds": true,
"height": "20%",
"id": "flxPopUpTitle",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "0dp",
"skin": "CopyslFbox2",
"top": "0dp",
"width": "100%",
"zIndex": 1
}, {}, {});
flxPopUpTitle.setDefaultUnit(kony.flex.DP);
var lblHeader = new kony.ui.Label({
"centerX": "50%",
"centerY": "50%",
"id": "lblHeader",
"isVisible": true,
"skin": "CopyCopyslLabel003bd8bf414dc4f",
"text": "Enable Touch ID",
"width": kony.flex.USE_PREFFERED_SIZE,
"zIndex": 10
}, {
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"textCopyable": false,
"wrapping": constants.WIDGET_TEXT_WORD_WRAP
});
flxPopUpTitle.add(lblHeader);
var flxEnableTouchIdPopupLine = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"clipBounds": true,
"height": "2px",
"id": "flxEnableTouchIdPopupLine",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "0dp",
"skin": "CopysknFlxLineBg1",
"top": "20%",
"width": "100%",
"zIndex": 1
}, {}, {});
flxEnableTouchIdPopupLine.setDefaultUnit(kony.flex.DP);
flxEnableTouchIdPopupLine.add();
var imgEnableTouchIDIcon = new kony.ui.Image2({
"centerX": "50%",
"centerY": "40%",
"height": "60dp",
"id": "imgEnableTouchIDIcon",
"isVisible": true,
"skin": "CopyslImage5",
"src": "touchid.png",
"width": "60dp",
"zIndex": 10
}, {
"imageScaleMode": constants.IMAGE_SCALE_MODE_MAINTAIN_ASPECT_RATIO,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {});
var lblMessage = new kony.ui.Label({
"centerX": "50%",
"centerY": "65%",
"id": "lblMessage",
"isVisible": true,
"skin": "CopyCopyslLabel0145ec6291e6a43",
"text": "You can use touch ID to Login",
"width": kony.flex.USE_PREFFERED_SIZE,
"zIndex": 10
}, {
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"textCopyable": false,
"wrapping": constants.WIDGET_TEXT_WORD_WRAP
});
flxEnableTouchIDPopup.add(flxButtons, flxPopUpTitle, flxEnableTouchIdPopupLine, imgEnableTouchIDIcon, lblMessage);
var flxTouchIDPopup = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"bottom": "27%",
"centerX": "50%",
"centerY": "50%",
"clipBounds": true,
"height": "36%",
"id": "flxTouchIDPopup",
"isVisible": false,
"layoutType": kony.flex.FREE_FORM,
"left": "0%",
"skin": "CopysknFlxMobFFFFFFOp1",
"top": "0%",
"width": "89%",
"zIndex": 10
}, {}, {});
flxTouchIDPopup.setDefaultUnit(kony.flex.DP);
var flxTouchIDButtons = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"bottom": "0%",
"clipBounds": true,
"height": "25%",
"id": "flxTouchIDButtons",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "0dp",
"skin": "CopyslFbox2",
"width": "100%",
"zIndex": 1
}, {}, {});
flxTouchIDButtons.setDefaultUnit(kony.flex.DP);
var btnTouchCancel = new kony.ui.Button({
"focusSkin": "CopyCopyslButtonGlossRed1",
"height": "100%",
"id": "btnTouchCancel",
"isVisible": true,
"left": "0%",
"onClick": controller.AS_Button_fe871ac9bd194551b75bf1f10044f309,
"skin": "CopysknBtnFA1",
"text": "Cancel",
"top": "0%",
"width": "100%",
"zIndex": 10
}, {
"contentAlignment": constants.CONTENT_ALIGN_CENTER,
"displayText": true,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"showProgressIndicator": true
});
flxTouchIDButtons.add(btnTouchCancel);
var flxTouchIDPopUpTitle = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"clipBounds": true,
"height": "25%",
"id": "flxTouchIDPopUpTitle",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "0dp",
"skin": "CopyslFbox2",
"top": "0dp",
"width": "100%",
"zIndex": 1
}, {}, {});
flxTouchIDPopUpTitle.setDefaultUnit(kony.flex.DP);
var lblTouchHeader = new kony.ui.Label({
"centerX": "50%",
"centerY": "50%",
"id": "lblTouchHeader",
"isVisible": true,
"skin": "CopyCopyslLabel0749e4ce9707f41",
"text": "Touch ID",
"width": kony.flex.USE_PREFFERED_SIZE,
"zIndex": 10
}, {
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"textCopyable": false,
"wrapping": constants.WIDGET_TEXT_WORD_WRAP
});
flxTouchIDPopUpTitle.add(lblTouchHeader);
var flxTouchIDPopupLine = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"clipBounds": true,
"height": "2px",
"id": "flxTouchIDPopupLine",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"left": "0dp",
"skin": "CopysknFlxLineBg1",
"top": "25%",
"width": "100%",
"zIndex": 1
}, {}, {});
flxTouchIDPopupLine.setDefaultUnit(kony.flex.DP);
flxTouchIDPopupLine.add();
var imgTouchIDPopupIcon = new kony.ui.Image2({
"centerX": "50%",
"centerY": "40%",
"height": "50dp",
"id": "imgTouchIDPopupIcon",
"isVisible": true,
"skin": "CopyslImage5",
"src": "touchid.png",
"width": "50dp",
"zIndex": 10
}, {
"imageScaleMode": constants.IMAGE_SCALE_MODE_MAINTAIN_ASPECT_RATIO,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {});
var lblTouchMessage = new kony.ui.Label({
"centerX": "50%",
"centerY": "65%",
"id": "lblTouchMessage",
"isVisible": true,
"skin": "CopyCopyslLabel00f384d7e7e3347",
"text": "Use Touch ID to Login",
"width": kony.flex.USE_PREFFERED_SIZE,
"zIndex": 10
}, {
"contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {
"textCopyable": false,
"wrapping": constants.WIDGET_TEXT_WORD_WRAP
});
flxTouchIDPopup.add(flxTouchIDButtons, flxTouchIDPopUpTitle, flxTouchIDPopupLine, imgTouchIDPopupIcon, lblTouchMessage);
flxPopups.add(flxEnableTouchIDPopup, flxTouchIDPopup);
flxLogin.add(flxBottomContainer, flxlogo, flxTouchId, flxSocialLogin, flxCredentials, flxPopups);
var flxIdentity = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"centerX": "50%",
"centerY": "50%",
"clipBounds": true,
"height": "100%",
"id": "flxIdentity",
"isVisible": false,
"layoutType": kony.flex.FREE_FORM,
"left": "0%",
"top": "0%",
"width": "100%",
"zIndex": 10
}, {}, {});
flxIdentity.setDefaultUnit(kony.flex.DP);
var brwsrIdentity = new kony.ui.Browser({
"detectTelNumber": true,
"enableZoom": false,
"height": "100%",
"htmlString": "Please wait !!\n",
"id": "brwsrIdentity",
"isVisible": true,
"left": "0%",
"top": "0%",
"width": "100%",
"zIndex": 100
}, {}, {});
var flxClose = new kony.ui.FlexContainer({
"autogrowMode": kony.flex.AUTOGROW_NONE,
"clipBounds": true,
"height": "30dp",
"id": "flxClose",
"isVisible": true,
"layoutType": kony.flex.FREE_FORM,
"onClick": controller.AS_FlexContainer_c86710f8599b4a1f8ef335ad57a4a707,
"right": "2%",
"top": "0.50%",
"width": "30dp",
"zIndex": 101
}, {}, {});
flxClose.setDefaultUnit(kony.flex.DP);
var imgClose = new kony.ui.Image2({
"height": "100%",
"id": "imgClose",
"isVisible": true,
"left": "0%",
"src": "clear_input_icon.png",
"top": "0%",
"width": "100%",
"zIndex": 101
}, {
"imageScaleMode": constants.IMAGE_SCALE_MODE_MAINTAIN_ASPECT_RATIO,
"padding": [0, 0, 0, 0],
"paddingInPixel": false
}, {});
flxClose.add(imgClose);
flxIdentity.add(brwsrIdentity, flxClose);
login.add(flxLogin, flxIdentity);
return login;
}
})
|
/**
* The bounds for the areas of the Header
* Offset from the start of header, not memory address, e.g. 0x04 would actually be 0x0104
*/
const bounds = {
entry: [0x00, 0x04],
logo: [0x04, 0x34],
title: [0x34, 0x44],
publisher: [0x44, 0x46],
superGameBoy: [0x46, 0x47],
type: [0x47, 0x48],
romSize: [0x48, 0x49],
ramSize: [0x49, 0x4A],
destination: [0x4A, 0x4B],
publisherOld: [0x4B, 0x4C],
romVersion: [0x4C, 0x4D],
headerChecksum: [0x4D, 0x4E],
globalChecksum: [0x4E, 0x50],
};
export const getTitle = header => String.fromCharCode(...header.subarray(...bounds.logo));
export const isSGB = header => !!header[bounds.superGameBoy[0]];
export const getRomSize = header => header[bounds.romSize[0]];
export const getRamSize = header => header[bounds.ramSize[0]];
export const getDestination = header => header[bounds.destination[0]] === 1 ? 'Japan' : 'International';
// TODO: align this as new publisher is two-bytes
export const getPublisher = header => header[bounds.publisher[0]] || header[bounds.publisherOld[0]];
export const getRomVersion = header => header[bounds.romVersion[0]];
export default header => ({
title: getTitle(header),
superGameBoy: isSGB(header),
romSize: getRomSize(header),
ramSize: getRamSize(header),
destination: getDestination(header),
publisher: getPublisher(header),
version: getRomVersion(header),
});
|
import React, { Component } from 'react'
import { Button, Col, Container, Form, FormGroup, FormText, Label, Input, Row } from 'reactstrap'
import { createUrl } from '../../api/utils'
import { Intro } from '../Homepage'
class FinishSteam extends Component {
state = {
acceptInvite: null,
}
componentDidMount() {
this.setState({
acceptInvite: localStorage.getItem('acceptInvite')
})
}
render() {
const {
match: { params: { partial_token } },
} = this.props
const { acceptInvite } = this.state
return (
<Container>
<Intro>
<h1>Finish Signup</h1>
</Intro>
<Row>
<Col sm='12' md={{ size: '6', offset: '3' }} lg={{ size: '4', offset: '4' }}>
<Form action={createUrl('/complete/steam/?next=/social-redirect/my-teams')} method="post">
<input type="hidden" name="partial_token" value={partial_token} />
{acceptInvite && <input type="hidden" name="accept_invite" value={acceptInvite} />}
<FormGroup>
<Label for='email'>Email Address</Label>
<Input id='email' type='email' name='email' />
<FormText>
Your email is private. You can change your email preferences from your settings. We do
not share or sell your personal information.
</FormText>
</FormGroup>
<div className='text-center'>
<Button color='success'>Submit</Button>
</div>
</Form>
</Col>
</Row>
</Container>
)
}
}
export default FinishSteam
|
// Module
// ------
// A simple module system, used to create privacy and encapsulation in
// Marionette applications
Marionette.Module = function(moduleName, app, options){
this.moduleName = moduleName;
this.options = _.extend({}, this.options, options);
// Allow for a user to overide the initialize
// for a given module instance.
this.initialize = options.initialize || this.initialize;
// Set up an internal store for sub-modules.
this.submodules = {};
this._setupInitializersAndFinalizers();
// Set an internal reference to the app
// within a module.
this.app = app;
// By default modules start with their parents.
this.startWithParent = true;
// Setup a proxy to the trigger method implementation.
this.triggerMethod = Marionette.triggerMethod;
if (_.isFunction(this.initialize)){
this.initialize(this.options, moduleName, app);
}
};
Marionette.Module.extend = Marionette.extend;
// Extend the Module prototype with events / listenTo, so that the module
// can be used as an event aggregator or pub/sub.
_.extend(Marionette.Module.prototype, Backbone.Events, {
// Initialize is an empty function by default. Override it with your own
// initialization logic when extending Marionette.Module.
initialize: function(){},
// Initializer for a specific module. Initializers are run when the
// module's `start` method is called.
addInitializer: function(callback){
this._initializerCallbacks.add(callback);
},
// Finalizers are run when a module is stopped. They are used to teardown
// and finalize any variables, references, events and other code that the
// module had set up.
addFinalizer: function(callback){
this._finalizerCallbacks.add(callback);
},
// Start the module, and run all of its initializers
start: function(options){
// Prevent re-starting a module that is already started
if (this._isInitialized){ return; }
// start the sub-modules (depth-first hierarchy)
_.each(this.submodules, function(mod){
// check to see if we should start the sub-module with this parent
if (mod.startWithParent){
mod.start(options);
}
});
// run the callbacks to "start" the current module
this.triggerMethod("before:start", options);
this._initializerCallbacks.run(options, this);
this._isInitialized = true;
this.triggerMethod("start", options);
},
// Stop this module by running its finalizers and then stop all of
// the sub-modules for this module
stop: function(){
// if we are not initialized, don't bother finalizing
if (!this._isInitialized){ return; }
this._isInitialized = false;
Marionette.triggerMethod.call(this, "before:stop");
// stop the sub-modules; depth-first, to make sure the
// sub-modules are stopped / finalized before parents
_.each(this.submodules, function(mod){ mod.stop(); });
// run the finalizers
this._finalizerCallbacks.run(undefined,this);
// reset the initializers and finalizers
this._initializerCallbacks.reset();
this._finalizerCallbacks.reset();
Marionette.triggerMethod.call(this, "stop");
},
// Configure the module with a definition function and any custom args
// that are to be passed in to the definition function
addDefinition: function(moduleDefinition, customArgs){
this._runModuleDefinition(moduleDefinition, customArgs);
},
// Internal method: run the module definition function with the correct
// arguments
_runModuleDefinition: function(definition, customArgs){
// If there is no definition short circut the method.
if (!definition){ return; }
// build the correct list of arguments for the module definition
var args = _.flatten([
this,
this.app,
Backbone,
Marionette,
Marionette.$, _,
customArgs
]);
definition.apply(this, args);
},
// Internal method: set up new copies of initializers and finalizers.
// Calling this method will wipe out all existing initializers and
// finalizers.
_setupInitializersAndFinalizers: function(){
this._initializerCallbacks = new Marionette.Callbacks();
this._finalizerCallbacks = new Marionette.Callbacks();
}
});
// Type methods to create modules
_.extend(Marionette.Module, {
// Create a module, hanging off the app parameter as the parent object.
create: function(app, moduleNames, moduleDefinition){
var module = app;
// get the custom args passed in after the module definition and
// get rid of the module name and definition function
var customArgs = slice.call(arguments);
customArgs.splice(0, 3);
// Split the module names and get the number of submodules.
// i.e. an example module name of `Doge.Wow.Amaze` would
// then have the potential for 3 module definitions.
moduleNames = moduleNames.split(".");
var length = moduleNames.length;
// store the module definition for the last module in the chain
var moduleDefinitions = [];
moduleDefinitions[length-1] = moduleDefinition;
// Loop through all the parts of the module definition
_.each(moduleNames, function(moduleName, i){
var parentModule = module;
module = this._getModule(parentModule, moduleName, app, moduleDefinition);
this._addModuleDefinition(parentModule, module, moduleDefinitions[i], customArgs);
}, this);
// Return the last module in the definition chain
return module;
},
_getModule: function(parentModule, moduleName, app, def, args){
var options = _.extend({}, def);
var ModuleClass = this.getClass(def);
// Get an existing module of this name if we have one
var module = parentModule[moduleName];
if (!module){
// Create a new module if we don't have one
module = new ModuleClass(moduleName, app, options);
parentModule[moduleName] = module;
// store the module on the parent
parentModule.submodules[moduleName] = module;
}
return module;
},
// ## Module Classes
//
// Module classes can be used as an alternative to the define pattern.
// The extend function of a Module is identical to the extend functions
// on other Backbone and Marionette classes.
// This allows module lifecyle events like `onStart` and `onStop` to be called directly.
getClass: function(moduleDefinition) {
var ModuleClass = Marionette.Module;
if (!moduleDefinition) {
return ModuleClass;
}
// If all of the module's functionality is defined inside its class,
// then the class can be passed in directly. `MyApp.module("Foo", FooModule)`.
if (moduleDefinition.prototype instanceof ModuleClass) {
return moduleDefinition;
}
return moduleDefinition.moduleClass || ModuleClass;
},
// Add the module definition and add a startWithParent initializer function.
// This is complicated because module definitions are heavily overloaded
// and support an anonymous function, module class, or options object
_addModuleDefinition: function(parentModule, module, def, args){
var fn = this._getDefine(def);
var startWithParent = this._getStartWithParent(def, module);
if (fn){
module.addDefinition(fn, args);
}
this._addStartWithParent(parentModule, module, startWithParent);
},
_getStartWithParent: function(def, module) {
var swp;
if (_.isFunction(def) && (def.prototype instanceof Marionette.Module)) {
swp = module.constructor.prototype.startWithParent;
return _.isUndefined(swp) ? true : swp;
}
if (_.isObject(def)){
swp = def.startWithParent;
return _.isUndefined(swp) ? true : swp;
}
return true;
},
_getDefine: function(def) {
if (_.isFunction(def) && !(def.prototype instanceof Marionette.Module)) {
return def;
}
if (_.isObject(def)){
return def.define;
}
return null;
},
_addStartWithParent: function(parentModule, module, startWithParent) {
module.startWithParent = module.startWithParent && startWithParent;
if (!module.startWithParent || !!module.startWithParentIsConfigured){
return;
}
module.startWithParentIsConfigured = true;
parentModule.addInitializer(function(options){
if (module.startWithParent){
module.start(options);
}
});
}
});
|
/* Func:
Kind of like the JQuery's Deferreds. But with some extra funtions to track down the status of those deferred tasks, which is convinent for debugging.
Properties:
[ Public ]
<NUM> FLAG_FUTURE_NOT_YET = The flag marking the future is not yet settled
<NUM> FLAG_FUTURE_IS_OK = The flag marking the future is settled with the OK status
<NUM> FLAG_FUTURE_IS_ERR = The flag marking the future is settled with the error status
[ Private ]
<CLS> _cls_Future_Queue_Ctrl = the controller controlling the jobs queued up to do in the settled future
<CLS> _cls_Future_During_Ctrl = the controller controlling the jobs to do as the unsettled future would like to inform something
<CLS> _cls_Future = The so-called Future obj to defer and schedule the future jobs' execution after the prerequisite job ends, kind of like the jQuery's Deferred.
<CLS> _cls_Future_Swear = The swear from one Future obj. We can use it to make the future obj swear to do sth after the future arrives. The swear obj has no right to settle the future so we can give it to outsiders. Let outsiders access the future obj without the ability to settle/interfere the future, kind of like jQuery's promise obj.
<OBJ> _futures = the table to storing the future objs
Methods:
[ Private ]
> _logErr : Log error
> _define : Define constant property on one object
[ Public ]
> exist : Check if the specified Future obj is stored and made before.
> dump : Dump the array of names of Future objs. With the method, we could find out Future objs which are settled or not.
> newOne : New one Future obj. Future will also store the generated future obj. Thus we would be able to call Future.dump to track every Future obj's status.
> rmOne : Remvoe one Future obj from Future's Future pool (Better remove after the future is settled so as to be able to track down unsettled future).
> upon : Return one new swear obj of one future. This future, the dependent future, depends upon other prior futures to settle itself.
Only all the prior futures upon which this dependent future depends are approved, it would be approved, otherwise, it would be disapproved.
kind of like jQuery's when but different in the following manners:
The dependent future wouldn't be settled even though it knows it must be disapproved because there is one prior future which had been disapporved. the dependent future would be settled only upon all the prior futures are settled.
When the dependent future is approved, disapproved or informed, the jobs(callbacks) chained onto it would be passed arguments which come from the prior futures.
These arguments are passed in the order of the prior future being added. For example, the dependent future is waiting for the future A, the future B and the future C.
Case 1: the future A is approved with no argument. The future B is approved with 1 argument. The future C is approved with 2 arguments.
The depenedent future would be approved and pass 3 arguments to callbacks chained to it.
The 1st argument is an empty array since the future A has no argument.
The 2nd argument is an array storing the only one argument coming from the future B.
The 3rd argument is an array storing the 2 arguments coming from the future C.
Case 2: the future A is disapproved with no argument. The future B is disapporved with 1 argument. The future C is approved with 2 arguments.
The depenedent future would be disapproved and pass 3 arguments to callbacks chained to it.
The 1st argument is an empty array since the future A has no argument.
The 2nd argument is an array storing the only one argument coming from the future B.
The 3rd argument is undefined since the future C is approved and has no arguments for the disapproved status.
Case 3: the future A informs with 1 argument.
The dependent future would be informed and then pass 3 arguments to inform callbacks chained to it.
The 1st argument is an array storing the only one argument coming from the future A.
The 2nd and the 3rd argument is both undefined since the future B and the future C has nothing to do with this.
*/
var Future = (function () {
/* Arg:
<STR> The error message
*/
function _logErr(msg) {
if (typeof Error == "function") {
try {
throw new Error;
} catch (e) {
var stack = "";
if (typeof e.stack == "string") {
stack = e.stack.replace("Error", "");
}
msg += " error " + stack;
}
}
if (console.error) {
console.error(msg);
} else {
console.log(msg);
}
}
/* Arg:
<OBJ> obj = the object on which the constant property is defined
<STR> propName = the constant property name
<*> propValue = the constant property value
<BOO> [enumerable] = true to make the constant property enumerable on the object
Return:
@ OK: <*> The defined value
@ NG: undefined
*/
function _define(obj, propName, propValue, enumerable) {
var defined;
if (obj instanceof Object && propName && typeof propName == "string") {
if (obj[propName] === undefined) {
try {
Object.defineProperty(
obj,
propName,
{
value : propValue,
writable : false,
configurable : false,
enumerable : (enumerable === true)
}
);
} catch (e) {
obj[propName] = propValue;
}
}
defined = obj[propName];
}
return defined;
}
/* Properties:
[ Public ]
<NUM> FLAG_QUEUE_TYPE_OK = the flag marking the type of queue is for jobs which shall be run in the ok future
<NUM> FLAG_QUEUE_TYPE_ERR = the flag marking the type of queue is for jobs which shall be run in the error future
<NUM> FLAG_QUEUE_TYPE_ANYWAY = the flag marking the type of queue is for jobs which shall be run disregarding the ok or error future
<STR> FLAG_CALLBACK_TYPE_PROP_NAME = the name of property in queued callback which indicates the type of queued callback
[ Private ]
<ARR> __queue = the queue of jobs to call when the future is settled. The element inside are callbacks for jobs. Each callback would be added one property which bears the value of this::FLAG_QUEUE_TYPE_* to indicate the type of callback
Methods:
[ Public ]
> setVarsForQueue : Set the vars to be passed into the queued callbacks once they are invoked. Only can set once.
> setContextForQueue : Set the this obj used when invoking jobs. Only can set once.
> push : Add one job(callback) into the queue.
> flush : Call the queued callbacks in the order they are pushed. After flushing the queue would be empty.
*/
function _cls_Future_Queue_Ctrl() {
/* Properties:
[ Public ]
<ARR> argsForOK = the array of arguments for the jobs queued for ok
<ARR> argsForERR = the array of arguments for the jobs queued for error
<OBJ> contextForOK, contextForERR = the this obj used when invoking jobs; Default is window.
*/
var __queue = []; {
__queue.argsForOK = [];
__queue.contextForOK = window;
__queue.argsForERR = [];
__queue.contextForERR = window;
}
/* Arg:
<STR> queueType = the queue type. Only accept the type of this::FLAG_QUEUE_TYPE_OK/ERR
<ARR> vars = the vars to passed to the queued callbacks once they are invoked
Return:
@ OK: true
@ NG: false
*/
this.setVarsForQueue = function (queueType, vars) {
if (vars instanceof Array) {
if (queueType == this.FLAG_QUEUE_TYPE_OK && __queue.argsForOK.length <= 0) {
__queue.argsForOK = vars.slice(0);
return true;
} else if (queueType == this.FLAG_QUEUE_TYPE_ERR && __queue.argsForERR.length <= 0) {
__queue.argsForERR = vars.slice(0);
return true;
}
}
return false;
}
/* Arg:
<STR> queueType = the queue type. Only accept the type of this::FLAG_QUEUE_TYPE_OK/ERR
<OBJ> context = the this obj used when invoking jobs, cannot be null or undefined
Return:
@ OK: true
@ NG: false
*/
this.setContextForQueue = function (queueType, context) {
if (context !== null && context !== undefined) {
if (queueType == this.FLAG_QUEUE_TYPE_OK && __queue.contextForOK === window) {
__queue.contextForOK = context;
return true;
} else if (queueType == this.FLAG_QUEUE_TYPE_ERR && __queue.contextForERR === window) {
__queue.contextForERR = context;
return true;
}
}
return false;
}
/* Arg:
<STR> queueType = the queue type
<FN|ARR> callbacks = the function to push, if multiple put in one array
Return:
<NUM> the numbers of jobs queued (including both for ok and for error)
*/
this.push = function (queueType, callbacks) {
var callback,
callbacksArray = (callbacks instanceof Array) ? callbacks : [callbacks],
type = (queueType == this.FLAG_QUEUE_TYPE_OK || queueType == this.FLAG_QUEUE_TYPE_ERR || queueType == this.FLAG_QUEUE_TYPE_ANYWAY) ? queueType : null;
if (type !== null) {
callback = callbacksArray.shift();
while (typeof callback == "function") {
_define(callback, this.FLAG_CALLBACK_TYPE_PROP_NAME, type, false);
__queue.push(callback);
callback = callbacksArray.shift();
}
}
return __queue.length;
}
/* Arg:
<STR> queueType = the type of queue to flush. Only accept the type of this::FLAG_QUEUE_TYPE_OK/ERR
*/
this.flush = function (queueType) {
var type = (queueType == this.FLAG_QUEUE_TYPE_OK || queueType == this.FLAG_QUEUE_TYPE_ERR) ? queueType : null;
if (type !== null) {
var callback,
argsForQueue,
contextForQueue;
if (type == this.FLAG_QUEUE_TYPE_OK) {
argsForQueue = __queue.argsForOK;
contextForQueue = __queue.contextForOK;
} else if (type == this.FLAG_QUEUE_TYPE_ERR) {
argsForQueue = __queue.argsForERR;
contextForQueue = __queue.contextForERR;
}
callback = __queue.shift();
while (typeof callback == "function") {
if ( callback[this.FLAG_CALLBACK_TYPE_PROP_NAME] == type
|| callback[this.FLAG_CALLBACK_TYPE_PROP_NAME] == this.FLAG_QUEUE_TYPE_ANYWAY
) {
try {
callback.apply(contextForQueue, argsForQueue);
} catch (err) {
_logErr("" + err);
}
}
callback = __queue.shift();
}
}
}
}; {
_define(_cls_Future_Queue_Ctrl.prototype, "FLAG_QUEUE_TYPE_OK", 0, false);
_define(_cls_Future_Queue_Ctrl.prototype, "FLAG_QUEUE_TYPE_ERR", 1, false);
_define(_cls_Future_Queue_Ctrl.prototype, "FLAG_QUEUE_TYPE_ANYWAY", 2, false);
_define(_cls_Future_Queue_Ctrl.prototype, "FLAG_CALLBACK_TYPE_PROP_NAME", "_CALLBACK_TYPE", false);
}
/* Properties:
[ Private ]
<ARR> __durings = the jobs(callbacks) to do as the unsettled future would like to inform something
Methods:
[ Public ]
> push : Push one job
> loop : Loop through and call the callbacks in this::__durings
*/
function _cls_Future_During_Ctrl() {
var __durings = [];
/* Arg:
<FN> callback = the callback to push into this::__durings
Return:
<NUM> The number of jobs in this::__durings
*/
this.push = function (callback) {
if (typeof callback == "function") {
__durings.push(callback);
}
return __durings.length;
}
/* Arg:
<OBJ> context = the this obj used when invoking jobs
<ARR> args = the arguments to pass into the job when invoking each job
*/
this.loop = function (context, args) {
if (args instanceof Array) {
for (var i = 0; i < __durings.length; i++) {
try {
__durings[i].apply(
(context === null || context === undefined) ? window : context,
args
);
} catch (err) {
_logErr("" + err);
}
}
}
}
}
/* Properties:
[ Private ]
<STR> __name = the name of this future obj
<NUM> __andThenCount = the counts how many this.andThen call
<STR> __status = the stauts, could be
@ The prerequsite job is done successfully: Future.FLAG_FUTURE_IS_OK
@ The prerequsite job is done unsuccessfully: Future.FLAG_FUTURE_IS_ERR
@ The prerequsite job is done not yet: Future.FLAG_FUTURE_NOT_YET
<OBJ> __queueCtrl = the instance of Future::_cls_Future_Queue_Ctrl
<OBJ> __duringCtrl = the instance of Future::_cls_Future_During_Ctrl
Methods:
[ Private ]
> __flushQueue : Call this::__queueCtrl to flush the corresponding jobs deferred into the future if this future is settled. Do not call this::__queueCtrl directly to flush, instead, use this method to prevent from flushing the job queue while the future is not yet settled.
[ Public ]
> getName : Get the name of future
> report : Report the future obj status
> next : Add one job and execute the job once the future status is settled with OK, kind of like jQuery's done
> fall : Add one job and execute the job once the future status is settled with error, kind of like jQuery's fail
> anyway : Add one job and execute the job anyway no matter that the future is settled with OK or error, kind of like jQuery's always
> during : Add one job and execute the job during that the future is still ongoing and would like to inform something, kind of like jQuery's progress
> andThen : Add jobs and execute the jobs once the future status is settled.
Calling this method gives us a chance to make the jobs after this method chained to another future/swear obj.
According to the returned value of the called callback, there could be four cases:
- Case 1: the ok/error and-then callback returns one future or one swear obj different from the original one so the future jobs chained after this andThen call would be tied to this new successor future/swear obj and the arguments for jobs in the successor's queue would depend on the successor's arguments settled with.
- Case 2: the and-then callback returns the original future obj so the successor would be the original one still and the arguments for jobs in the successor's queue would be arguments passed along the original one's queue.
- Case 3: the and-then callbacks returns one array of arguments but future obj so the successor would be the original one still and that returned array would be the arguments for jobs in the successor's queue.
- Case 4: No and-then callbacks could be called so the successor would be the original one still and the arguments for jobs in the successor's queue would be arguments passed along the original one's queue.
- Case 5: The during and-then callbacks have been called and return other future/swear obj. In this case, the jobs chained after the andThen method have multiple future to chose so the race among futures begins.
The following chained jobs will be invoked in the future which is settled first.
For example, two during callbacks generates two futures, the ok callback keeps the original future and the error callback generates another new future.
If one of the futures from the during callbacks is settled first, the chained jobs are invoked in this future.
Or if the ok callback is called first, the chained jobs are invoked in the original future.
Or if the error callback is called first, the chained jobs are invoked in the first-settled one among the remaining three futures (two from the during callbacks, one from the error callback).
This method is kind of like jQuery's then.
> inform : Inform about the future's progress. Calling this method will invoke the during callbacks in the order they were added. The during callbacks won't be cleared after invoked so they are able to receive the next notification. No effect as the future is settled, kind of like jQuery's notify. Unlike jQuery's notify, however, the during callback added later is unable to receive the notification informed before, which is possible in jQuery's notify.
> informWith : Inform about the future's progress with the given context(this obj), kind of like jQuery's notifyWith
> approve : Approve the future. Calling this method will invoke the callbacks for the ok future in the order they were added. The callbacks are cleared after invoked. This is to settle the future with the OK status, kind of like jQuery's resolve
> approveWith : Approve the future with the given context(this obj), kind of like jQuery's resolveWith
> disapprove : Disapprove the future. Calling this method will invoke the callbacks for the error future in the order they were added. The callbacks are cleared after invoked. This is to settle the future with the Error status, kind of like jQuery's reject
> disapproveWith : Disapprove the future with the given context(this obj), kind of like jQuery's rejectWith
> swear : Get the swear obj assocciated with this future obj, kind of like jQuery's promise
------------------------------------------------------------------------------------------------
Arg:
<STR> name = the name of the future obj
*/
function _cls_Future(name) {
var __name = name,
__swear = null,
__andThenCount = 0,
__status = Future.FLAG_FUTURE_NOT_YET,
__queueCtrl = new _cls_Future_Queue_Ctrl,
__duringCtrl = new _cls_Future_During_Ctrl;
/*
*/
function __flushQueue() {
if (Future.FLAG_FUTURE_IS_OK === __status) {
__queueCtrl.flush(__queueCtrl.FLAG_QUEUE_TYPE_OK);
} else if (Future.FLAG_FUTURE_IS_ERR === __status) {
__queueCtrl.flush(__queueCtrl.FLAG_QUEUE_TYPE_ERR);
}
}
/* Return:
<STR> the name of future
*/
this.getName = function () {
return __name;
}
/* Return: Refer to Private::__status
*/
this.report = function () {
if ( __status !== Future.FLAG_FUTURE_NOT_YET
&& __status !== Future.FLAG_FUTURE_IS_OK
&& __status !== Future.FLAG_FUTURE_IS_ERR
) {
// Sth wrong! the status is crupt so correct it.
_logErr("The unknown future status : " + __status);
__status = Future.FLAG_FUTURE_NOT_YET;
}
return __status;
}
/* Arg:
<FN|ARR> callbacks = the jobs to do in the OK future; If multiple, put in one array
Return:
<OBJ> This future
*/
this.next = function (callbacks) {
if (typeof callbacks == "function" || callbacks instanceof Array) {
__queueCtrl.push(__queueCtrl.FLAG_QUEUE_TYPE_OK, callbacks);
__flushQueue();
}
return this;
}
/* Arg:
<FN|ARR> callbacks = the jobs to do in the error future; If multiple, put in one array
Return:
<OBJ> This future
*/
this.fall = function (callbacks) {
if (typeof callbacks == "function" || callbacks instanceof Array) {
__queueCtrl.push(__queueCtrl.FLAG_QUEUE_TYPE_ERR, callbacks);
__flushQueue();
}
return this;
}
/* Arg:
<FN|ARR> callbacks = the job to do in the future; If multiple, put in one array
Return:
<OBJ> This future
*/
this.anyway = function (callbacks) {
if (typeof callbacks == "function" || callbacks instanceof Array) {
__queueCtrl.push(__queueCtrl.FLAG_QUEUE_TYPE_ANYWAY, callbacks);
__flushQueue();
}
return this;
}
/* Arg:
<FN|ARR> callbacks = the job to add; If multiple, put in one array
Return:
<OBJ> This future
*/
this.during = function (callbacks) {
var fns = (callbacks instanceof Array) ? callbacks : [callbacks];
for (var i = 0; i < fns.length; i++) {
__duringCtrl.push(fns[i]);
}
return this;
}
/* Arg:
<FN> [okCallback] = the job to do in the OK future
<FN> [errCallback] = the job to do in the error future
<FN> [duringCallback] = the job to receive the notification from future
Return:
<OBJ> one instance of Future::_cls_Future_Swear.
However the execution of jobs chained after this method does not depend on this returned swear obj but the returned value by the input callback
*/
this.andThen = function (okCallback, errCallback, duringCallback) {
// New one future obj for the and-then jobs. This future obj is kind of like an mediator future.
var andThenFuture = Future.newOne(__name + "::andThen_" + __andThenCount++);
/* Func:
Mediate the jobs chained after calling this andThen methods to go to which future obj's jobs queue
Properties:
[ Private ]
<OBJ> andThenFuture = The instance of _cls_Future which its _cls_Future_Swear obj will be returned outside.
<OBJ> originalFuture = The current instance of _cls_Future
<OBJ> originalSwear = The current instance of _cls_Future_Swear of the current instance of _cls_Future
<FN> okCallback, errCallback, duringCallback = The callbacks passed into this andThen method
<OBJ> newFuturePool = The pool managing the future/swear objs returned by calling this::okCallback/errCallback/duringCallback
Methods:
[ Private ]
> chainAndThenFutureOn : Chain the future jobs after this and-then onto the future/swear obj decided by the calling of callbacks
[ Public ]
> callAndThenCallback : Call the callbacks passed into the andThen method
*/
var futureMediator = (function (andThenFuture, originalFuture, okCallback, errCallback, duringCallback) {
/* Properties:
[ Private ]
<ARR> __addeds = The added the future/swear objs
Methods:
[ Public ]
> add : Add one future/swear obj if not in this::__addeds
> exist : Check the existence of one future/swear obj
*/
var newFuturePool = (function () {
var __addeds = [];
return {
/* Arg:
<OBJ> f = One future/swear obj
Return:
@ OK: true
@ NG: false
*/
add : function (f) {
if ( (f instanceof _cls_Future || f instanceof _cls_Future_Swear)
&& !this.exist(f)
) {
__addeds.push(f);
return true;
}
return false;
},
/* Arg:
<OBJ> f = One future/swear obj
Return:
@ In this::__addeds: true
@ Not in this::__addeds: false
*/
exist : function (f) {
for (var i = 0; i < __addeds.length; i++) {
if (__addeds[i] === f) {
return true;
}
}
return false;
}
}}());
/* Properties:
[ Public ]
<BOO> [useNewArgs] = true means taking this::newArgs as the arguments, otherwise, taking the default arguments
<*|ARR> [newArgs] = The new arguments to pass into the following jobs
--------------------------------------
Arg:
<OBJ> baseFuture = The base future onto which the and-then future is chained; could be one future/swear obj
<STR> cmd = the command to chain
*/
function chainAndThenFutureOn(baseFuture, cmd) {
switch (cmd) {
case "approve":
baseFuture.next(function () {
var args = chainAndThenFutureOn.useNewArgs ? chainAndThenFutureOn.newArgs : Array.prototype.slice.call(arguments, 0);
andThenFuture.approveWith(this, args);
});
return;
case "disapprove":
baseFuture.fall(function () {
var args = chainAndThenFutureOn.useNewArgs ? chainAndThenFutureOn.newArgs : Array.prototype.slice.call(arguments, 0);
andThenFuture.disapproveWith(this, args);
});
return;
case "inform":
baseFuture.during(function () {
var args = chainAndThenFutureOn.useNewArgs ? chainAndThenFutureOn.newArgs : Array.prototype.slice.call(arguments, 0);
andThenFuture.informWith(this, args);
});
return;
}
}
chainAndThenFutureOn.newArgs = [];
chainAndThenFutureOn.useNewArgs = false;
return {
/* Arg:
<STR> predecessorStatus = the predecessor future obj's status
<OBJ> contextForAndThen = the context(this obj) in which the predecessor's callbacks ar invoked
<ARR> varsForAndThen = the vars passed along the predecessor's queue and would be passed to the and-then callbacks
*/
callAndThenCallback : function (predecessorStatus, contextForAndThen, varsForAndThen) {
var newFuture,
callType,
callResultCase,
callResultValue,
callbacks = {
okCallback : okCallback,
errCallback : errCallback,
duringCallback : duringCallback
};
switch (predecessorStatus) {
case Future.FLAG_FUTURE_IS_OK:
callType = "okCallback";
break;
case Future.FLAG_FUTURE_IS_ERR:
callType = "errCallback";
break;
case Future.FLAG_FUTURE_NOT_YET:
callType = "duringCallback";
break;
}
// Let's call the desired callback to
// decide the future onto which the future jobs after this and-then are chained
// and decide the arguments passed into the future jobs
chainAndThenFutureOn.newArgs = [];
chainAndThenFutureOn.useNewArgs = false;
if (typeof callbacks[callType] == "function") {
callResultValue = callbacks[callType].apply(contextForAndThen, varsForAndThen);
if (callResultValue instanceof _cls_Future || callResultValue instanceof _cls_Future_Swear) {
newFuture = callResultValue;
} else {
newFuture = originalFuture;
chainAndThenFutureOn.newArgs = callResultValue;
chainAndThenFutureOn.useNewArgs = true;
}
} else {
newFuture = originalFuture;
}
if (newFuturePool.add(newFuture)) { // We don't want to double chain onto the one chained before
// Let's chain the future jobs after this and-then onto the future/swear obj decided by the calling of callbacks
chainAndThenFutureOn(newFuture, "approve");
chainAndThenFutureOn(newFuture, "disapprove");
chainAndThenFutureOn(newFuture, "inform");
}
}
}
}(andThenFuture, this, okCallback, errCallback, duringCallback));
this.next(function () {
futureMediator.callAndThenCallback(Future.FLAG_FUTURE_IS_OK, this, Array.prototype.slice.call(arguments, 0));
})
.fall(function () {
futureMediator.callAndThenCallback(Future.FLAG_FUTURE_IS_ERR, this, Array.prototype.slice.call(arguments, 0));
})
.during(function () {
futureMediator.callAndThenCallback(Future.FLAG_FUTURE_NOT_YET, this, Array.prototype.slice.call(arguments, 0));
});
// Return the and-then future's swear obj so the following jobs will be chained to the and-then future
return andThenFuture.swear();
}
/* Arg:
<*|ARR> [msgArgs] = the messages being informed; the arguments to pass into the during callbacks; if multiple, put in one array. Please note that if only one var to pass along, but, that var is an array, please still wrap that var in one array or it woudl be treated as passing in mulitple vars.
Return:
Refer to this.report
*/
this.inform = function (msgArgs) {
if (this.report() === Future.FLAG_FUTURE_NOT_YET) {
var args = (msgArgs instanceof Array) ? msgArgs.slice(0) : (arguments.length > 0) ? [msgArgs] : [];
__duringCtrl.loop(null, args);
}
}
/* Arg:
<OBJ> context = the this obj used when invoking jobs
<*|ARR> [msgArgs] = the messages being informed; the arguments to pass into the during callbacks; if multiple, put in one array. Please note that if only one var to pass along, but, that var is an array, please still wrap that var in one array or it woudl be treated as passing in mulitple vars.
Return:
Refer to this.report
*/
this.informWith = function (context, msgArgs) {
if (this.report() === Future.FLAG_FUTURE_NOT_YET) {
var args = (msgArgs instanceof Array) ? msgArgs.slice(0) : (arguments.length > 1) ? [msgArgs] : [];
__duringCtrl.loop(context, args);
}
}
/* Arg:
<*|ARR> [settledArgs] = the var to pass along to the future jobs(functions); if multiple, put in one array. Please note that if only one var to pass along, but, that var is an array, please still wrap that var in one array or it woudl be treated as passing in mulitple vars.
Return:
Refer to this.report
*/
this.approve = function (settledArgs) {
if (this.report() === Future.FLAG_FUTURE_NOT_YET) {
var args = (settledArgs instanceof Array) ? settledArgs.slice(0) : (arguments.length > 0) ? [settledArgs] : [];
__status = Future.FLAG_FUTURE_IS_OK;
__queueCtrl.setVarsForQueue(__queueCtrl.FLAG_QUEUE_TYPE_OK, args);
__flushQueue();
}
return this.report();
}
/* Arg:
<OBJ> context = the this obj used when invoking queued up jobs
<*|ARR> [settledArgs] = refer to this.approve
Return:
Refer to this.report
*/
this.approveWith = function (context, settledArgs) {
if (this.report() === Future.FLAG_FUTURE_NOT_YET) {
__queueCtrl.setContextForQueue(__queueCtrl.FLAG_QUEUE_TYPE_OK, context);
if (arguments.length > 1) {
this.approve(settledArgs);
} else {
this.approve();
}
}
return this.report();
}
/* Arg:
<*|ARR> [settledArgs] = the var to pass along to the future jobs(functions); if multiple, put in one array. Please note that if only one var to pass along, but, that var is an array, please still wrap that var in one array or it woudl be treated as passing in mulitple vars.
Return:
Refer to this.report
*/
this.disapprove = function (settledArgs) {
if (this.report() === Future.FLAG_FUTURE_NOT_YET) {
var args = (settledArgs instanceof Array) ? settledArgs.slice(0) : (arguments.length > 0) ? [settledArgs] : [];
__status = Future.FLAG_FUTURE_IS_ERR;
__queueCtrl.setVarsForQueue(__queueCtrl.FLAG_QUEUE_TYPE_ERR, args);
__flushQueue();
}
return this.report();
}
/* Arg:
<OBJ> context = the this obj used when invoking queued up jobs
<*|ARR> [settledArgs] = refer to this.disapprove
Return:
Refer to this.report
*/
this.disapproveWith = function (context, settledArgs) {
if (this.report() === Future.FLAG_FUTURE_NOT_YET) {
__queueCtrl.setContextForQueue(__queueCtrl.FLAG_QUEUE_TYPE_ERR, context);
if (arguments.length > 1) {
this.disapprove(settledArgs);
} else {
this.disapprove();
}
}
return this.report();
}
/* Return:
<OBJ> The instance of _cls_Future_Swear assocciated with this future obj
*/
this.swear = function () {
if (!(__swear instanceof _cls_Future_Swear)) {
__swear = new _cls_Future_Swear(this);
}
return __swear;
}
}
/* Properties:
[ Private ]
<OBJ> __future = the future obj with which this swear obj associated
Methods:
[ Public ]
> report, swear : Refer to this::__future
> next, fall, anyway, during, andThen : Refer to this::__future. But always return this swear obj instead.
*/
function _cls_Future_Swear(future) {
var __future = future;
function bindMethod(self, name, alwaysSwear) { // Just a utility function for reuse
if (typeof __future[name] != "function") {
_logErr("Unknow future method : " + name);
return;
}
self[name] = !alwaysSwear ?
function () {
return __future[name].apply(__future, Array.prototype.slice.call(arguments, 0));
}
:
function () {
__future[name].apply(__future, Array.prototype.slice.call(arguments, 0));
return this;
};
}
var boundMethods; // Just a variable for reuse
boundMethods = ["report", "swear"];
while(boundMethods.length > 0) {
bindMethod(this, boundMethods.pop(), false);
}
boundMethods = ["next", "fall", "anyway", "during", "andThen"];
while(boundMethods.length > 0) {
bindMethod(this, boundMethods.pop(), true);
}
}
/* Properties:
[ Public ]
<OBJ> the property name is the future obj's name, the property value is the instance of Future::_cls_Future
*/
var _futures = {};
var publicProps = {
/* Arg:
<STR> name = the name of future obj
Return:
@ OK: true
@ NG: false
*/
exist : function (name) {
return _futures[name] instanceof _cls_Future;
},
/* Arg:
<STR> status = the status of deferred objs to dump, refer to Future::_cls_Future::__status
Return:
<ARR> array of names of future objs with the given status
*/
dump : function(status) {
var dumped = [];
if ( status === Future.FLAG_FUTURE_NOT_YET
|| status === Future.FLAG_FUTURE_IS_OK
|| status === Future.FLAG_FUTURE_IS_ERR
) {
for (var name in _futures) {
if (_futures[name] instanceof _cls_Future) {
if (_futures[name].report() == status) {
dumped.push(name);
}
}
}
}
return dumped;
},
/* Arg:
<STR> name = the name of future obj
Watch out this method is to new one future obj so passing the name of any existing future would result nothing.
Return:
@ OK: <OBJ> the instance of Future::_cls_Future
@ NG: null
*/
newOne : function (name) {
if (name && typeof name == "string" && !this.exist(name)) {
_futures[name] = new _cls_Future(name);
return _futures[name];
}
return null;
},
/* Arg:
<STR> name = the name of future obj
Return:
@ OK: <OBJ> the deleted instance of Future::_cls_Future
@ NG: null
*/
rmOne : function (name) {
if (name && typeof name == "string" && this.exist(name)) {
var deleted = _futures[name];
delete _futures[name];
return deleted;
}
return null;
},
/* Arg:
<STR> name = the name of the future upon futures.
Please watch out that this name cannot be the name of any existing future, which means the upon method always generates new future only.
<ARR> futures = The array of instances of Future::_cls_Future / Future::_cls_Future_Swear.
These arguments are the prior futures upon which the future upon futures depends.
Please watch out that as long as one of the array element is not valid, then, the entire array would be rejected.
Return:
@ OK: <OBJ> One Future::_cls_Future_Swear obj associated with the future upon futures
@ NG: null
*/
upon : function (name, futures) {
var future = null;
if (futures instanceof Array && futures.length > 0 && !this.exist(name)) {
var i;
for (i = 0; i < futures.length; i++) {
if (!(futures[i] instanceof _cls_Future) && !(futures[i] instanceof _cls_Future_Swear)) {
return future;
}
}
future = this.newOne(name);
if (future) {
function arrayHas(a, el) {
if (typeof a.indexOf == "function") {
return a.indexOf(el) >= 0;
}
for (i = 0; i < a.length; a++) {
if (a[i] === el) return true;
}
return false;
}
var priors = [], // The array of the prior futures on which the future after futures depends
approved = true, // The flag marking if all the prior futures are approved or not
okArgsArray = [], // The array of arguments passed by the prior futures when approved
errArgsArray = [], // The array of arguments passed by the prior futures when disapproved
duringArgsArray = []; // The array of arguments passed by the prior futures when informing
for (i = 0; i < futures.length; i++) {
if (!arrayHas(priors, futures[i])) {
priors.push(futures[i]);
}
}
priors.count = priors.length; // The count of prior future still not settled
function settle() { // Try to settle the future when the count of priors reaches 0
if (priors.count <= 0) {
if (approved) {
future.approve(okArgsArray);
} else {
future.disapprove(errArgsArray);
}
}
}
for (i = 0; i < priors.length; i++) {
okArgsArray[i] = undefined;
errArgsArray[i] = undefined;
priors[i].next((function (idx) {
return function () {
okArgsArray[idx] = (arguments.length <= 0) ? [] : Array.prototype.slice.call(arguments, 0);
priors.count--;
settle();
}
}(i)));
priors[i].fall((function (idx) {
return function () {
errArgsArray[idx] = (arguments.length <= 0) ? [] : Array.prototype.slice.call(arguments, 0);
approved = false;
priors.count--;
settle();
}
}(i)));
priors[i].during((function (idx) {
return function () {
for (var i = 0; i < priors.length; i++) {
duringArgsArray[i] = undefined;
}
duringArgsArray[idx] = (arguments.length <= 0) ? [] : Array.prototype.slice.call(arguments, 0);
future.inform(duringArgsArray);
}
}(i)));
}
}
}
return future ? future.swear() : future;
}
};
_define(publicProps, "FLAG_FUTURE_NOT_YET", 0, true);
_define(publicProps, "FLAG_FUTURE_IS_OK", 1, true);
_define(publicProps, "FLAG_FUTURE_IS_ERR", 2, true);
return publicProps;
}());
|
$.support.cors = true
function APIRequest(request, data, callback) {
var fulldata = "requestType="+request+"&"+data;
$.ajax({
url: "http://127.0.0.1:9987/api",
type: "post",
crossDomain: true,
dataType: 'json',
data : fulldata,
async: true,
success: callback,
error: function (jqXHR, textStatus, errorThrown)
{
document.write("request error!");
}
});
}
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require chosen-jquery
//= require messages
//= require ImageSelect.jquery
//= require dataTables/jquery.dataTables
//= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
//= require tinymce-jquery
//= require turbolinks
//= require bootstrap-sprockets
//= require highcharts/highcharts
//= require highcharts/highcharts-more
//= require users
//= require admins
//= require tickets
//= require tooltip
//= require_tree .
|
(this["webpackJsonp@visa/vds-react"]=this["webpackJsonp@visa/vds-react"]||[]).push([[147],{1659:function(s,t,a){s.exports=a.p+"static/media/illustration-spotlight-plane-dark.08345be3.svg"}}]);
//# sourceMappingURL=147.33780dc4.chunk.js.map
|
var Readable = require('stream').Readable;
var rs = Readable();
var c = 97;
rs._read = function () {
rs.push(String.fromCharCode(c++));
if (c > 'z'.charCodeAt(0))
rs.push(null);
};
rs.pipe(process.stdout);
|
import React, {PropTypes} from 'react'
import { NavDropdown, MenuItem } from 'react-bootstrap'
import { connect } from 'react-redux'
import i18next from 'i18next'
import { browserHistory } from 'react-router'
import { CurrentUser } from '../mixins'
import { refresh, signOut }from '../actions/oauth'
import { ajax } from '../utils'
const Widget = React.createClass({
mixins: [CurrentUser],
componentDidMount: function(){
const {onRefresh} = this.props;
onRefresh();
},
render: function() {
const {user, oauth, onSignOut} = this.props;
var title, links;
if (this.isSignIn()){
title = i18next.t("users.welcome", {name:user.name});
links = [
{href:"/users/dashboard", label:i18next.t("users.dashboard")},
null,
{href:"/dict", label:i18next.t("dict.index")},
null,
{label:i18next.t("users.sign_out"), click:onSignOut},
];
}else{
title = i18next.t("users.sign_in_or_up");
links = [
{href:oauth.google, label:i18next.t("users.sign_in_with_google")}
];
}
return (
<NavDropdown title={title} id="personal-bar">
{links.map(function(l, i){
return l == null ?
(<MenuItem key={i} divider />) :
(l.click ?
(<MenuItem key={i} onClick={l.click}>{l.label}</MenuItem>) :
(<MenuItem key={i} href={l.href}>{l.label}</MenuItem>))
})}
</NavDropdown>
);
}
});
Widget.propTypes = {
user: PropTypes.object.isRequired,
oauth: PropTypes.object.isRequired,
onRefresh: PropTypes.func.isRequired,
onSignOut: PropTypes.func.isRequired,
};
export default connect(
state => ({ user: state.currentUser, oauth:state.oauth2 }),
dispatch => ({
onSignOut:function(){
dispatch(signOut());
browserHistory.push('/');
},
onRefresh: function(){
ajax("get", "/oauth/sign_in", null, function(rst){
dispatch(refresh(rst));
});
}
})
)(Widget);
|
var express = require("express");
var app = express();
app.use(function(request, response, next) {
if(request.url == "/") {
response.send("Welcome to the homepage!");
}else {
next();
}
});
app.use(function(request, response, next) {
if(request.url == "/about") {
response.send("Welcome to the about page!");
}else {
next();
}
});
app.use(function(request, response) {
response.send("404 error!");
});
app.listen(3000);
|
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["color", "title"];
import React from 'react';
import PropTypes from 'prop-types';
export var BlockquoteIcon = function BlockquoteIcon(_ref) {
var color = _ref.color,
title = _ref.title,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
return /*#__PURE__*/React.createElement("svg", _extends({
width: "11",
height: "8",
viewBox: "0 0 11 8",
xmlns: "http://www.w3.org/2000/svg"
}, props), title && /*#__PURE__*/React.createElement("title", null, title), /*#__PURE__*/React.createElement("path", {
d: "M.794 8c1.188 0 2.177-.341 2.968-1.023.79-.682 1.366-1.694 1.724-3.034.341.547.713.948 1.116 1.204.403.255.869.383 1.398.383.194 0 .403-.028.626-.083.224-.056.453-.137.688-.243a3.187 3.187 0 01-1.376 1.667c-.647.388-1.505.626-2.575.714L5.724 8h.31c.493 0 .978-.07 1.454-.212.477-.14.9-.34 1.27-.6a4.643 4.643 0 001.509-1.746c.353-.706.529-1.476.529-2.31 0-.918-.262-1.67-.785-2.254C9.488.293 8.817 0 8 0c-.594 0-1.104.156-1.53.467-.427.312-.796.794-1.107 1.447-.306-.659-.668-1.142-1.085-1.45C3.86.153 3.355 0 2.76 0 1.99 0 1.338.269.803.807A2.679 2.679 0 000 2.77c0 .776.266 1.43.798 1.962s1.187.798 1.963.798c.2 0 .408-.026.626-.08.218-.052.45-.134.697-.246a3.286 3.286 0 01-1.385 1.667c-.64.388-1.5.626-2.576.714L.485 8h.309z",
fill: color
}));
};
BlockquoteIcon.propTypes = {
color: PropTypes.string,
title: PropTypes.string
};
BlockquoteIcon.defaultProps = {
color: '#222',
title: ''
};
|
(function (define) {
define(function (require) {
var jsonpath = require('../lib/jsonpath');
var undef;
return nested;
/**
*
* If the jsonPath specifies a property that cannot be navigated,
* the missing parameter is called. If there is no missing parameter,
* an Error is thrown.
* @param {Function} getter gets a property of an object
* @param {Function} setter sets a property on an object
* @param {Function} missing is a function that provides a value
* when the property or some part of the structure is missing.
* @param {Function} construct is a function that is provided
* the current property name as well as the full path and returns an
* object. This object is used to construct the structure when it is
* doesn't yet exist. Use the included construct function to create
* object literals or arrays, as necessary. If omitted, an error is
* thrown if the structure doesn't already exist.
* @returns {{get: Function, set: Function}}
*/
function nested (getter, setter, construct, missing) {
if (!missing) missing = prematureEnd;
if (!construct) construct = prematureEnd;
return { get: get, set: set };
/**
* Gets a value within a complex Object/Array structure using
* json-path-like syntax. A path in the following form:
* 'items[1].thing'
* will navigate to the 2nd "thing" property in this structure:
* { items: [ { thing: 'foo' }, { thing: 'bar' } ] }
* The path could also be written in these other ways:
* 'items.1.thing'
* 'items[1]["thing"]'
* @param {Object|Array} obj an arbitrarily complex structure of Object
* and Array types.
* @param {String} path is a jsonPath descriptor of a property in obj.
* @return {*}
*/
function get (obj, path) {
if (!obj) return missing('', path);
try {
return walk(obj, String(path));
}
catch (ex) {
if (ex.prop) return missing(ex.prop, path);
else throw ex;
}
}
/**
* Sets a value within a complex Object/Array structure using
* jsonPath-like syntax. If the jsonPath specifies a property that
* cannot be navigated, an Error is thrown.
* @param {Object|Array} obj an arbitrarily complex structure of Object
* and Array types.
* @param {String} path is a jsonPath descriptor of a property in obj.
* @param {*} [value] sets the value of the property described
* by path.
* @param {Boolean} build should be true to construct the structure
* as needed.
* @return {*}
*/
function set (obj, path, value, build) {
var popLast, end;
// pop off last property
popLast = jsonpath.pop(String(path));
end = walk(obj, popLast.path, build);
if (undef !== end) {
setter(end, popLast.name, value);
}
else {
prematureEnd(popLast.name, path);
}
return obj;
}
function walk (obj, path, build) {
var popped, parent, prop;
if (path.length == 0) return obj;
popped = jsonpath.pop(path);
if (!popped.name) throw new Error('json-path parsing error: ' + path);
parent = walk(obj, popped.path, build);
prop = getter(parent, popped.name);
if (build && undef === prop) {
prop = construct(popped.name, path);
setter(parent, popped.name, prop);
}
return prop;
}
}
function prematureEnd (name, path) {
var err = new Error('incomplete json-path structure. ' + name + ' not found in ' + path);
err.prop = name;
err.path = path;
throw err;
}
});
}(
typeof define == 'function' && define.amd
? define
: function (factory) { module.exports = factory(require); }
));
|
'use strict';
var React = require('react-native');
var Button = require('apsl-react-native-button');
var {
StyleSheet,
Text,
View,
} = React;
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
textStyleUp: {
color: 'white'
},
buttonStyleUp: {
flex: 1,
borderColor: 'black',
backgroundColor: '#6f0909',
width: 150
},
});
var ApplyFilterButton = React.createClass({
isDisabled: function(){
var initialLoad = this.props.initialLoad
var arrayEmpty = this.props.filterAlcohol.length ? false : true
return (initialLoad && arrayEmpty) ? true : false;
},
render: function(){
return(
<View style={[styles.container, this.border('red')]}>
<Button
style={styles.buttonStyleUp}
textStyle={styles.textStyleUp}
isDisabled={this.isDisabled()}
onPress={() => {this.props.handleApplyFilterButton()}}>
{this.isDisabled() ? 'Select Filters' : 'Show Drink'}
</Button>
</View>
)
},
border: function(color){
return {
borderColor: color,
borderWidth: 0
}
}
});
module.exports = ApplyFilterButton;
|
import React, { Component, PropTypes } from 'react';
import Radium, { Style } from 'radium';
import { type, breakpoint, layout } from './vars'
@Radium
class Styles extends Component {
render() {
return (
<Style rules={{
html: {
boxSizing: 'border-box',
fontSize: type.bodySize,
'-webkit-font-smoothing': 'antialiased'
},
'*, *::before, *::after': {
boxSizing: 'inherit',
textRendering: 'optimizeSpeed',
padding: 0,
margin: 0
},
body: {
fontFamily: type.fontSans,
fontWeight: type.fontRegular,
lineHeight: '1.5'
},
h1: {
fontSize: type.alpha,
fontFamily: type.fontSans,
lineHeight: '1.1',
letterSpacing: '-1px',
maxWidth: '1000px',
},
h2: {
fontFamily: type.fontSans,
fontSize: type.beta,
lineHeight: '1.3'
},
h3: {
fontWeight: type.fontRegular,
fontSize: type.bodySize,
marginBottom: '40px'
},
p: {
marginBottom: '20px'
},
a: {
color: 'inherit',
textDecoration: 'none',
paddingBottom: '1px',
borderBottom: '1px solid',
transition: '0.2s opacity'
},
'a:hover': {
opacity: '0.7'
},
img: {
maxWidth: '100%'
},
li: {
listStyle: 'none'
},
'input, textarea': {
'-webkit-appearance': 'none',
borderRadius: '0',
width: '100%',
outline: 'none',
fontFamily: type.fontSans,
fontSize: type.bodySize
},
'input::-webkit-input-placeholder, textarea::-webkit-input-placeholder': {
color: 'currentColor'
},
textarea: {
minHeight: '200px',
maxWidth: '100%'
},
hr: {
backgroundColor: 'currentColor',
marginTop: '10px',
marginBottom: '60px',
border: 'none',
height: '2px',
opacity: '0.15'
},
'svg path': {
fill: 'currentColor'
},
mediaQueries: {
'(min-width: 600px)': {
h1: {
fontSize: type.mega
}
},
'(min-width: 800px)': {
h1: {
fontSize: type.giga
}
}
}
}} />
)
}
}
export default Styles
|
'use strict';
module.exports = {
app: {
title: 'CERBERUS',
description: 'CerberuSoft',
keywords: 'Software'
},
port: process.env.PORT || 3000,
udpPort: 6000,
templateEngine: 'swig',
sessionSecret: 'MEAN',
sessionCollection: 'sessions',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.css',
'public/lib/animate.css/animate.css',
'public/lib/font-awesome/css/font-awesome.min.css',
'public/lib/simple-line-icons/css/simple-line-icons.css'
],
js: [
'public/lib/jquery/dist/jquery.min.js',
'public/lib/jquery_appear/jquery.appear.js',
'public/lib/d3/d3.js',
'public/lib/angular/angular.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/ngstorage/ngStorage.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/bootstrap/dist/js/bootstrap.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
'public/lib/oclazyload/dist/ocLazyLoad.js',
'public/lib/angular-translate/angular-translate.js',
'public/lib/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
'public/lib/angular-translate-storage-coockie/angular-translate-storage-coockie.js',
'public/lib/angular-translate-storage-local/angular-translate-storage-local.js'
]
},
css: [
'public/modules/**/css/*.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
};
|
import React from "react";
import { mount } from "enzyme";
import { Portal } from "../Portal";
describe("Portal", () => {
it("should render in node on mount", () => {
const node = document.createElement("div");
let div = null;
const wrapper = mount(
<Portal node={node}>
<div ref={x => (div = x)}>Foo</div>
</Portal>,
);
expect(div).toBeTruthy();
expect(div.innerHTML).toBe("Foo");
expect(div.parentNode).toBe(node);
expect(wrapper.children().length).toBe(0);
});
it("should rerender node on update", () => {
const node = document.createElement("div");
let div1 = null;
const wrapper = mount(
<Portal node={node}>
<div ref={x => (div1 = x)}>Foo</div>
</Portal>,
);
expect(div1).toBeTruthy();
expect(div1.innerHTML).toBe("Foo");
expect(div1.parentNode).toBe(node);
expect(wrapper.children().length).toBe(0);
let div2 = null;
wrapper.setProps({ children: <div ref={x => (div2 = x)}>Bar</div> });
expect(div2).toBeTruthy();
expect(div2.innerHTML).toBe("Bar");
expect(div2.parentNode).toBe(node);
expect(wrapper.children().length).toBe(0);
});
it("should cleanup node on umount", () => {
const node = document.createElement("div");
let div1 = null;
const wrapper = mount(
<Portal node={node}>
<div ref={x => (div1 = x)}>Foo</div>
</Portal>,
);
expect(div1).toBeTruthy();
expect(div1.innerHTML).toBe("Foo");
expect(div1.parentNode).toBe(node);
expect(wrapper.children().length).toBe(0);
wrapper.unmount();
expect(div1).toBeNull();
expect(node.outerHTML).toBe("<div></div>");
});
});
|
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.HTMLGroup = function ( dom ) {
THREE.Group.call( this );
this.type = 'HTMLGroup';
/*
dom.addEventListener( 'mousemove', function ( event ) {
console.log( 'mousemove' );
} );
dom.addEventListener( 'click', function ( event ) {
console.log( 'click' );
} );
*/
};
THREE.HTMLGroup.prototype = Object.assign( Object.create( THREE.Group.prototype ), {
constructor: THREE.HTMLGroup
} );
THREE.HTMLMesh = function ( dom ) {
var texture = new THREE.HTMLTexture( dom );
var geometry = new THREE.PlaneGeometry( texture.image.width * 0.05, texture.image.height * 0.05 );
var material = new THREE.MeshBasicMaterial( { map: texture } );
THREE.Mesh.call( this, geometry, material );
this.type = 'HTMLMesh';
};
THREE.HTMLMesh.prototype = Object.assign( Object.create( THREE.Mesh.prototype ), {
constructor: THREE.HTMLMesh
} );
THREE.HTMLTexture = function ( dom ) {
THREE.CanvasTexture.call( this, html2canvas( dom ) );
this.dom = dom;
this.anisotropy = 16;
};
THREE.HTMLTexture.prototype = Object.assign( Object.create( THREE.CanvasTexture.prototype ), {
constructor: THREE.HTMLTexture,
update: function () {
console.log( 'yo!', this, this.dom );
this.image = html2canvas( this.dom );
this.needsUpdate = true;
}
} );
|
'use strict';
// Configuring the Directions module
angular.module('courses').run(['Menus',
function(Menus) {
// Set top bar menu items
//Menus.addMenuItem('topbar', 'Teachers', 'teachers', 'dropdown', '/teachers(/create)?',false,['admin']);
//Menus.addMenuItem('topbar', '基础数据管理', 'basemenus', 'dropdown', '/courses(/create)?',false,['admin']);
}
]);
|
return jSQL;
});
|
/**
* Created by zuozhuo on 2017/5/12.
*/
const webpack = require('webpack');
const shelljs = require('shelljs');
const fs = require('fs');
const Path = require('path');
const jsdom = require('jsdom');
function getFile(filePath) {
return Path.join(__dirname, filePath);
}
function outputFileExists(filePath) {
return fs.existsSync(getFile(filePath));
}
function fileContainsText(filePath, text) {
filePath = Path.isAbsolute(filePath) ? filePath : getFile(filePath);
const content = fs.readFileSync(filePath);
return content.indexOf(text) >= 0
}
function loadHtml() {
const htmlSource = fs.readFileSync(getFile('./dist-prepare/index.html'));
const _document = jsdom.jsdom(htmlSource, {
url: 'http://www.baidu.com',
features: {
FetchExternalResources: ['script'],
ProcessExternalResources: ['script'],
MutationEvents: '2.0',
QuerySelector: true,
},
parsingMode: "auto",
created: function (error, window) {
console.log('----------------------------------------------------');
console.log(typeof window.XM_GIT_COMMIT_HASH); // always undefined
console.log(_document.documentElement.innerHTML);
}
});
const _window = _document.defaultView;
return _window;
}
function initWebpackGlobalsEnv() {
const htmlSource = fs.readFileSync(getFile('./dist-prepare/index.html'));
const _document = jsdom.jsdom(htmlSource, {
features: {
FetchExternalResources: ['script'],
ProcessExternalResources: ['script'],
}
});
const allScripts = _document.querySelectorAll('script');
for (let _script of allScripts) {
if (_script.innerHTML) {
eval(_script.innerHTML);
}
}
require('./dist-prepare/vendors.js');
require('./dist-prepare/app.js');
}
function runCompile(env) {
process.env.NODE_ENV = env;
shelljs.exec('rm -rf test/dist-prepare');
const shellResult = shelljs.exec('yarn compile');
initWebpackGlobalsEnv();
return shellResult;
}
describe('Compile webpack as NODE_ENV=production', () => {
const shellResult = runCompile('production');
it('compile success', () => {
expect(shellResult.code).toBe(0);
});
it('output files', () => {
expect(outputFileExists('./dist-prepare/app.js')).toBeTruthy();
expect(outputFileExists('./dist-prepare/app.js.map')).toBeTruthy();
expect(outputFileExists('./dist-prepare/vendors.js')).toBeTruthy();
expect(outputFileExists('./dist-prepare/vendors.js.map')).toBeTruthy();
expect(outputFileExists('./dist-prepare/index.html')).toBeTruthy();
expect(outputFileExists('./dist-prepare/manifest.js')).toBeTruthy();
expect(outputFileExists('./dist-prepare/manifest.js.map')).toBeTruthy();
expect(outputFileExists('./dist-prepare/scss.css')).toBeTruthy();
expect(outputFileExists('./dist-prepare/scss.css.map')).toBeTruthy();
});
it('js global vars', () => {
// const _window = loadHtml();
// console.log(_window.document.documentElement.innerHTML);
expect(window.webpackJsonp).toBeTruthy();
expect(window.LOGIN_USER.role).toEqual('client');
expect(window.ADMIN_USER.role).toEqual('admin');
expect(typeof window.importChunkA).toEqual('function');
expect(typeof window.importChunkB).toEqual('function');
});
it('code split', () => {
expect(fileContainsText('./dist-prepare/chunk.1.1.js', 'window.CHUNK_A="CHUNK_A"')).toBe(true);
expect(fileContainsText('./dist-prepare/chunk.0.0.js', 'window.CHUNK_B="CHUNK_B"')).toBe(true);
});
it('strip debug env code', () => {
expect(fileContainsText('./dist-prepare/app.js', 'window.IS_DEBUG_NODE_ENV')).toBe(false);
expect(window.IS_DEBUG_NODE_ENV).toBe(undefined);
});
it('strip react propType', () => {
expect(window.ReactHello).toBeTruthy();
expect(window.ReactHello.propTypes).toBeFalsy();
});
it('no react warning code', () => {
const searchText = 'You are manually calling a React.PropTypes validation';
expect(fileContainsText(require.resolve('react/dist/react.js'), searchText))
.toBe(true);
expect(fileContainsText('./dist-prepare/vendors.js', searchText))
.toBe(false);
});
it('vendors.js contains React source', () => {
// prototype.isReactComponent
expect(fileContainsText('./dist-prepare/vendors.js', 'prototype.isReactComponent')).toBe(true);
expect(fileContainsText('./dist-prepare/vendors.js', 'prototype.setState')).toBe(true);
expect(fileContainsText('./dist-prepare/vendors.js', 'prototype.forceUpdate')).toBe(true);
});
it('app.js DOES NOT contains React source', () => {
// prototype.isReactComponent
expect(fileContainsText('./dist-prepare/app.js', 'prototype.isReactComponent')).toBe(false);
expect(fileContainsText('./dist-prepare/app.js', 'prototype.setState')).toBe(false);
expect(fileContainsText('./dist-prepare/app.js', 'prototype.forceUpdate')).toBe(false);
});
it('sass extract correctly', () => {
expect(fileContainsText('./dist-prepare/scss.css', '#117366')).toBe(true);
});
it('postcss:autoprefixer works', () => {
expect(fileContainsText('./dist-prepare/scss.css', '-webkit-box-flex')).toBe(true);
});
it('tree shaking', () => {
// tree shaking will always pack class defines
expect(fileContainsText('./dist-prepare/app.js', 'ModuleAClass')).toBe(true);
expect(fileContainsText('./dist-prepare/app.js', 'ModuleBClass')).toBe(true);
// pack modules that we have imported
expect(window.moduleAConstName).toBe('moduleAConstName');
expect(window.getModuleBName()).toBe('getModuleBName');
// DO NOT pack modules that we DONT import
expect(fileContainsText('./dist-prepare/app.js', 'getModuleAName')).toBe(false);
expect(fileContainsText('./dist-prepare/app.js', 'moduleBConstName')).toBe(false);
});
it('css module', () => {
expect(fs.existsSync(getFile('./dist-prepare/css-modules.css'))).toBe(true);
expect(fileContainsText('./dist-prepare/css-modules.css', '#4f7a99')).toBe(true);
expect(fileContainsText('./dist-prepare/css-modules.css', '16.48862px')).toBe(true);
expect(window.cssModuleClassNames['i-am-module-css']).toBeTruthy();
});
it('es module & commonjs module', () => {
expect(window.commonJsRequireEsModule1).toEqual({
"default": "esModule1-default",
"esModule1Age": "esModule1-age",
"esModule1Name": "esModule1-name"
});
expect(window.commonJS1Name).toBe("commonJS1-Name");
expect(window.commonJS1Age).toBe("commonJS1-Age");
expect(window.commonJS2).toBe('commonJS2');
expect(window.esModule1Default).toBe("esModule1-default");
expect(window.esModule1Name).toBe("esModule1-name");
expect(window.esModule1Age).toBe("esModule1-age");
});
it('html payload data', () => {
expect(window.HTML_WEBPACK_PLUGIN_PAYLOAD).toEqual({
grade: 19,
level: 33,
});
});
});
/*
describe('Compile webpack as NODE_ENV=development', () => {
runCompile('development');
it('debug env code exists', () => {
expect(fileContainsText('./dist-prepare/app.js', 'window.IS_DEBUG_NODE_ENV')).toBe(true);
expect(window.IS_DEBUG_NODE_ENV).toBe(true);
});
});
*/
|
import {useView, inject} from 'aurelia-framework';
import {Registry} from 'shared/registry';
@useView('shared/showcase.html')
@inject(Registry)
export class Index {
constructor(registry) {
this.registry = registry;
}
configureRouter(config, router) {
this.router = router;
return this.registry.load(config, 'toolbar');
}
}
|
var path = require('path')
var fs = require('fs')
var nodeModules = {}
fs.readdirSync('node_modules')
.filter(function (x) {
return ['.bin'].indexOf(x) === -1
})
.forEach(function (mod) {
nodeModules[mod] = 'commonjs ' + mod
})
module.exports = {
entry: './app/index.js',
target: 'node',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
devtool: 'source-map',
externals: nodeModules,
module: {
rules: [{
test: /\.js$/,
use: [
'babel-loader',
'source-map-loader',
],
}, {
test: /\.json$/,
use: [
'json-loader',
],
}],
},
}
|
(function (t) {
// hr
t.add("This value should be false.", "Ova vrijednost treba biti neto\u010dna (false).", "validators", "hr");
t.add("This value should be true.", "Ova vrijednost treba biti to\u010dna (true).", "validators", "hr");
t.add("This value should be of type {{ type }}.", "Ova vrijednost treba biti tipa {{ type }}.", "validators", "hr");
t.add("This value should be blank.", "Ova vrijednost treba biti prazna.", "validators", "hr");
t.add("The value you selected is not a valid choice.", "Ova vrijednost treba biti jedna od ponu\u0111enih.", "validators", "hr");
t.add("You must select at least {{ limit }} choice.|You must select at least {{ limit }} choices.", "Izaberite barem {{ limit }} mogu\u0107nosti.", "validators", "hr");
t.add("You must select at most {{ limit }} choice.|You must select at most {{ limit }} choices.", "Izaberite najvi\u0161e {{ limit }} mogu\u0107nosti.", "validators", "hr");
t.add("One or more of the given values is invalid.", "Jedna ili vi\u0161e danih vrijednosti nije ispravna.", "validators", "hr");
t.add("This field was not expected.", "Ovo polje nije o\u010dekivalo.", "validators", "hr");
t.add("This field is missing.", "Ovo polje nedostaje.", "validators", "hr");
t.add("This value is not a valid date.", "Ova vrijednost nije ispravan datum.", "validators", "hr");
t.add("This value is not a valid datetime.", "Ova vrijednost nije ispravan datum-vrijeme.", "validators", "hr");
t.add("This value is not a valid email address.", "Ova vrijednost nije ispravna e-mail adresa.", "validators", "hr");
t.add("The file could not be found.", "Datoteka ne mo\u017ee biti prona\u0111ena.", "validators", "hr");
t.add("The file is not readable.", "Datoteka nije \u010ditljiva.", "validators", "hr");
t.add("The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}.", "Datoteka je prevelika ({{ size }} {{ suffix }}). Najve\u0107a dozvoljena veli\u010dina je {{ limit }} {{ suffix }}.", "validators", "hr");
t.add("The mime type of the file is invalid ({{ type }}). Allowed mime types are {{ types }}.", "Mime tip datoteke nije ispravan ({{ type }}). Dozvoljeni mime tipovi su {{ types }}.", "validators", "hr");
t.add("This value should be {{ limit }} or less.", "Ova vrijednost treba biti {{ limit }} ili manje.", "validators", "hr");
t.add("This value is too long. It should have {{ limit }} character or less.|This value is too long. It should have {{ limit }} characters or less.", "Ova vrijednost je preduga\u010dka. Treba imati {{ limit }} znakova ili manje.", "validators", "hr");
t.add("This value should be {{ limit }} or more.", "Ova vrijednost treba biti {{ limit }} ili vi\u0161e.", "validators", "hr");
t.add("This value is too short. It should have {{ limit }} character or more.|This value is too short. It should have {{ limit }} characters or more.", "Ova vrijednost je prekratka. Treba imati {{ limit }} znakova ili vi\u0161e.", "validators", "hr");
t.add("This value should not be blank.", "Ova vrijednost ne smije biti prazna.", "validators", "hr");
t.add("This value should not be null.", "Ova vrijednost ne smije biti null.", "validators", "hr");
t.add("This value should be null.", "Ova vrijednost treba biti null.", "validators", "hr");
t.add("This value is not valid.", "Ova vrijednost nije ispravna.", "validators", "hr");
t.add("This value is not a valid time.", "Ova vrijednost nije ispravno vrijeme.", "validators", "hr");
t.add("This value is not a valid URL.", "Ova vrijednost nije ispravan URL.", "validators", "hr");
t.add("The two values should be equal.", "Obje vrijednosti trebaju biti jednake.", "validators", "hr");
t.add("The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.", "Ova datoteka je prevelika. Najve\u0107a dozvoljena veli\u010dina je {{ limit }} {{ suffix }}.", "validators", "hr");
t.add("The file is too large.", "Ova datoteka je prevelika.", "validators", "hr");
t.add("The file could not be uploaded.", "Ova datoteka ne mo\u017ee biti prenesena.", "validators", "hr");
t.add("This value should be a valid number.", "Ova vrijednost treba biti ispravan broj.", "validators", "hr");
t.add("This file is not a valid image.", "Ova datoteka nije ispravna slika.", "validators", "hr");
t.add("This is not a valid IP address.", "Ovo nije ispravna IP adresa.", "validators", "hr");
t.add("This value is not a valid language.", "Ova vrijednost nije ispravan jezik.", "validators", "hr");
t.add("This value is not a valid locale.", "Ova vrijednost nije ispravana regionalna oznaka.", "validators", "hr");
t.add("This value is not a valid country.", "Ova vrijednost nije ispravna zemlja.", "validators", "hr");
t.add("This value is already used.", "Ova vrijednost je ve\u0107 iskori\u0161tena.", "validators", "hr");
t.add("The size of the image could not be detected.", "Veli\u010dina slike se ne mo\u017ee odrediti.", "validators", "hr");
t.add("The image width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px.", "\u0160irina slike je prevelika ({{ width }}px). Najve\u0107a dozvoljena \u0161irina je {{ max_width }}px.", "validators", "hr");
t.add("The image width is too small ({{ width }}px). Minimum width expected is {{ min_width }}px.", "\u0160irina slike je premala ({{ width }}px). Najmanja dozvoljena \u0161irina je {{ min_width }}px.", "validators", "hr");
t.add("The image height is too big ({{ height }}px). Allowed maximum height is {{ max_height }}px.", "Visina slike je prevelika ({{ height }}px). Najve\u0107a dozvoljena visina je {{ max_height }}px.", "validators", "hr");
t.add("The image height is too small ({{ height }}px). Minimum height expected is {{ min_height }}px.", "Visina slike je premala ({{ height }}px). Najmanja dozvoljena visina je {{ min_height }}px.", "validators", "hr");
t.add("This value should be the user's current password.", "Ova vrijednost treba biti trenutna korisni\u010dka lozinka.", "validators", "hr");
t.add("This value should have exactly {{ limit }} character.|This value should have exactly {{ limit }} characters.", "Ova vrijednost treba imati to\u010dno {{ limit }} znakova.", "validators", "hr");
t.add("The file was only partially uploaded.", "Datoteka je samo djelomi\u010dno prenesena.", "validators", "hr");
t.add("No file was uploaded.", "Niti jedna datoteka nije prenesena.", "validators", "hr");
t.add("No temporary folder was configured in php.ini.", "U php.ini datoteci nije konfiguriran privremeni folder.", "validators", "hr");
t.add("Cannot write temporary file to disk.", "Ne mogu zapisati privremenu datoteku na disk.", "validators", "hr");
t.add("A PHP extension caused the upload to fail.", "Prijenos datoteke nije uspio zbog PHP ekstenzije.", "validators", "hr");
t.add("This collection should contain {{ limit }} element or more.|This collection should contain {{ limit }} elements or more.", "Ova kolekcija treba sadr\u017eavati {{ limit }} ili vi\u0161e elemenata.|Ova kolekcija treba sadr\u017eavati {{ limit }} ili vi\u0161e elemenata.|Ova kolekcija treba sadr\u017eavati {{ limit }} ili vi\u0161e elemenata.", "validators", "hr");
t.add("This collection should contain {{ limit }} element or less.|This collection should contain {{ limit }} elements or less.", "Ova kolekcija treba sadr\u017eavati {{ limit }} ili manje elemenata.|Ova kolekcija treba sadr\u017eavati {{ limit }} ili manje elemenata.|Ova kolekcija treba sadr\u017eavati {{ limit }} ili manje elemenata.", "validators", "hr");
t.add("This collection should contain exactly {{ limit }} element.|This collection should contain exactly {{ limit }} elements.", "Ova kolekcija treba sadr\u017eavati to\u010dno {{ limit }} element.|Ova kolekcija treba sadr\u017eavati to\u010dno {{ limit }} elementa.|Ova kolekcija treba sadr\u017eavati to\u010dno {{ limit }} elemenata.", "validators", "hr");
t.add("Invalid card number.", "Neispravan broj kartice.", "validators", "hr");
t.add("Unsupported card type or invalid card number.", "Neispravan broj kartice ili tip kartice nije podr\u017ean.", "validators", "hr");
t.add("This is not a valid International Bank Account Number (IBAN).", "Ova vrijednost nije ispravan me\u0111unarodni broj bankovnog ra\u010duna (IBAN).", "validators", "hr");
t.add("This value is not a valid ISBN-10.", "Ova vrijednost nije ispravan ISBN-10.", "validators", "hr");
t.add("This value is not a valid ISBN-13.", "Ova vrijednost nije ispravan ISBN-13.", "validators", "hr");
t.add("This value is neither a valid ISBN-10 nor a valid ISBN-13.", "Ova vrijednost nije ispravan ISBN-10 niti ISBN-13.", "validators", "hr");
t.add("This value is not a valid ISSN.", "Ova vrijednost nije ispravan ISSN.", "validators", "hr");
t.add("This value is not a valid currency.", "Ova vrijednost nije ispravna valuta.", "validators", "hr");
t.add("This value should be equal to {{ compared_value }}.", "Ova vrijednost bi trebala biti jednaka {{ compared_value }}.", "validators", "hr");
t.add("This value should be greater than {{ compared_value }}.", "Ova vrijednost bi trebala biti ve\u0107a od {{ compared_value }}.", "validators", "hr");
t.add("This value should be greater than or equal to {{ compared_value }}.", "Ova vrijednost bi trebala biti ve\u0107a ili jednaka od {{ compared_value }}.", "validators", "hr");
t.add("This value should be identical to {{ compared_value_type }} {{ compared_value }}.", "Ova vrijednost bi trebala biti {{ compared_value_type }} {{ compared_value }}.", "validators", "hr");
t.add("This value should be less than {{ compared_value }}.", "Ova vrijednost bi trebala biti manja od {{ compared_value }}.", "validators", "hr");
t.add("This value should be less than or equal to {{ compared_value }}.", "Ova vrijednost bi trebala biti manja ili jednaka {{ compared_value }}.", "validators", "hr");
t.add("This value should not be equal to {{ compared_value }}.", "Ova vrijednost ne bi trebala biti {{ compared_value }}.", "validators", "hr");
t.add("This value should not be identical to {{ compared_value_type }} {{ compared_value }}.", "Ova vrijednost ne bi trebala biti {{ compared_value_type }} {{ compared_value }}.", "validators", "hr");
t.add("The image ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}.", "Omjer slike je prevelik ({{ ratio }}). Dozvoljeni maksimalni omjer je {{ max_ratio }}.", "validators", "hr");
t.add("The image ratio is too small ({{ ratio }}). Minimum ratio expected is {{ min_ratio }}.", "Omjer slike je premali ({{ ratio }}). Minimalni o\u010dekivani omjer je {{ min_ratio }}.", "validators", "hr");
t.add("The image is square ({{ width }}x{{ height }}px). Square images are not allowed.", "Slika je kvadratnog oblika ({{ width }}x{{ height }}px). Kvadratne slike nisu dozvoljene.", "validators", "hr");
t.add("The image is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented images are not allowed.", "Slika je orijentirana horizontalno ({{ width }}x{{ height }}px). Horizontalno orijentirane slike nisu dozvoljene.", "validators", "hr");
t.add("The image is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented images are not allowed.", "Slika je orijentirana vertikalno ({{ width }}x{{ height }}px). Vertikalno orijentirane slike nisu dozvoljene.", "validators", "hr");
t.add("An empty file is not allowed.", "Prazna datoteka nije dozvoljena.", "validators", "hr");
t.add("The host could not be resolved.", "Poslu\u017eitelj nije mogao biti razrije\u0161en.", "validators", "hr");
t.add("This value does not match the expected {{ charset }} charset.", "Znakovne oznake vrijednosti ne odgovaraju o\u010dekivanom {{ charset }} skupu.", "validators", "hr");
t.add("This is not a valid Business Identifier Code (BIC).", "Ovo nije validan poslovni identifikacijski broj (BIC).", "validators", "hr");
t.add("This form should not contain extra fields.", "Ovaj obrazac ne smije sadr\u017eavati dodatna polja.", "validators", "hr");
t.add("The uploaded file was too large. Please try to upload a smaller file.", "Prenesena datoteka je prevelika. Molim poku\u0161ajte prenijeti manju datoteku.", "validators", "hr");
t.add("The CSRF token is invalid. Please try to resubmit the form.", "CSRF vrijednost nije ispravna. Poku\u0161ajte ponovo poslati obrazac.", "validators", "hr");
})(Translator);
|
//----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//----------------------------------------------------------------------------------
var fs = require('fs');
var util = require('util');
var config = require('./config.js');
var storage = require('azure-storage');
var queueNamePrefix = "storagesampleforqueue";
var queueService;
function advancedSamples() {
// Create a queue service client for interacting with the Queue service from account name and account key or the connection string.
// You can either connect to an Azure storage account with account name and account key specified OR use the storage emulator for development.
// How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
if (config.connectionString) {
queueService = storage.createQueueService(config.connectionString);
} else {
queueService = storage.createQueueService(config.accountName, config.accountKey);
}
return scenarios = [
{
action: corsRules,
message: 'Queue CORS Sample\n'
},
{
action: serviceProperties,
message: 'Queue Service Properties Sample\n'
},
{
action: queueMetadata,
message: 'Queue Metadata Sample\n'
},
{
action: queueAcl,
message: 'Queue Access Policy Sample\n'
}
];
}
// Get Cors properties, change them and revert back to original
function corsRules(callback) {
console.log('Get service properties');
queueService.getServiceProperties(function (error, properties) {
if (error) return callback(error);
console.log('Set Cors rules in the service properties');
// Keeps the original Cors rules
var originalCors = properties.Cors;
properties.Cors = {
CorsRule: [{
AllowedOrigins: ['*'],
AllowedMethods: ['POST', 'GET', 'HEAD', 'PUT'],
AllowedHeaders: ['*'],
ExposedHeaders: ['*'],
MaxAgeInSeconds: 3600
}]
};
queueService.setServiceProperties(properties, function (error) {
if (error) return callback(error);
console.log('Cors rules set successfuly');
// reverts the cors rules back to the original ones so they do not get corrupted by the ones set in this sample
properties.Cors = originalCors;
queueService.setServiceProperties(properties, function (error) {
return callback(error);
});
});
});
}
// Manage logging and metrics service properties
function serviceProperties(callback) {
// Create a blob client for interacting with the blob service from connection string
// How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
var blobService = storage.createBlobService(config.connectionString);
console.log('Get service properties');
blobService.getServiceProperties(function (error, properties) {
if (error) return callback(error);
var originalProperties = properties;
properties = serviceProperties = {
Logging: {
Version: '1.0',
Delete: true,
Read: true,
Write: true,
RetentionPolicy: {
Enabled: true,
Days: 10,
},
},
HourMetrics: {
Version: '1.0',
Enabled: true,
IncludeAPIs: true,
RetentionPolicy: {
Enabled: true,
Days: 10,
},
},
MinuteMetrics: {
Version: '1.0',
Enabled: true,
IncludeAPIs: true,
RetentionPolicy: {
Enabled: true,
Days: 10,
},
}
};
console.log('Set service properties');
blobService.setServiceProperties(properties, function (error) {
if (error) return callback(error);
// reverts the cors rules back to the original ones so they do not get corrupted by the ones set in this sample
blobService.setServiceProperties(originalProperties, function (error) {
return callback(error);
});
});
});
}
// Retrieve statistics related to replication for the Queue service
function serviceStats(callback) {
console.log('Get service statistics');
queueService.getServiceStats(function (error, serviceStats){
if (error) return callback(error);
callback(null);
});
}
// Manage queue user-defined metadata
function queueMetadata(callback) {
var queueName = queueNamePrefix + "myqueueformetadata";
var metadata = { color: 'blue', foo: 'Bar' };
console.log('Create queue');
queueService.createQueueIfNotExists(queueName, function (error) {
if (error) return callback(error);
console.log('Set queue metadata');
queueService.setQueueMetadata(queueName, metadata, function (error) {
if (error) return callback(error);
console.log('Get queue metadata');
queueService.getQueueMetadata(queueName, function (error, queue) {
if (error) return callback(error);
console.log(' color: ' + queue.metadata.color);
console.log(' foo: ' + queue.metadata.foo);
console.log('Delete queue');
queueService.deleteQueue(queueName, function () {
callback(error);
});
});
});
});
}
// Manage access policies of the queue
function queueAcl(callback) {
var queueName = queueNamePrefix + "myqueueforacl";
console.log('Create queue');
queueService.createQueueIfNotExists(queueName, function() {
// Set access policy
var expiryDate = new Date();
expiryDate.setMinutes(expiryDate.getMinutes() + 10);
var id = 'sampleIDForQueuePolicy';
var sharedAccessPolicy = {
sampleIDForQueuePolicy: {
Permissions: storage.QueueUtilities.SharedAccessPermissions.PROCESS,
Expiry: expiryDate
}
};
console.log('Set queue access policy');
queueService.setQueueAcl(queueName, sharedAccessPolicy, function (error, result, response) {
if (error) return callback(error);
// Get access policy
console.log('Get queue access policy');
queueService.getQueueAcl(queueName, function(error, result, response) {
if (error) return callback(error);
console.log(' Permissions: ' + result.signedIdentifiers.sampleIDForQueuePolicy.Permissions);
console.log(' Expiry: ' + result.signedIdentifiers.sampleIDForQueuePolicy.Expiry.toISOString());
console.log('Delete queue');
queueService.deleteQueue(queueName, function () {
callback(error);
});
});
});
});
}
module.exports = advancedSamples();
|
var path = require('path');
module.exports = {
src: {
ts: path.join(__dirname, 'src/index.ts'),
scss: path.join(__dirname, 'src/index.scss'),
html: path.join(__dirname, 'src/index.html')
},
output: {
dev: {
js: 'main-dev.js',
directory: 'build-dev',
css: 'main-dev.css'
},
prod: {
js: 'main-prod.js',
directory: 'build-prod',
css: 'main-prod.css'}
},
app: {
__APP_NAME__: JSON.stringify('doodoodle')
}
};
|
'use strict';
var fs = require('fs-extra'),
path = require('path'),
CoreMailer,
CoreExtension,
CoreUtilities,
CoreController,
appSettings,
appenvironment,
mongoose,
mailerSettingsFile = path.join(process.cwd(), 'content/config/extensions/periodicjs.ext.mailer/transport.json'),
mailerSettingJSON = fs.readJsonSync(mailerSettingsFile),
logger;
var testemail = function(req,res){
var mailerSettings = mailerSettingJSON[appenvironment],
mail_settings = {
periodic_config:{
},
'periodicjs.ext.mailer':{
'transport.json':{
}
}
};
mail_settings.periodic_config[appenvironment] = {
'adminnotificationemail': appSettings.adminnotificationemail,
'serverfromemail':appSettings.serverfromemail,
'adminnotificationemail_bcc': appSettings.adminnotificationemail_bcc,
'adminbccemail': appSettings.adminbccemail,
};
mail_settings['periodicjs.ext.mailer']['transport.json'][appenvironment] = mailerSettings;
var viewtemplate = {
viewname: 'p-admin/mailer/test',
themefileext: appSettings.templatefileextension,
extname: 'periodicjs.ext.mailer'
},
viewdata = {
appenvironment: appenvironment,
pagedata: {
title: 'Test Email Settings',
toplink: '» Test email settings',
pageID: 'application',
extensions: CoreUtilities.getAdminMenu()
},
user: req.user,
mail_settings: mail_settings
};
CoreController.renderView(req, res, viewtemplate, viewdata);
};
/**
* send a test email from a form submission
* @param {object} req
* @param {object} res
* @return {object} reponds with an error page or email sent status
*/
var sendmail = function(req, res){
CoreMailer.getTransport({appenvironment : appSettings.application.environment},function(err,transport){
if(err){
CoreController.handleDocumentQueryErrorResponse({
err:err,
res:res,
req:req
});
}
else{
var emailMessage = CoreUtilities.removeEmptyObjectValues(req.body);
emailMessage.generateTextFromHTML = true;
transport.sendMail(emailMessage,function(err,email_response){
if(err){
CoreController.handleDocumentQueryErrorResponse({
err:err,
res:res,
req:req
});
}
else{
CoreController.handleDocumentQueryRender({
res:res,
req:req,
responseData:{
result: 'success',
data:email_response
}
});
}
});
}
});
};
/**
* mailer controller
* @module mailerController
* @{@link https://github.com/typesettin/periodic}
* @author Yaw Joseph Etse
* @copyright Copyright (c) 2014 Typesettin. All rights reserved.
* @license MIT
* @requires module:fs
* @requires module:util-extent
* @param {object} resources variable injection from current periodic instance with references to the active logger and mongo session
* @return {object} sendmail
*/
var controller = function(resources){
logger = resources.logger;
mongoose = resources.mongoose;
appSettings = resources.settings;
CoreController = resources.core.controller;
CoreUtilities = resources.core.utilities;
CoreExtension = resources.core.extension;
CoreMailer = resources.core.mailer;
appenvironment = appSettings.application.environment;
return{
testemail:testemail,
sendmail:sendmail
};
};
module.exports = controller;
|
/**
* Helper that loads a CSS file (i.e. LINK tag).
*
* @returns {Function} a function for loading LINKs into the current <code>document</code>:
* <code>loadLink(href : String, rel : String, callback : Function)</code>
*
* where
* <code>href</code>: (String) the URL for the LINK
* <code>rel</code>: (String) OPTIONAL the value for the <code>rel</code> attribute of the LINK tag (DEFAULT: <code>stylesheet</code>)
* <code>callback</code>: (Function) OPTIONAL a callback function for the <code>onload</code> event (NOTE: this is not supported or fully supported by all browsers -- may never be fired!)
*
* or
* <code>options</code>: (Object) an options object with properties.
* where the properties should/can be:
* <code>options.href</code>: (String) the URL for the LINK
* <code>options.rel</code>: (String) OPTIONAL (see above)
* <code>options.onload</code>: (Function) OPTIONAL callback for onload event (see above)
* <code>options.<property></code>: (any) OPTIONAL any additional properties will be added to the created LINK object "as-is"
*
* @requires document
* @requires document.head
* @requires document.createElement( link )
*/
define(function loadJqmCss() {
function loadLink(href, rel, callback){
//normalize arguments:
var attrs = null;
if(typeof href === 'object'){
//handle case: args is options object
attrs = href;
if(attrs.href){
href = attrs.href;
delete attrs.href;
}
if(attrs.rel){
rel = attrs.rel;
delete attrs.rel;
}
if(attrs.onload){
callback = attrs.onload;
delete attrs.onload;
}
}
else if(typeof rel === 'function'){
//handle case: args' 2nd param is callback function
callback = rel;
rel = void(0);
}
//create the link and its properties:
var link = document.createElement('link');
link.rel = rel? rel : 'stylesheet';
link.href = href;
if(attrs) for(var prop in attrs){
if(attrs.hasOwnProperty(prop)){
// if(/^on/.test(prop)){
// TODO russa: should we apply special treatment for event handlers?
// }
link[prop] = attrs[prop];
}
}
//NOTE this may not work
// (some browser do not support onload for CSS; some only fire onload for remotely loaded CSS files...)
if (typeof callback === 'function') {
/** @ignore */
link.onload = function() {
callback.apply(this, href, rel);
};
}
document.getElementsByTagName('head')[0].appendChild(link);
}
return loadLink;
});
|
angular.
module('phonecatApp').
config(['$locationProvider', '$routeProvider',
function config($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.
when('/phones', {
template: '<phone-list></phone-list>'
}).
when('/phones/:phoneId', {
template: '<phone-detail></phone-detail>'
}).
otherwise('/phones');
}
]);
|
---
---
class Slider {
constructor(elem) {
this.active = 0;
this.viewport = elem.querySelector(".slides-viewport");
this.slides = elem.querySelectorAll(".slide");
}
findNext() {
if(this.active + 1 >= this.slides.length) return 0;
return this.active + 1;
}
findPrev() {
if(this.active - 1 < 0) return this.slides.length-1;
return this.active - 1;
}
updateScrollPosition() {
this.viewport.scrollTo(this.active * this.slides[0].offsetWidth, 0);
}
next() {
this.active = this.findNext();
this.updateScrollPosition();
}
prev() {
this.active = this.findPrev();
this.updateScrollPosition();
}
}
class Swipeable {
constructor(elem) {
this.elem = elem;
this.x0 = 0;
this.x1 = 0;
this.leftSwipe = new CustomEvent("swipe", {
detail: {
direction: "left",
}
});
this.rightSwipe = new CustomEvent("swipe", {
detail: {
direction: "right",
}
});
elem.addEventListener("touchstart", this.handleTouchStart.bind(this), {passive: true});
elem.addEventListener("touchend", this.handleTouchEnd.bind(this), {passive: true});
}
fireEvent() {
const dx = this.x1-this.x0;
let event = null;
if(dx > 50)
event = this.rightSwipe;
else if(dx < -50)
event = this.leftSwipe;
if(event)
this.elem.dispatchEvent(event);
}
handleTouchStart(e) {
console.log(e.touches);
this.x0 = e.touches[0].clientX;
}
handleTouchEnd(e) {
this.x1 = e.changedTouches[0].clientX;
this.fireEvent();
}
}
document.addEventListener("DOMContentLoaded", () => {
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)"),
sliders = document.querySelectorAll(".slider");
sliders.forEach((elem, key) => {
let slider = new Slider(elem);
let autoscroll = null;
new Swipeable(elem);
// Start scrolling every 7s if prefers reduced motion flag isn't set
if(!reduceMotion || !reduceMotion.matches) {
autoscroll = window.setInterval(() => {
slider.next();
}, 7000);
}
const cancelAutoscroll = () => {
if(autoscroll != null) {
window.clearInterval(autoscroll);
autoscroll = null;
}
}
// Swipe detection
elem.addEventListener("swipe", (e) => {
cancelAutoscroll();
if(e.detail.direction === "left") {
slider.next();
} else {
slider.prev();
}
});
// Control buttons
elem.querySelector(".controls .next").addEventListener("click", () => {
cancelAutoscroll();
slider.next()
});
elem.querySelector(".controls .back").addEventListener("click", () => {
cancelAutoscroll();
slider.prev()
});
// Resizing the window can fudge up the slider. Update it to to fix it.
window.addEventListener("resize", () => {
slider.updateScrollPosition();
})
});
});
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) { return 5; }
root.ng.common.locales['kok'] = [
'kok',
[['म.पू.', 'म.नं.'], u, u],
u,
[
['आ', 'सो', 'मं', 'बु', 'गु', 'शु', 'शे'],
['आयतार', 'सोमार', 'मंगळार', 'बुधवार', 'गुरुवार', 'शुक्रार', 'शेनवार'], u,
['आय', 'सोम', 'मंगळ', 'बुध', 'गुरु', 'शुक्र', 'शेन']
],
u,
[
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
[
'जानेवारी', 'फेब्रुवारी', 'मार्च', 'एप्रिल', 'मे', 'जून', 'जुलाय', 'आगोस्त', 'सप्टेंबर', 'ऑक्टोबर',
'नोव्हेंबर', 'डिसेंबर'
],
u
],
u,
[['क्रिस्तपूर्व', 'क्रिस्तशखा'], u, u],
0,
[0, 0],
['d-M-yy', 'dd-MM-y', 'd MMMM y', 'EEEE d MMMM y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
['{1} {0}', u, u, u],
['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##,##0.###', '#,##,##0%', '¤ #,##,##0.00', '#E0'],
'₹',
'INR',
{'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']},
plural,
[]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
|
const should = require("should");
const ziffer = require("..");
describe("Option: digits", () => {
it("Should default to null", () => {
const n = ziffer();
n.format(123.456).should.equal("123,456");
});
it("Should accept a string with 10 symbols to replace from 0 to 9", () => {
const n = ziffer();
n.format(123.456, { digits: "٠١٢٣٤٥٦٧٨٩" }).should.equal("١٢٣,٤٥٦");
});
it("Should be able to unformat into common decimals again", () => {
const n = ziffer();
n.unformat("١٢٣,٤٥٦", { digits: "٠١٢٣٤٥٦٧٨٩" }).should.equal(123.456);
});
});
|
'use strict'
require('babel-core/register')
require('babel-polyfill')
const describe = require('mocha-sugar-free').describe
const it = require('mocha-sugar-free').it
const expect = require('chai').expect
const { audioPlay, audioPlaying, audioPause, audioPaused, audioEnded,
audioRegister, audioUnregister, audioSrc, audioCommand } = require('../src/actions')
describe('actions', () => {
describe('audioPlay', () => {
it('returns an object with id and type', () => {
expect(audioPlay('id')).to.eql({type: '@@redux-audio/PLAY', id: 'id'})
})
})
describe('audioPlaying', () => {
it('returns an object with id and type', () => {
expect(audioPlaying('id')).to.eql({type: '@@redux-audio/PLAYING', id: 'id'})
})
})
describe('audioPause', () => {
it('returns an object with id and type', () => {
expect(audioPause('id')).to.eql({type: '@@redux-audio/PAUSE', id: 'id'})
})
})
describe('audioPaused', () => {
it('returns an object with id and type', () => {
expect(audioPaused('id')).to.eql({type: '@@redux-audio/PAUSED', id: 'id'})
})
})
describe('audioEnded', () => {
it('returns an object with id and type', () => {
expect(audioEnded('id')).to.eql({type: '@@redux-audio/ENDED', id: 'id'})
})
})
describe('audioRegister', () => {
it('returns an object with id and type', () => {
expect(audioRegister('id')).to.eql({type: '@@redux-audio/REGISTER', id: 'id'})
})
})
describe('audioUnregister', () => {
it('returns an object with id and type', () => {
expect(audioUnregister('id')).to.eql({type: '@@redux-audio/UNREGISTER', id: 'id'})
})
})
describe('audioSrc', () => {
it('returns an object with id, type, and src', () => {
expect(audioSrc('id', 'src')).to.eql({type: '@@redux-audio/SRC', id: 'id', src: 'src'})
})
})
describe('audioCommand', () => {
it('returns an object with id and type', () => {
expect(audioCommand('id')).to.eql({type: '@@redux-audio/COMMAND', id: 'id'})
})
})
})
|
export default function findProjectsWithWorkPlans() {
return {
query: `
query {
findProjectsWithWorkPlans {
id,
name
},
}
`,
}
}
|
define(
[
"jquery",
"cfgs",
"core/core-modules/framework.event",
"core/core-modules/framework.dict",
"core/core-modules/framework.ajax",
'core/core-modules/framework.util'
],
function ($, cfgs, event, dict, ajax, util) {
var readStyle = function (keyword) {
if (cfgs.options.styles[keyword]) {
return cfgs.options.styles[keyword];
} else {
return cfgs.options.styles['btn-default'];
}
};
var module = {
"define": {
name: "[插件]表单处理 for MODULE-LAYOUT",
version: "1.0.0.0",
copyright: " Copyright 2017-2027 WangXin nvlbs,Inc."
},
"init": function (layout) {
this.source = layout;
// EVENT-ON:sidebar.changed
event.on('sidebar.changed', function () {
module.renderAllSelect();
});
$(window).on('resize', function () {
setTimeout(function () {
module.renderAllSelect();
}, 500);
});
},
"source": {},
/** 初始化下拉列表框控件
* @param {string} dictname 绑定的数据字典项名称
* @param {object} target 控件绑定的dom对象
* @param {string} value 默认值
* @param {boolean} ismulit 是否多选,默认为false
*/
"initDict": function (dictname, target, value, ismulit) {
dict.get(dictname, function (datas) {
$.each(datas, function (index, item) {
target.append(
$("<option/>")
.val(index)
.text(item.text ? item.text : item)
);
});
target.val(value);
// target.attr("data-value", value);
if (ismulit) {
target.attr("data-mulit", true);
}
});
},
/** 渲染下拉列表控件 */
"renderAllSelect": function () {
// 解决时间段选择控件冲突问题
$("select:not(.monthselect,.yearselect)").each(function () {
var selectvalue = $(this).val();
var ismulit = $(this).attr("data-mulit");
$(this).select2(cfgs.options.select2);
if (selectvalue) {
if (ismulit) {
$(this)
.val(selectvalue.split(","))
.trigger("change");
} else {
$(this)
.val(selectvalue)
.trigger("change");
}
} else {
$(this)
.val(null)
.trigger("change");
}
});
},
/** 渲染日期时间控件 */
"renderDate": function () {
$(".form-date,.form-datetime").each(function () {
var wrapper = $("<div></div>").addClass("input-group date");
var span = $("<span></span>").addClass("input-group-addon");
var button = $("<a></a>").addClass("date-set");
button.append($("<i></i>").addClass("fa fa-calendar"));
span.append(button);
$(this).wrapAll(wrapper);
$(this)
.parent()
.append(span);
var datepicker;
if ($(this).hasClass("form_datetime")) {
// $(this).removeClass('.form-datetime');
datepicker = $(this)
.parent()
.datetimepicker(cfgs.options.datetimepicker);
} else {
// $(this).removeClass('.form-date');
datepicker = $(this)
.parent()
.datetimepicker(cfgs.options.datepicker);
}
datepicker.on("changeDate", function () {
if ($(".core-form").data("bootstrapValidator")) {
var id = $("[id]", $(this)).attr("id")
$(".core-form")
.data("bootstrapValidator")
.updateStatus(id, "NOT_VALIDATED", null)
.validateField(id);
}
});
});
},
/** 支持缓存的列表请求方法.通常用于请求字典数据.
*
* @param {Object} options 参数设置
* [可选结构]
* api 请求的服务地址.
* args 请求时附带的参数.
* hasall 是否附带“全部”选项.
* cached 是否缓存数据,boolean,默认为true.
* target 承载内容的元素selector,通常为select
* valuefn 返回value内容的方法,function(index,item) return string
* textfn 返回text内容的方法,function(index,item) return string
* parsefn 请求成功后解析数据的方法 function(index,item).该属性与target\valuefn\textfn冲突仅设置一种
* done 解析数据完成后执行的反馈 function().
*
* @author wangxin
*/
"initCache": function (options) {
if (!options.api) {
console.error("未设置数据服务地址!");
return;
}
if (!options.args) {
options.args = {};
}
if (options.cached == undefined) {
options.cached = true;
}
var parse = function (index, item) {
if (options.parsefn) {
options.parsefn(index, item);
} else if (options.target && options.textfn && options.valuefn) {
var value = options.valuefn(index, item);
var text = options.textfn(index, item);
var opotion = $("<option/>")
.val(value)
.text(text);
options.target.append(opotion);
}
};
var requestDone = function (list) {
if (list && list.length > 0) {
cfgs.cache[options.api] = list;
$.each(list, function (index, item) {
parse(index, item);
});
}
if (options.done) {
options.done();
}
};
if (cfgs.cache[options.api] && options.cached) {
console.debug("Cached:" + options.api);
$.each(cfgs.cache[options.api], function (index, item) {
parse(index, item);
});
if (options.done) {
options.done();
}
} else {
console.debug("UnCached:" + options.api);
ajax.get(
options.api, {
cache: false,
args: options.args,
block: false
}, {
noneDate: function () {
requestDone();
},
success: function (json) {
requestDone(json.data.list);
}
}
);
}
},
"renderButton": function () {
/** 设置页面按钮文本\图标\颜色等基本信息 */
$.each(cfgs.options.texts, function (key, value) {
$("." + key).each(function () {
$(this).html(value).addClass(readStyle(key));
});
});
},
/** 渲染页面元素 */
"render": function () {
// 注册页面控件
this.renderAllSelect();
this.renderButton();
this.renderDate();
$(":checkbox,:radio").uniform();
},
/** ajax方式加载页面内容.
* @param {JSON} options 打开页面的参数
* {string} title 界面的标题
* {string} url 打开界面的地址
* {boolean} map 打开界面时是否添加站点地图
* {function} callback 打开界面后回调函数
*
* @author wangxin
*/
"openview": function (options) {
var loadcallback = function () {
/** 打开界面默认参数 */
var defaults = {
/** 界面标题 */
"title": "",
/** 打开界面的地址*/
"url": "",
/** 打开界面时是否添加站点地图*/
"map": true,
/** 打开界面后回调函数 */
"callback": function () { }
};
/** 打开界面的参数 */
var _options = $.extend(defaults, options);
if (_options.title && _options.title != "") { } else {
_options.title = $("h4", ".ajax-content").eq(0).text();
}
if (_options.map) {
$("<span />")
.text(_options.title)
.appendTo($("<li />").appendTo($(".content-breadcrumb")));
}
_options.callback();
};
if (module.source && module.source.load && typeof module.source.load === "function")
module.source.load(options.url, loadcallback);
},
/** ajax方式加载页面内容.
* @param {JSON} options 打开页面的参数
* {string} title 界面的标题
* {string} url 打开界面的地址
* {boolean} map 打开界面时是否添加站点地图
* {function} callback 打开界面后回调函数
*
* @author wangxin
*/
"openWidow": function (options) {
/** 打开界面默认参数 */
var defaults = {
/** 界面标题 */
"title": "",
/** 打开界面的地址*/
"url": "",
/** 模式对话框的宽度 */
"width": 'full',
/** 模式对话框的高度 */
'height': 'full',
/** 对话框内容模式:影响滚动条 normal=普通页面|tab=带有tab的页面 */
"mode": "normal", //normal|tab
/** 打开模式对话框时处理函数 */
"onshow": function () { },
/** 关闭模式对话框时处理函数 */
"onhide": function () { }
};
/** 打开界面的参数 */
var _options = $.extend(defaults, options);
// 移除模式对话框容器
if ($('.modal-container').length > 0) {
$('.modal-container').remove();
}
$('body').append($("<div/>").addClass('modal-container'));
var modalHeight, modalWidth;
if (_options.width == 'full') {
modalWidth = $(window).width() - 50;
} else {
modalWidth = _options.width;
}
if (_options.height == 'full') {
modalHeight = $(window).height() - 180;
} else {
modalHeight = _options.height;
}
$('.modal-container').load(cfgs.modalpage, function () {
if (_options.title) {
$(".modal-container .modal .modal-title").html(_options.title);
}
var eventArgs = {
"sender": $('.modal-container .modal')
};
$(".modal-dialog", eventArgs.sender).width(modalWidth);
$(".modal-body", eventArgs.sender).height(modalHeight);
if (_options.mode == "normal") {
let scrollOption = $.extend(cfgs.options.scroller, {
height: modalHeight
});
$(".modal-body", eventArgs.sender).css("height", (modalHeight) + "px");
$(".modal-body", eventArgs.sender).slimScroll(scrollOption);
}
$(".modal-body", eventArgs.sender).load(_options.url, function () {
$(".modal-container .modal-footer").append(
$('.modal-container tools')
);
eventArgs.sender.on('show.bs.modal', function () {
$('tools>button').unwrap();
_options.onshow(eventArgs.sender);
module.renderButton();
});
eventArgs.sender.on('hide.bs.modal', function () {
$('.modal-container').remove();
_options.onhide(eventArgs.sender);
});
if (_options.mode == "tab") {
modalHeight = modalHeight - $(".tabbable.header-tabs .nav-tabs").height() - 15;
let scrollOption = $.extend(cfgs.options.scroller, {
height: modalHeight
});
$(".tabbable.header-tabs .tab-content", eventArgs.sender).css("height", (modalHeight) + "px");
$(".tabbable.header-tabs .tab-content", eventArgs.sender).slimScroll(scrollOption);
}
eventArgs.sender.modal();
});
});
// return $('.modal-container .modal');
},
/** 在container中增加空单元格(td),并且返回该单元格
* @param {Element} container 承载空单元格的容器
* @returns {Element} 装入container的单元格
*/
"appendEmpty": function (container) {
return $(cfgs.templates.cell).appendTo(container);
},
/** 在container中增加一个动作按钮,并且返回该按钮
* @param {Element} container 承载动作按钮的容器
* @param {string} textKey 动作按钮的文本键,对应cfgs.texts
* @param {function} clickEventHandler 动作按钮点击事件的处理函数
* @param {string} eventArgs 动作按钮附加的参数 data-args='eventArgs'
* @returns {Element} 动作按钮
*/
"appendAction": function (container, textKey, clickEventHandler, eventArgs) {
var actionButton = $("<button />").appendTo(container)
.html(cfgs.options.texts[textKey])
.addClass(cfgs.options.styles[textKey])
// .addClass('btn-mini')
.addClass(textKey)
// .attr("href", "javascript:;")
.on("click", clickEventHandler);
if (eventArgs) {
actionButton.attr('data-args', eventArgs);
}
return actionButton;
},
/** 在container中增加HTML单元格(td),并且返回该单元格
* @param {Element} container 承载动作按钮的容器
* @param {string} html 添加到单元格的HTML内容
* @returns {Element} 承载HTML内容的单元格
*/
"appendHTML": function (container, html) {
return this.appendEmpty(container).html(html);
},
/** 在container中增加文本单元格(td),并且返回该单元格
* @param {Element} container 承载动作按钮的容器
* @param {string} text 添加到单元格的文本内容
* @returns {Element} 承载文本内容的单元格
*/
"appendText": function (container, text) {
return this.appendEmpty(container).text(text);
},
/** 在container中增加字典单元格(td),并且返回该单元格
* @param {Element} container 承载动作按钮的容器
* @param {string} dictname 字典名称
* @param {string} text 字典对应的值,若isMulit=true,则多个值用,分割
* @param {boolean} isMulit 是否支持多值转换
* @returns {Element} 承载字典内容的单元格
*/
"appendDictText": function (container, dictname, text, isMulit) {
if (isMulit) {
// 内容不存在时不需要处理
if (!text) {
return this.appendText(container, '');
}
let newtext = "";
$.each(text.split(","), function (index, item) {
if (index > 0) {
newtext += ",";
}
newtext += dict.getText(dictname, item);
});
return this.appendText(container, newtext);
} else {
let item = dict.getItem(dictname, text);
if (item.text) {
var td = this.appendEmpty(container);
var span = $('<span/>').append(item.text);
// if (item.label) {
// span.addClass('label label-sm');
// span.addClass(item.label);
// }
td.append(span);
return td;
} else {
return this.appendText(container, item);
}
}
},
/** 在container中增加时间单元格(td),并且返回该单元格
* @param {Element} container 承载动作按钮的容器
* @param {string} text 时间文本(UTC)格式
* @param {string} format 日期转换的格式
* @returns {Element} 承载时间内容的单元格
*/
"appendDateText": function (container, text, format) {
var newtext = "";
if (format) {
newtext = util.utcTostring(text, format)
} else {
newtext = util.utcTostring(text, cfgs.options.defaults.datetimeformat)
}
return this.appendText(container, newtext);
},
}
return module;
}
);
|
(function () {
var dM = angular.module('aqb.dir');
// dM
})();
|
/*
Component: Collision
Calls a callback when colliding with another entity
*/
(function () {
'use strict';
var Scene = require('../scene');
var Component = require('../component');
module.exports = (function() {
// Inherit from the Component class
Component.extend(Collision);
// The name to refer to this component
Collision.prototype.name = 'Collision';
Collision.title = 'Collision';
// The function to call if a collision was detected
Collision.prototype.callback = null;
// The event to listen to and check for a collision
Collision.prototype.eventName = 'preRender';
// The component on other entities that can be collided with
// If none given, all can be collided with
Collision.prototype.componentCollidable = null;
function Collision(entity, componentCollidable, callback, eventName) {
this.entity = entity;
this.componentCollidable = componentCollidable;
this.callback = callback;
if (eventName !== null) {
this.eventName = eventName;
}
Collision.__super__.constructor.call(this, entity);
}
Collision.prototype.preRender = function(event, scene) {
if (this.eventName === event.type) {
this.check(event, scene);
}
};
Collision.prototype.mouseup = function(event, scene) {
if (this.eventName === event.type) {
this.check(event, scene);
}
};
Collision.prototype.mousedown = function(event, scene) {
if (this.eventName === event.type) {
this.check(event, scene);
}
};
Collision.prototype.mousemove = function(event, scene) {
if (this.eventName === event.type) {
this.check(event, scene);
}
};
// Check for a collision and act
Collision.prototype.check = function(event, scene) {
// Can't collide with a hidden entity
if (this.entity.display) {
// Loop through all entities
for (var i in scene.entities) {
var entity = scene.entities[i];
// Do we care if these entities overlap?
if ((this.entity !== entity) && entity.display && ((this.componentCollidable === null) || (this.componentCollidable in entity.components))) {
// Check if the entities overlap
if (Scene.isOverlap(this.entity, entity)) {
// Call the callback!
this.callback(event, scene, entity);
}
}
}
}
};
return Collision;
})();
})();
|
#!/usr/bin/env babel-node
import fs from 'fs';
import path from 'path';
import schema from '../data/schema';
import { graphql } from 'graphql';
import { introspectionQuery, printSchema } from 'graphql/utilities';
(async() => {
const result = await (graphql(schema, introspectionQuery));
if (result.errors) {
console.error(
'ERROR introspecting schema: ',
JSON.stringify(result.errors, null, 2)
);
} else {
fs.writeFileSync(
path.join(__dirname, '../data/schema.json'),
JSON.stringify(result, null, 2)
);
}
})();
fs.writeFileSync(
path.join(__dirname, '../data/schema.graphql'),
printSchema(schema)
);
|
function ask() {
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("What do you think of Node.js? ", function(answer) {
// TODO: Log the answer in a database
myanswer = answer
console.log("Thank you for your valuable feedback:", answer);
rl.close();
});
}
myanswer = "";
ask();
console.log("we've got :" + myanswer);
|
const convertSourceMap = require('convert-source-map')
const libCoverage = require('istanbul-lib-coverage')
const libSourceMaps = require('istanbul-lib-source-maps')
const fs = require('fs')
const Hash = require('./hash')
const path = require('path')
// TODO: write some unit tests for this class.
function SourceMaps (opts) {
this.cache = opts.cache
this.cacheDirectory = opts.cacheDirectory
this.sourceMapCache = libSourceMaps.createSourceMapStore()
this.loadedMaps = {}
this.hashCache = {}
}
SourceMaps.prototype.extractAndRegister = function (code, filename) {
var sourceMap = convertSourceMap.fromSource(code) || convertSourceMap.fromMapFileSource(code, path.dirname(filename))
if (sourceMap) {
var hash = Hash(code, filename)
if (this.cache && !this.hashCache[filename]) {
this.hashCache[filename] = hash
var mapPath = path.join(this.cacheDirectory, hash + '.map')
fs.writeFileSync(mapPath, sourceMap.toJSON())
} else {
this.sourceMapCache.registerMap(filename, sourceMap.sourcemap)
}
}
return sourceMap
}
SourceMaps.prototype.remapCoverage = function (obj) {
var transformed = this.sourceMapCache.transformCoverage(
libCoverage.createCoverageMap(obj)
)
return transformed.map.data
}
SourceMaps.prototype.reloadCachedSourceMaps = function (report) {
var _this = this
Object.keys(report).forEach(function (absFile) {
var fileReport = report[absFile]
if (fileReport && fileReport.contentHash) {
var hash = fileReport.contentHash
if (!(hash in _this.loadedMaps)) {
try {
var mapPath = path.join(_this.cacheDirectory, hash + '.map')
_this.loadedMaps[hash] = JSON.parse(fs.readFileSync(mapPath, 'utf8'))
} catch (e) {
// set to false to avoid repeatedly trying to load the map
_this.loadedMaps[hash] = false
}
}
if (_this.loadedMaps[hash]) {
_this.sourceMapCache.registerMap(absFile, _this.loadedMaps[hash])
}
}
})
}
module.exports = SourceMaps
|
/**
* @license Copyright (c) 2014, smrtlabs
* For licensing, see LICENSE
*/
"use strict";
var assert = require("chai").assert,
cached = require("gulp-cached"),
esformatter = require("gulp-esformatter"),
eslint = require("gulp-eslint"),
fs = require("fs"),
gulp = require("gulp"),
istanbul = require("gulp-istanbul"),
mocha = require("gulp-mocha"),
path = require("path");
/*eslint no-sync: 0 */
global.paths = {
"configs": {
"esformatter": path.join(__dirname, ".esformatter"),
"eslintrc": path.join(__dirname, ".eslintrc")
},
"coverage": {
"root": path.join(__dirname, "node_coverage")
},
"gulpfile": __filename,
"libs": {
"files": path.join(__dirname, "smrt-*/**/*.js")
},
"tests": {
"files": path.join(__dirname, "smrt-*/**/*.test.js")
},
"root": __dirname
};
global.paths.all = [
global.paths.gulpfile,
global.paths.libs.files,
global.paths.tests.files
];
gulp.task("beautify", function (done) {
fs.readFile(global.paths.configs.esformatter, function (err, config) {
assert.ifError(err);
gulp.src(global.paths.all)
.pipe(cached("beautifying"))
.pipe(esformatter(JSON.parse(config.toString("utf8"))))
.pipe(gulp.dest(global.paths.root))
.on("finish", done);
});
});
gulp.task("cover", function (done) {
gulp.src(global.paths.libs.files)
.pipe(istanbul())
.on("finish", function () {
gulp.src(global.paths.tests.files)
.pipe(mocha())
.pipe(istanbul.writeReports(global.paths.coverage.root))
.on("finish", done);
});
});
gulp.task("lint", ["beautify"], function (done) {
fs.readFile(global.paths.configs.eslintrc, function (err, config) {
assert.ifError(err);
gulp.src(global.paths.all)
.pipe(eslint(JSON.parse(config.toString("utf8"))))
.pipe(eslint.format())
.on("end", done);
});
});
gulp.task("test", ["lint"], function (done) {
Error.stackTraceLimit = Infinity;
gulp.src(global.paths.tests.files)
.pipe(mocha())
.on("finish", done);
});
gulp.task("watch", function () {
gulp.src(global.paths.all).pipe(cached("beautifying"));
gulp.watch(global.paths.all, ["default"]);
});
gulp.task("default", ["beautify", "lint", "test"]);
|
import * as React from 'react';
type AlignType = 'left' | 'center' | 'right';
type ColumnKey = string | number;
export type Cell = {
isScrolling?: boolean,
align?: AlignType,
className?: string,
highlighted?: bool,
width: number,
minWidth?: number,
maxWidth?: number,
height: number,
cell?: string | React.Node,
columnKey?: ColumnKey,
/**
* The row index that will be passed to `cellRenderer` to render.
*/
rowIndex: number,
/**
* Callback for when resizer knob (in FixedDataTableCell) is clicked
* to initialize resizing. Please note this is only on the cells
* in the header.
* @param number combinedWidth
* @param number left
* @param number width
* @param number minWidth
* @param number maxWidth
* @param number|string columnKey
* @param object event
*/
onColumnResize?: (combinedWidth: number, left: number, width: number,
minWidth: number, maxWidth: number, columnKey: ColumnKey, event: mixed) => any,
onColumnReorder?: Function,
/**
* The left offset in pixels of the cell.
*/
left?: number,
/**
* Flag for enhanced performance check
*/
pureRendering?: bool,
}
|
var randTree = new Tree();
function generate() {
for (var i = 0; i < 3; ++i) {
var children, n;
randTree.root.addChild({name: i});
randTree.root.children()[i].addChild();
if (Math.random() * 2 > 1) {
randTree.root.children()[i].addChild();
}
if (Math.random() * 2 > 1) {
children = randTree.root.children();
n = children.length;
children[Math.floor(Math.random() * n)].addChild();
}
if (Math.random() * 2 > 1) {
children = randTree.root.children();
n = children.length;
var childChild = children[Math.floor(Math.random() * n)];
children = childChild.children();
n = children.length;
children[Math.floor(Math.random() * n)].addChild();
children[Math.floor(Math.random() * n)].addChild();
}
}
}
generate();
function FBT(c, tree, konfig) {
var t = tree ? tree : new Tree();
var defaultConfig = {
zoomFactor : 1.1,
nodeRadius : 30,
nodeColor : '#057cb8',
nodeGlowColor : '#FF8C00'
};
var container = c ? c : document.body;
var paper = new Raphael(container);
container = $(container);
var config = defaultConfig;
if (konfig) {
for (var item in konfig) {
if (item in config) {
config[item] = konfig[item];
}
}
}
config.origH = container.height();
config.origW = container.width();
var effects = {
circle: {
grow: function() {
this.animate({'r': Math.floor(config.nodeRadius * 1.33)},
500,
'elastic')
.attr({'fill': 'darkorange'});
},
shrink: function() {
this.animate({'r': config.nodeRadius},
500,
'elastic')
.attr({'fill': '#057cb8'});
}
},
line: {
casterGrow: function() {
paper.getById(this.casterId).attr({'stroke-width': 4, 'stroke' : 'darkorange'});
},
casterShrink: function() {
paper.getById(this.casterId).animate({'stroke' : '#000'}, 100).attr('stroke-width', 3);
}
}
};
var svg;
var h, w, x, y;
paper.setStart();
function addNode(pos)
{
return paper.circle(pos.x, pos.y, 30).attr({
'fill' : '#057cb8',
'stroke-width' : 0
}).hover(effects.circle.grow, effects.circle.shrink).toBack().id;
}
var rootPos = {x: Math.floor(config.origW / 2), y: 50};
globalConfig = {
rootX : rootPos.x,
rootY : rootPos.y,
offsetY : 150
};
var nodes = [];
function bfs(root) {
nodes.push(root);
for (var i = 0; i < nodes.length; ++i) {
var node = nodes[i];
var children = node.children();
for (var c = 0; c < children.length; ++c) {
nodes.push(children[c]);
}
}
}
function bfsRender(root) {
if (root) {
paper.setStart();
nodes = [];
bfs(root);
var row = [];
var level = 0;
for (var i = 0; i < nodes.length + 1; ++i) {
var node = null;
if (i < nodes.length) {
node = nodes[i];
if (node.level() == level) {
row.push(node);
continue;
}
}
var config = {};
for (var key in globalConfig) {
if (globalConfig.hasOwnProperty(key)) {
config[key] = globalConfig[key];
}
}
var width = container.width() - 80;
if (row.length > 1) {
config.offsetX = width / (row.length - 1);
config.startX = 40;
}
else {
config.offsetX = width/2;
config.startX = width/2 + 40;
}
for (var c = 0; c < row.length; ++c) {
var pos = {x: config.startX + c * config.offsetX, y: 50 + level * config.offsetY};
if (row[c].parent()) {
var pid = row[c].parent().DOMid;
var parent = paper.getById(pid);
var cx = parent.attr('cx');
var cy = parent.attr('cy');
var seen = paper.path('M' + cx + ',' + cy + 'L' + pos.x + ',' + pos.y).attr('stroke-width', 3)
.hover(effects.line.grow, effects.line.shrink);
var shadow = paper.path('M' + cx + ',' + cy + 'L' + pos.x + ',' + pos.y).attr({'stroke-width': '15', 'stroke': 'transparent'});
shadow.casterId = seen.id;
shadow.hover(effects.line.casterGrow, effects.line.casterShrink);
}
row[c].DOMid = addNode(pos);
}
row = [];
if (node) {
level = node.level();
row.push(node);
}
}
}
for (var j = 0; j < nodes.length; ++j) {
paper.getById(nodes[j].DOMid).toFront();
}
origH = h = container.height();
origW = w = container.width();
x = y = 0;
paper.setViewBox(x, y, w, h);
svg = paper.setFinish();
}
bfsRender(t.root);
var down = 0;
var downX, downY, dx = 0, dy = 0, setX = 0, setY = 0, mousePosX, mousePosY;
window.addWheelListener(document.getElementById('fbt-container'), function(e) {
if (!down) {
e.preventDefault();
var rx = (mousePosX)/origW;
var ry = (mousePosY)/origH;
var SVGx = ((mousePosX)/origW) * w + x;
var SVGy = ((mousePosY)/origH) * h + y;
if (e.deltaY < 0) {
w = Math.round(w/config.zoomFactor);
h = Math.round(h/config.zoomFactor);
}
else {
w = Math.round(w * config.zoomFactor);
h = Math.round(h * config.zoomFactor);
}
x = Math.round((SVGx) - rx * w);
y = Math.round((SVGy) - ry * h);
paper.setViewBox(x, y, Math.round(w), Math.round(h));
}
});
container.mousedown(function(e) {
if (e.which == 1) {
down = 1;
downX = e.pageX;
downY = e.pageY;
}
});
container.mousemove(function(e) {
mousePosX = (e.pageX - Math.round(container.offset().left));
mousePosY = (e.pageY - Math.round(container.offset().top));
if (down) {
var curX = e.pageX;
var curY = e.pageY;
var scale = w/origW;
dx = (curX - downX) * scale;
if (setX !== 0) {
dx += setX;
}
dy = (curY - downY) * scale;
if (setY !== 0) {
dy += setY;
}
svg.transform('T' + dx + ',' + dy);
}
});
container.mouseup(function() {
setX = dx;
setY = dy;
down = 0;
});
container.dblclick(function(e) {
e.preventDefault();
e.stopPropagation();
svg.transform('T0,0');
x = y = dx = dy = setX = setY = 0;
paper.setViewBox(0, 0, origW, origH);
h = origH;
w = origW;
});
$(window).resize(function() {
paper.clear();
paper.setStart();
bfsRender(t.root);
svg = paper.setFinish();
svg.transform('T' + dx + ',' + dy);
});
}
FBT(document.getElementById('fbt-container'), randTree);
|
var OptionParser, argv, coffeecup, compile, fs, handle_error, log, options, path, switches, usage, write;
coffeecup = require('./coffeecup');
fs = require('fs');
path = require('path');
log = console.log;
OptionParser = require('coffee-script/lib/coffee-script/optparse').OptionParser;
argv = process.argv.slice(2);
options = null;
handle_error = function(err) {
if (err) return console.log(err.stack);
};
compile = function(input_path, output_directory, js, namespace) {
if (namespace == null) namespace = 'templates';
return fs.readFile(input_path, 'utf-8', function(err, contents) {
var ext, func, name, output;
handle_error(err);
name = path.basename(input_path, path.extname(input_path));
if (!js) {
output = coffeecup.render(contents, options);
ext = '.html';
} else {
func = coffeecup.compile(contents, options);
output = "(function(){ \n this." + namespace + " || (this." + namespace + " = {});\n this." + namespace + "[" + (JSON.stringify(name)) + "] = " + func + ";\n}).call(this);";
ext = '.js';
}
return write(input_path, name, output, output_directory, ext);
});
};
write = function(input_path, name, contents, output_directory, ext) {
var dir, filename;
filename = name + ext;
dir = output_directory || path.dirname(input_path);
return path.exists(dir, function(exists) {
var output_path;
if (!exists) fs.mkdirSync(dir, 0777);
output_path = path.join(dir, filename);
if (contents.length <= 0) contents = ' ';
return fs.writeFile(output_path, contents, function(err) {
handle_error(err);
if (options.print) log(contents);
if (options.watch) return log("Compiled " + input_path);
});
});
};
usage = 'Usage:\n coffeecup [options] path/to/template.coffee';
switches = [['-j', '--js', 'compile template to js function (template + embedded renderer)'], ['-b', '--bare', 'use with -j to compile template to js (template only)'], ['-c', '--core', 'use with -j to compile renderer to js (renderer only)'], ['-n', '--namespace [name]', 'global object holding the templates (default: "templates")'], ['-w', '--watch', 'watch templates for changes, and recompile'], ['-o', '--output [dir]', 'set the directory for compiled html'], ['-p', '--print', 'print the compiled html to stdout'], ['-f', '--format', 'apply line breaks and indentation to html output'], ['-u', '--utils', 'add helper locals (currently only "render")'], ['-z', '--optimize', 'optimize resulting JS'], ['-v', '--version', 'display coffeecup version'], ['-h', '--help', 'display this help message']];
this.run = function() {
var args, file, parser;
parser = new OptionParser(switches, usage);
options = parser.parse(argv);
args = options.arguments;
delete options.arguments;
if (options.help || argv.length === 0) log(parser.help());
if (options.version) log(coffeecup.version);
if (options.utils) {
if (options.locals == null) options.locals = {};
options.locals.render = function(file) {
var contents;
contents = fs.readFileSync(file, 'utf-8');
return coffeecup.render(contents, options);
};
}
if (args.length > 0) {
file = args[0];
if (options.watch) {
fs.watchFile(file, {
persistent: true,
interval: 500
}, function(curr, prev) {
if (curr.size === prev.size && curr.mtime.getTime() === prev.mtime.getTime()) {
return;
}
return compile(file, options.output, options.js, options.namespace);
});
}
return compile(file, options.output, options.js, options.namespace);
}
};
|
'use strict';
(function(module) {
const homeController = {};
homeController.render = function() {
//reset active tab
$('.tab').removeClass('active');
$('.tab:first').addClass('active');
$('hr').show();
$('.tab-content').hide();
$('#intro').fadeIn();
}
module.homeController = homeController;
})(window);
|
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
// TreeNode定义
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
};
// 判断是否为有效数
var isValid = function(val) {
if (val || val === 0) {
return true;
}
return false;
};
// array to tree
var toTree = function(arr) {
if (arr.length) {
var rootNode = new TreeNode(arr[0]);
var stack = [rootNode];
var idx = 1;
while (stack.length && idx < arr.length) {
var curNode = stack.pop();
var num1 = arr[idx];
idx++;
var num2 = arr[idx];
idx++;
if (isValid(num2)) {
curNode.right = new TreeNode(num2);
stack.push(curNode.right);
}
if (isValid(num1)) {
curNode.left = new TreeNode(num1);
stack.push(curNode.left);
}
// console.log('curNode: ', curNode);
}
return rootNode;
} else {
return null;
}
};
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrderBottom = function(root) {
let stack = [], list = [], result = [];
if(root) {
stack.push(root);
while(stack.length) {
while(stack.length) {
list.push(stack.pop());
}
let arr = [];
while(list.length) {
let elem = list.pop();
arr.push(elem.val);
if(elem.left) {
stack.push(elem.left);
}
if(elem.right) {
stack.push(elem.right);
}
}
result.unshift(arr);
}
}
return result;
};
let nums = [3,9,20,null,null,15,7];
console.info('levelOrderBottom: ', levelOrderBottom(toTree(nums)));
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.11.4-master-5034a04
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.button
* @description
*
* Button
*/
angular
.module('material.components.button', [ 'material.core' ])
.directive('mdButton', MdButtonDirective);
/**
* @ngdoc directive
* @name mdButton
* @module material.components.button
*
* @restrict E
*
* @description
* `<md-button>` is a button directive with optional ink ripples (default enabled).
*
* If you supply a `href` or `ng-href` attribute, it will become an `<a>` element. Otherwise, it will
* become a `<button>` element. As per the [Material Design specifications](http://www.google.com/design/spec/style/color.html#color-ui-color-application)
* the FAB button background is filled with the accent color [by default]. The primary color palette may be used with
* the `md-primary` class.
*
* @param {boolean=} md-no-ink If present, disable ripple ink effects.
* @param {expression=} ng-disabled En/Disable based on the expression
* @param {string=} md-ripple-size Overrides the default ripple size logic. Options: `full`, `partial`, `auto`
* @param {string=} aria-label Adds alternative text to button for accessibility, useful for icon buttons.
* If no default text is found, a warning will be logged.
*
* @usage
*
* Regular buttons:
*
* <hljs lang="html">
* <md-button> Flat Button </md-button>
* <md-button href="http://google.com"> Flat link </md-button>
* <md-button class="md-raised"> Raised Button </md-button>
* <md-button ng-disabled="true"> Disabled Button </md-button>
* <md-button>
* <md-icon md-svg-src="your/icon.svg"></md-icon>
* Register Now
* </md-button>
* </hljs>
*
* FAB buttons:
*
* <hljs lang="html">
* <md-button class="md-fab" aria-label="FAB">
* <md-icon md-svg-src="your/icon.svg"></md-icon>
* </md-button>
* <!-- mini-FAB -->
* <md-button class="md-fab md-mini" aria-label="Mini FAB">
* <md-icon md-svg-src="your/icon.svg"></md-icon>
* </md-button>
* <!-- Button with SVG Icon -->
* <md-button class="md-icon-button" aria-label="Custom Icon Button">
* <md-icon md-svg-icon="path/to/your.svg"></md-icon>
* </md-button>
* </hljs>
*/
function MdButtonDirective($mdButtonInkRipple, $mdTheming, $mdAria, $timeout) {
return {
restrict: 'EA',
replace: true,
transclude: true,
template: getTemplate,
link: postLink
};
function isAnchor(attr) {
return angular.isDefined(attr.href) || angular.isDefined(attr.ngHref) || angular.isDefined(attr.ngLink) || angular.isDefined(attr.uiSref);
}
function getTemplate(element, attr) {
return isAnchor(attr) ?
'<a class="md-button" ng-transclude></a>' :
'<button class="md-button" ng-transclude></button>';
}
function postLink(scope, element, attr) {
var node = element[0];
$mdTheming(element);
$mdButtonInkRipple.attach(scope, element);
var elementHasText = node.textContent.trim();
if (!elementHasText) {
$mdAria.expect(element, 'aria-label');
}
// For anchor elements, we have to set tabindex manually when the
// element is disabled
if (isAnchor(attr) && angular.isDefined(attr.ngDisabled) ) {
scope.$watch(attr.ngDisabled, function(isDisabled) {
element.attr('tabindex', isDisabled ? -1 : 0);
});
}
// disabling click event when disabled is true
element.on('click', function(e){
if (attr.disabled === true) {
e.preventDefault();
e.stopImmediatePropagation();
}
});
// restrict focus styles to the keyboard
scope.mouseActive = false;
element.on('mousedown', function() {
scope.mouseActive = true;
$timeout(function(){
scope.mouseActive = false;
}, 100);
})
.on('focus', function() {
if (scope.mouseActive === false) {
element.addClass('md-focused');
}
})
.on('blur', function(ev) {
element.removeClass('md-focused');
});
}
}
MdButtonDirective.$inject = ["$mdButtonInkRipple", "$mdTheming", "$mdAria", "$timeout"];
})(window, window.angular);
|
var _ = require('lodash');
function getCurrentNamespace(parentNamespace, tasks) {
if (_.isEmpty(parentNamespace) && _.isEmpty(tasks.namespace)) {
return '';
} else if (_.isEmpty(parentNamespace)) {
return tasks.namespace + '.';
} else if (_.isEmpty(tasks.namespace)) {
return parentNamespace;
} else {
return parentNamespace + tasks.namespace + '.';
}
}
function processNamespace(tasks, parentNamespace) {
if (!tasks) {
return;
}
tasks._completeNamespace = getCurrentNamespace(parentNamespace, tasks);
_.forEach(tasks._imports, imported => processNamespace(imported, tasks._completeNamespace));
}
module.exports = function(tasks, parentNamespace) {
if (_.isEmpty(parentNamespace)) {
processNamespace(tasks, '');
} else {
processNamespace(tasks, parentNamespace);
}
return tasks;
};
|
const { AbstractLiteralEntry } = require('./AbstractLiteralEntry');
class NameEntry extends AbstractLiteralEntry {
constructor (value) {
super('name', value);
}
}
module.exports.NameEntry = NameEntry;
|
/*!
* customize-engine-uglify <https://github.com/nknapp/customize-engine-uglify>
*
* Copyright (c) 2016 Nils Knappmeier.
* Released under the MIT license.
*/
'use strict'
var _ = require('lodash')
var uglify = require('uglify-js')
var orderFiles = require('./lib/orderFiles')
module.exports = {
schema: require('./schema.js'),
defaultConfig: {
files: {},
dependencies: {},
options: {
outFileName: 'bundle.js',
outSourceMap: 'bundle.js.map',
output: {
comments: /(@license|@preserve|^!)/
}
}
},
preprocessConfig: function (config) {
// No preprocessing needed at the moment, since we just merge objects
return config
},
watched: function (config) {
return _.values(config.files)
},
/**
* Run uglify and store the resulting JavaScript and Source-Map into the result object
* @param config
*/
run: function (config) {
var inputFileOrder = orderFiles(Object.keys(config.files), config.dependencies)
var inputFiles = inputFileOrder.map(function (filename) {
return config.files[filename]
})
var outputFiles = {}
if (inputFiles.length === 0) {
outputFiles[config.options.outFileName] = ''
return outputFiles
}
var result = uglify.minify(inputFiles, config.options)
outputFiles[config.options.outFileName] = result.code
outputFiles[config.options.outSourceMap] = result.map
return outputFiles
}
}
|
Grailbird.data.tweets_2019_08 =
[
{
"created_at": "Sat Aug 31 19:14:49 +0000 2019",
"id": 1167878427598176300,
"id_str": "1167878427598176257",
"text": "@i96jms @tabamatu Aaaahhh. We missed you by a few hours. Have a fab evening.",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "i96jms",
"name": "Jane",
"id": 245852213,
"id_str": "245852213",
"indices": [
0,
7
]
},
{
"screen_name": "tabamatu",
"name": "Andy Parker",
"id": 19486018,
"id_str": "19486018",
"indices": [
8,
17
]
}
],
"urls": []
},
"source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>",
"in_reply_to_status_id": 1167877337221714000,
"in_reply_to_status_id_str": "1167877337221713920",
"in_reply_to_user_id": 245852213,
"in_reply_to_user_id_str": "245852213",
"in_reply_to_screen_name": "i96jms",
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 527,
"friends_count": 279,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1015,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5600,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 1,
"favorited": false,
"retweeted": false,
"lang": "en"
},
{
"created_at": "Sat Aug 31 19:11:47 +0000 2019",
"id": 1167877664335491000,
"id_str": "1167877664335491086",
"text": "@ElusiveBrew @NagsHeadReading You're meant to be having a whizz, not taking photos of the art on the walls 😂🤣",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "ElusiveBrew",
"name": "Elusive Brewing",
"id": 410605445,
"id_str": "410605445",
"indices": [
0,
12
]
},
{
"screen_name": "NagsHeadReading",
"name": "Nag's Head Reading",
"id": 512094009,
"id_str": "512094009",
"indices": [
13,
29
]
}
],
"urls": []
},
"source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>",
"in_reply_to_status_id": 1167874853874987000,
"in_reply_to_status_id_str": "1167874853874987009",
"in_reply_to_user_id": 410605445,
"in_reply_to_user_id_str": "410605445",
"in_reply_to_screen_name": "ElusiveBrew",
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 527,
"friends_count": 279,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1015,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5600,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 1,
"favorited": false,
"retweeted": false,
"lang": "en"
},
{
"created_at": "Sat Aug 31 19:07:47 +0000 2019",
"id": 1167876655404085200,
"id_str": "1167876655404085250",
"text": "@ElusiveBrew @ahoppyplace @Lovibonds That is so cool. My train beers have just stepped up to a while new level.",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "ElusiveBrew",
"name": "Elusive Brewing",
"id": 410605445,
"id_str": "410605445",
"indices": [
0,
12
]
},
{
"screen_name": "ahoppyplace",
"name": "@ahoppyplace",
"id": 1079431118196301800,
"id_str": "1079431118196301826",
"indices": [
13,
25
]
},
{
"screen_name": "Lovibonds",
"name": "Lovibonds Brewery",
"id": 202168643,
"id_str": "202168643",
"indices": [
26,
36
]
}
],
"urls": []
},
"source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>",
"in_reply_to_status_id": 1167801532458393600,
"in_reply_to_status_id_str": "1167801532458393601",
"in_reply_to_user_id": 410605445,
"in_reply_to_user_id_str": "410605445",
"in_reply_to_screen_name": "ElusiveBrew",
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 527,
"friends_count": 279,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1015,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5600,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 2,
"favorited": false,
"retweeted": false,
"lang": "en"
},
{
"created_at": "Fri Aug 30 22:25:50 +0000 2019",
"id": 1167564107052134400,
"id_str": "1167564107052134402",
"text": "Those peeps in the background are queuing for this, but I got the last one 🤣 Nom nom nom 😋 #meatopia #dessert… https://t.co/zZgNmpUrEu",
"truncated": true,
"entities": {
"hashtags": [
{
"text": "meatopia",
"indices": [
91,
100
]
},
{
"text": "dessert",
"indices": [
101,
109
]
}
],
"symbols": [],
"user_mentions": [],
"urls": [
{
"url": "https://t.co/zZgNmpUrEu",
"expanded_url": "https://twitter.com/i/web/status/1167564107052134402",
"display_url": "twitter.com/i/web/status/1…",
"indices": [
111,
134
]
}
]
},
"source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 527,
"friends_count": 285,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1010,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5597,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 1,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Fri Aug 30 18:53:37 +0000 2019",
"id": 1167510701868507100,
"id_str": "1167510701868507136",
"text": "I've found my happy place, and they have a great selection of craft beers to help all this meat go down 😋😋😋😋… https://t.co/a515nKDAuQ",
"truncated": true,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [
{
"url": "https://t.co/a515nKDAuQ",
"expanded_url": "https://twitter.com/i/web/status/1167510701868507136",
"display_url": "twitter.com/i/web/status/1…",
"indices": [
110,
133
]
}
]
},
"source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 527,
"friends_count": 285,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1010,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5597,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 1,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Fri Aug 30 17:28:40 +0000 2019",
"id": 1167489325560451000,
"id_str": "1167489325560451075",
"text": "RT @ClaireLSeymour: Look at his happy little face😊 @MeatopiaUK #XmasInAugust https://t.co/W31ZFRvHQn",
"truncated": false,
"entities": {
"hashtags": [
{
"text": "XmasInAugust",
"indices": [
63,
76
]
}
],
"symbols": [],
"user_mentions": [
{
"screen_name": "ClaireLSeymour",
"name": "Claire Seymour",
"id": 794529843023056900,
"id_str": "794529843023056896",
"indices": [
3,
18
]
},
{
"screen_name": "MeatopiaUK",
"name": "MeatopiaUK",
"id": 1381456454,
"id_str": "1381456454",
"indices": [
51,
62
]
}
],
"urls": [],
"media": [
{
"id": 1167474899717435400,
"id_str": "1167474899717435394",
"indices": [
77,
100
],
"media_url": "http://pbs.twimg.com/media/EDO0PFnXsAIkTlB.jpg",
"media_url_https": "https://pbs.twimg.com/media/EDO0PFnXsAIkTlB.jpg",
"url": "https://t.co/W31ZFRvHQn",
"display_url": "pic.twitter.com/W31ZFRvHQn",
"expanded_url": "https://twitter.com/ClaireLSeymour/status/1167474931728297989/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 510,
"h": 680,
"resize": "fit"
},
"large": {
"w": 1536,
"h": 2048,
"resize": "fit"
},
"medium": {
"w": 900,
"h": 1200,
"resize": "fit"
}
},
"source_status_id": 1167474931728298000,
"source_status_id_str": "1167474931728297989",
"source_user_id": 794529843023056900,
"source_user_id_str": "794529843023056896"
}
]
},
"extended_entities": {
"media": [
{
"id": 1167474899717435400,
"id_str": "1167474899717435394",
"indices": [
77,
100
],
"media_url": "http://pbs.twimg.com/media/EDO0PFnXsAIkTlB.jpg",
"media_url_https": "https://pbs.twimg.com/media/EDO0PFnXsAIkTlB.jpg",
"url": "https://t.co/W31ZFRvHQn",
"display_url": "pic.twitter.com/W31ZFRvHQn",
"expanded_url": "https://twitter.com/ClaireLSeymour/status/1167474931728297989/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 510,
"h": 680,
"resize": "fit"
},
"large": {
"w": 1536,
"h": 2048,
"resize": "fit"
},
"medium": {
"w": 900,
"h": 1200,
"resize": "fit"
}
},
"source_status_id": 1167474931728298000,
"source_status_id_str": "1167474931728297989",
"source_user_id": 794529843023056900,
"source_user_id_str": "794529843023056896"
}
]
},
"source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 527,
"friends_count": 285,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1010,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5597,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"retweeted_status": {
"created_at": "Fri Aug 30 16:31:29 +0000 2019",
"id": 1167474931728298000,
"id_str": "1167474931728297989",
"text": "Look at his happy little face😊 @MeatopiaUK #XmasInAugust https://t.co/W31ZFRvHQn",
"truncated": false,
"entities": {
"hashtags": [
{
"text": "XmasInAugust",
"indices": [
43,
56
]
}
],
"symbols": [],
"user_mentions": [
{
"screen_name": "MeatopiaUK",
"name": "MeatopiaUK",
"id": 1381456454,
"id_str": "1381456454",
"indices": [
31,
42
]
}
],
"urls": [],
"media": [
{
"id": 1167474899717435400,
"id_str": "1167474899717435394",
"indices": [
57,
80
],
"media_url": "http://pbs.twimg.com/media/EDO0PFnXsAIkTlB.jpg",
"media_url_https": "https://pbs.twimg.com/media/EDO0PFnXsAIkTlB.jpg",
"url": "https://t.co/W31ZFRvHQn",
"display_url": "pic.twitter.com/W31ZFRvHQn",
"expanded_url": "https://twitter.com/ClaireLSeymour/status/1167474931728297989/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 510,
"h": 680,
"resize": "fit"
},
"large": {
"w": 1536,
"h": 2048,
"resize": "fit"
},
"medium": {
"w": 900,
"h": 1200,
"resize": "fit"
}
}
}
]
},
"extended_entities": {
"media": [
{
"id": 1167474899717435400,
"id_str": "1167474899717435394",
"indices": [
57,
80
],
"media_url": "http://pbs.twimg.com/media/EDO0PFnXsAIkTlB.jpg",
"media_url_https": "https://pbs.twimg.com/media/EDO0PFnXsAIkTlB.jpg",
"url": "https://t.co/W31ZFRvHQn",
"display_url": "pic.twitter.com/W31ZFRvHQn",
"expanded_url": "https://twitter.com/ClaireLSeymour/status/1167474931728297989/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 510,
"h": 680,
"resize": "fit"
},
"large": {
"w": 1536,
"h": 2048,
"resize": "fit"
},
"medium": {
"w": 900,
"h": 1200,
"resize": "fit"
}
}
}
]
},
"source": "<a href=\"http://twitter.com/download/android\" rel=\"nofollow\">Twitter for Android</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 794529843023056900,
"id_str": "794529843023056896",
"name": "Claire Seymour",
"screen_name": "ClaireLSeymour",
"location": "South East, England",
"description": "",
"url": "https://t.co/MfgIbvt5DX",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/MfgIbvt5DX",
"expanded_url": "http://cluckcorner.com",
"display_url": "cluckcorner.com",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 16,
"friends_count": 38,
"listed_count": 0,
"created_at": "Fri Nov 04 13:20:51 +0000 2016",
"favourites_count": 777,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 186,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "F5F8FA",
"profile_background_image_url": null,
"profile_background_image_url_https": null,
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/861612986024292352/807buxlG_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/861612986024292352/807buxlG_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/794529843023056896/1501241179",
"profile_link_color": "1DA1F2",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": true,
"default_profile_image": false,
"following": true,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": {
"id": "08be9e4ebe3d037d",
"url": "https://api.twitter.com/1.1/geo/id/08be9e4ebe3d037d.json",
"place_type": "city",
"name": "Poplar",
"full_name": "Poplar, London",
"country_code": "GB",
"country": "United Kingdom",
"contained_within": [],
"bounding_box": {
"type": "Polygon",
"coordinates": [
[
[
-0.080028,
51.48432
],
[
0.009989,
51.48432
],
[
0.009989,
51.545341
],
[
-0.080028,
51.545341
]
]
]
},
"attributes": {}
},
"contributors": null,
"is_quote_status": false,
"retweet_count": 3,
"favorite_count": 4,
"favorited": true,
"retweeted": true,
"possibly_sensitive": false,
"lang": "en"
},
"is_quote_status": false,
"retweet_count": 3,
"favorite_count": 0,
"favorited": true,
"retweeted": true,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Wed Aug 28 18:59:31 +0000 2019",
"id": 1166787412942606300,
"id_str": "1166787412942606342",
"text": "@MeatopiaUK do we have to print our tickets or will the PDF on our phones do the trick?",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "MeatopiaUK",
"name": "MeatopiaUK",
"id": 1381456454,
"id_str": "1381456454",
"indices": [
0,
11
]
}
],
"urls": []
},
"source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": 1381456454,
"in_reply_to_user_id_str": "1381456454",
"in_reply_to_screen_name": "MeatopiaUK",
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 526,
"friends_count": 286,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1009,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5594,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"lang": "en"
},
{
"created_at": "Sat Aug 24 21:47:12 +0000 2019",
"id": 1165380060418924500,
"id_str": "1165380060418924544",
"text": "Damned you @CavallsWorld !!! Well over 20 years after leaving high school, hearing Boys 2 Men (my Mrs is a big fan)… https://t.co/T4ABpcaBs0",
"truncated": true,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "CavallsWorld",
"name": "Cavall Burgess",
"id": 515624343,
"id_str": "515624343",
"indices": [
11,
24
]
}
],
"urls": [
{
"url": "https://t.co/T4ABpcaBs0",
"expanded_url": "https://twitter.com/i/web/status/1165380060418924544",
"display_url": "twitter.com/i/web/status/1…",
"indices": [
117,
140
]
}
]
},
"source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 526,
"friends_count": 284,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1008,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5593,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"lang": "en"
},
{
"created_at": "Sat Aug 24 19:13:26 +0000 2019",
"id": 1165341361907916800,
"id_str": "1165341361907916802",
"text": "@JohnStoneFit Oooof!! Makes the idea of dashcams on ya bike less of a silly idea after all. Glad you're ok mate.",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "JohnStoneFit",
"name": "Stoney",
"id": 69874062,
"id_str": "69874062",
"indices": [
0,
13
]
}
],
"urls": []
},
"source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>",
"in_reply_to_status_id": 1165289012267032600,
"in_reply_to_status_id_str": "1165289012267032577",
"in_reply_to_user_id": 69874062,
"in_reply_to_user_id_str": "69874062",
"in_reply_to_screen_name": "JohnStoneFit",
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 526,
"friends_count": 284,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1008,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5593,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"lang": "en"
},
{
"created_at": "Sat Aug 24 17:43:57 +0000 2019",
"id": 1165318843394343000,
"id_str": "1165318843394342912",
"text": "Jeez… I really shouldn't have tried quite so many colognes in Boots… I stink like a polecat & I'm gagging when the… https://t.co/RDy3SPsHcx",
"truncated": true,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [
{
"url": "https://t.co/RDy3SPsHcx",
"expanded_url": "https://twitter.com/i/web/status/1165318843394342912",
"display_url": "twitter.com/i/web/status/1…",
"indices": [
120,
143
]
}
]
},
"source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 526,
"friends_count": 284,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1008,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5593,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"lang": "en"
},
{
"created_at": "Sat Aug 24 17:10:44 +0000 2019",
"id": 1165310482745614300,
"id_str": "1165310482745614336",
"text": "@JohnStoneFit @BrewdogReading Niiice!",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "JohnStoneFit",
"name": "Stoney",
"id": 69874062,
"id_str": "69874062",
"indices": [
0,
13
]
},
{
"screen_name": "BrewdogReading",
"name": "BrewDog Reading",
"id": 2644232003,
"id_str": "2644232003",
"indices": [
14,
29
]
}
],
"urls": []
},
"source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>",
"in_reply_to_status_id": 1165291149508141000,
"in_reply_to_status_id_str": "1165291149508141056",
"in_reply_to_user_id": 69874062,
"in_reply_to_user_id_str": "69874062",
"in_reply_to_screen_name": "JohnStoneFit",
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 526,
"friends_count": 284,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1008,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5593,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"lang": "en"
},
{
"created_at": "Sat Aug 24 15:32:43 +0000 2019",
"id": 1165285817226616800,
"id_str": "1165285817226616835",
"text": "Come on @BrewdogReading, I've drooling over the prospect of the Arrogant Bastard for months now. The barrel aging i… https://t.co/CElaHG8jEY",
"truncated": true,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "BrewdogReading",
"name": "BrewDog Reading",
"id": 2644232003,
"id_str": "2644232003",
"indices": [
8,
23
]
}
],
"urls": [
{
"url": "https://t.co/CElaHG8jEY",
"expanded_url": "https://twitter.com/i/web/status/1165285817226616835",
"display_url": "twitter.com/i/web/status/1…",
"indices": [
117,
140
]
}
]
},
"source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 526,
"friends_count": 284,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1008,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5593,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 1,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Thu Aug 22 17:55:03 +0000 2019",
"id": 1164596859932958700,
"id_str": "1164596859932958720",
"text": "Holy sheeet, I've got some saving to do... £69 + £105 + SQ for three quarts of beer 🤭 https://t.co/HcYgoLUDc0",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"id": 1164596858838233000,
"id_str": "1164596858838233088",
"indices": [
86,
109
],
"media_url": "http://pbs.twimg.com/media/ECl6rD2WsAA0rFe.jpg",
"media_url_https": "https://pbs.twimg.com/media/ECl6rD2WsAA0rFe.jpg",
"url": "https://t.co/HcYgoLUDc0",
"display_url": "pic.twitter.com/HcYgoLUDc0",
"expanded_url": "https://twitter.com/lildude/status/1164596859932958720/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 680,
"h": 680,
"resize": "fit"
},
"medium": {
"w": 1024,
"h": 1024,
"resize": "fit"
},
"large": {
"w": 1024,
"h": 1024,
"resize": "fit"
}
}
}
]
},
"extended_entities": {
"media": [
{
"id": 1164596858838233000,
"id_str": "1164596858838233088",
"indices": [
86,
109
],
"media_url": "http://pbs.twimg.com/media/ECl6rD2WsAA0rFe.jpg",
"media_url_https": "https://pbs.twimg.com/media/ECl6rD2WsAA0rFe.jpg",
"url": "https://t.co/HcYgoLUDc0",
"display_url": "pic.twitter.com/HcYgoLUDc0",
"expanded_url": "https://twitter.com/lildude/status/1164596859932958720/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 680,
"h": 680,
"resize": "fit"
},
"medium": {
"w": 1024,
"h": 1024,
"resize": "fit"
},
"large": {
"w": 1024,
"h": 1024,
"resize": "fit"
}
}
}
]
},
"source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 526,
"friends_count": 284,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1008,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5588,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Thu Aug 22 16:43:03 +0000 2019",
"id": 1164578743169486800,
"id_str": "1164578743169486849",
"text": "Absolutely brilliant!!! Brilliant cast, story and production. Think I might need to do this theatre thing more often.",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
},
"source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>",
"in_reply_to_status_id": 1164533731857707000,
"in_reply_to_status_id_str": "1164533731857707008",
"in_reply_to_user_id": 8812362,
"in_reply_to_user_id_str": "8812362",
"in_reply_to_screen_name": "lildude",
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 526,
"friends_count": 284,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1008,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5588,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 3,
"favorited": false,
"retweeted": false,
"lang": "en"
},
{
"created_at": "Thu Aug 22 13:44:12 +0000 2019",
"id": 1164533731857707000,
"id_str": "1164533731857707008",
"text": "My first ever theatre experience and it's Hamilton and I don't think we could get any closer to the action without… https://t.co/ps25hC6P4b",
"truncated": true,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [
{
"url": "https://t.co/ps25hC6P4b",
"expanded_url": "https://twitter.com/i/web/status/1164533731857707008",
"display_url": "twitter.com/i/web/status/1…",
"indices": [
116,
139
]
}
]
},
"source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 526,
"friends_count": 284,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1008,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5588,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 1,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Tue Aug 20 17:47:17 +0000 2019",
"id": 1163870129823932400,
"id_str": "1163870129823932422",
"text": "RT @no_itsHueina: to everyone singing the lion king at this picture: the words are “nants ingonayama, bagithi Baba” and it means “here come…",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "no_itsHueina",
"name": "Wayna who?",
"id": 2151840007,
"id_str": "2151840007",
"indices": [
3,
16
]
}
],
"urls": []
},
"source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 526,
"friends_count": 285,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1008,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5585,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"retweeted_status": {
"created_at": "Sun Aug 18 18:36:20 +0000 2019",
"id": 1163157698088583200,
"id_str": "1163157698088583168",
"text": "to everyone singing the lion king at this picture: the words are “nants ingonayama, bagithi Baba” and it means “her… https://t.co/TFN6DgX0yT",
"truncated": true,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [
{
"url": "https://t.co/TFN6DgX0yT",
"expanded_url": "https://twitter.com/i/web/status/1163157698088583168",
"display_url": "twitter.com/i/web/status/1…",
"indices": [
117,
140
]
}
]
},
"source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 2151840007,
"id_str": "2151840007",
"name": "Wayna who?",
"screen_name": "no_itsHueina",
"location": "The Bad Place",
"description": "don’t hate. educate ||🇦🇸🇹🇴🇯🇵🌺🌸🍥 || kū kia’i mauna ||",
"url": null,
"entities": {
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 827,
"friends_count": 324,
"listed_count": 1,
"created_at": "Wed Oct 23 23:21:32 +0000 2013",
"favourites_count": 12342,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 4826,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "C0DEED",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": true,
"profile_image_url": "http://pbs.twimg.com/profile_images/1126674015118958592/a62IXx7X_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1126674015118958592/a62IXx7X_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/2151840007/1565152824",
"profile_link_color": "ABB8C2",
"profile_sidebar_border_color": "FFFFFF",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": true,
"quoted_status_id": 1161037928665104400,
"quoted_status_id_str": "1161037928665104384",
"quoted_status": {
"created_at": "Mon Aug 12 22:13:07 +0000 2019",
"id": 1161037928665104400,
"id_str": "1161037928665104384",
"text": "Kenya 🇰🇪 https://t.co/OUNEOPfdJ6",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"id": 1161037917629898800,
"id_str": "1161037917629898753",
"indices": [
9,
32
],
"media_url": "http://pbs.twimg.com/media/EBzV1asW4AEcM-6.jpg",
"media_url_https": "https://pbs.twimg.com/media/EBzV1asW4AEcM-6.jpg",
"url": "https://t.co/OUNEOPfdJ6",
"display_url": "pic.twitter.com/OUNEOPfdJ6",
"expanded_url": "https://twitter.com/EarthDiscovers/status/1161037928665104384/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 546,
"h": 680,
"resize": "fit"
},
"large": {
"w": 822,
"h": 1024,
"resize": "fit"
},
"medium": {
"w": 822,
"h": 1024,
"resize": "fit"
}
}
}
]
},
"extended_entities": {
"media": [
{
"id": 1161037917629898800,
"id_str": "1161037917629898753",
"indices": [
9,
32
],
"media_url": "http://pbs.twimg.com/media/EBzV1asW4AEcM-6.jpg",
"media_url_https": "https://pbs.twimg.com/media/EBzV1asW4AEcM-6.jpg",
"url": "https://t.co/OUNEOPfdJ6",
"display_url": "pic.twitter.com/OUNEOPfdJ6",
"expanded_url": "https://twitter.com/EarthDiscovers/status/1161037928665104384/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 546,
"h": 680,
"resize": "fit"
},
"large": {
"w": 822,
"h": 1024,
"resize": "fit"
},
"medium": {
"w": 822,
"h": 1024,
"resize": "fit"
}
}
},
{
"id": 1161037922327572500,
"id_str": "1161037922327572482",
"indices": [
9,
32
],
"media_url": "http://pbs.twimg.com/media/EBzV1sMXsAIEPPs.jpg",
"media_url_https": "https://pbs.twimg.com/media/EBzV1sMXsAIEPPs.jpg",
"url": "https://t.co/OUNEOPfdJ6",
"display_url": "pic.twitter.com/OUNEOPfdJ6",
"expanded_url": "https://twitter.com/EarthDiscovers/status/1161037928665104384/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"medium": {
"w": 828,
"h": 1024,
"resize": "fit"
},
"large": {
"w": 828,
"h": 1024,
"resize": "fit"
},
"small": {
"w": 550,
"h": 680,
"resize": "fit"
}
}
}
]
},
"source": "<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 827585192328044500,
"id_str": "827585192328044546",
"name": "Earth",
"screen_name": "EarthDiscovers",
"location": "dm for credit / removal",
"description": "Content is not ours, credit to the owners.",
"url": null,
"entities": {
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 41649,
"friends_count": 3995,
"listed_count": 18,
"created_at": "Fri Feb 03 18:31:00 +0000 2017",
"favourites_count": 31,
"utc_offset": null,
"time_zone": null,
"geo_enabled": false,
"verified": false,
"statuses_count": 530,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/1162101134732996629/-Zy15QFJ_normal.png",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1162101134732996629/-Zy15QFJ_normal.png",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/827585192328044546/1565901503",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": true,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 6922,
"favorite_count": 23551,
"favorited": false,
"retweeted": false,
"possibly_sensitive": true,
"lang": "in"
},
"retweet_count": 88141,
"favorite_count": 289350,
"favorited": true,
"retweeted": true,
"possibly_sensitive": false,
"lang": "en"
},
"is_quote_status": true,
"quoted_status_id": 1161037928665104400,
"quoted_status_id_str": "1161037928665104384",
"retweet_count": 88141,
"favorite_count": 0,
"favorited": true,
"retweeted": true,
"lang": "en"
},
{
"created_at": "Sun Aug 18 21:19:15 +0000 2019",
"id": 1163198697792053200,
"id_str": "1163198697792053250",
"text": "This is not the time of night I want to pretend to be manly 😱#bloodybigspider https://t.co/pSRQ2bNJLR",
"truncated": false,
"entities": {
"hashtags": [
{
"text": "bloodybigspider",
"indices": [
61,
77
]
}
],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"id": 1163198696416260000,
"id_str": "1163198696416260097",
"indices": [
78,
101
],
"media_url": "http://pbs.twimg.com/media/ECSDDS8WsAEuQwE.jpg",
"media_url_https": "https://pbs.twimg.com/media/ECSDDS8WsAEuQwE.jpg",
"url": "https://t.co/pSRQ2bNJLR",
"display_url": "pic.twitter.com/pSRQ2bNJLR",
"expanded_url": "https://twitter.com/lildude/status/1163198697792053250/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"large": {
"w": 1024,
"h": 1024,
"resize": "fit"
},
"small": {
"w": 680,
"h": 680,
"resize": "fit"
},
"medium": {
"w": 1024,
"h": 1024,
"resize": "fit"
}
}
}
]
},
"extended_entities": {
"media": [
{
"id": 1163198696416260000,
"id_str": "1163198696416260097",
"indices": [
78,
101
],
"media_url": "http://pbs.twimg.com/media/ECSDDS8WsAEuQwE.jpg",
"media_url_https": "https://pbs.twimg.com/media/ECSDDS8WsAEuQwE.jpg",
"url": "https://t.co/pSRQ2bNJLR",
"display_url": "pic.twitter.com/pSRQ2bNJLR",
"expanded_url": "https://twitter.com/lildude/status/1163198697792053250/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"large": {
"w": 1024,
"h": 1024,
"resize": "fit"
},
"small": {
"w": 680,
"h": 680,
"resize": "fit"
},
"medium": {
"w": 1024,
"h": 1024,
"resize": "fit"
}
}
}
]
},
"source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 525,
"friends_count": 285,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1007,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5584,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Sun Aug 18 16:54:27 +0000 2019",
"id": 1163132057339478000,
"id_str": "1163132057339478016",
"text": "Caught in the Insta-act @thefishermanscottage 😂🤣 https://t.co/hEjQtBQlN2",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"id": 1163132056177643500,
"id_str": "1163132056177643520",
"indices": [
49,
72
],
"media_url": "http://pbs.twimg.com/media/ECRGcUtWkAAwaUa.jpg",
"media_url_https": "https://pbs.twimg.com/media/ECRGcUtWkAAwaUa.jpg",
"url": "https://t.co/hEjQtBQlN2",
"display_url": "pic.twitter.com/hEjQtBQlN2",
"expanded_url": "https://twitter.com/lildude/status/1163132057339478016/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 680,
"h": 680,
"resize": "fit"
},
"medium": {
"w": 1024,
"h": 1024,
"resize": "fit"
},
"large": {
"w": 1024,
"h": 1024,
"resize": "fit"
}
}
}
]
},
"extended_entities": {
"media": [
{
"id": 1163132056177643500,
"id_str": "1163132056177643520",
"indices": [
49,
72
],
"media_url": "http://pbs.twimg.com/media/ECRGcUtWkAAwaUa.jpg",
"media_url_https": "https://pbs.twimg.com/media/ECRGcUtWkAAwaUa.jpg",
"url": "https://t.co/hEjQtBQlN2",
"display_url": "pic.twitter.com/hEjQtBQlN2",
"expanded_url": "https://twitter.com/lildude/status/1163132057339478016/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 680,
"h": 680,
"resize": "fit"
},
"medium": {
"w": 1024,
"h": 1024,
"resize": "fit"
},
"large": {
"w": 1024,
"h": 1024,
"resize": "fit"
}
}
}
]
},
"source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 525,
"friends_count": 285,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1007,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5584,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 1,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Sat Aug 17 15:10:28 +0000 2019",
"id": 1162743503383871500,
"id_str": "1162743503383871488",
"text": "Finally visited the @westberksbrew brewery and tap room. Great place, beer and food. https://t.co/whxOLZmxR0",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "westberksbrew",
"name": "WestBerkshireBrewery",
"id": 408385941,
"id_str": "408385941",
"indices": [
20,
34
]
}
],
"urls": [],
"media": [
{
"id": 1162743502272417800,
"id_str": "1162743502272417792",
"indices": [
85,
108
],
"media_url": "http://pbs.twimg.com/media/ECLlDgnXUAATTDF.jpg",
"media_url_https": "https://pbs.twimg.com/media/ECLlDgnXUAATTDF.jpg",
"url": "https://t.co/whxOLZmxR0",
"display_url": "pic.twitter.com/whxOLZmxR0",
"expanded_url": "https://twitter.com/lildude/status/1162743503383871488/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 680,
"h": 680,
"resize": "fit"
},
"large": {
"w": 1024,
"h": 1024,
"resize": "fit"
},
"medium": {
"w": 1024,
"h": 1024,
"resize": "fit"
}
}
}
]
},
"extended_entities": {
"media": [
{
"id": 1162743502272417800,
"id_str": "1162743502272417792",
"indices": [
85,
108
],
"media_url": "http://pbs.twimg.com/media/ECLlDgnXUAATTDF.jpg",
"media_url_https": "https://pbs.twimg.com/media/ECLlDgnXUAATTDF.jpg",
"url": "https://t.co/whxOLZmxR0",
"display_url": "pic.twitter.com/whxOLZmxR0",
"expanded_url": "https://twitter.com/lildude/status/1162743503383871488/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 680,
"h": 680,
"resize": "fit"
},
"large": {
"w": 1024,
"h": 1024,
"resize": "fit"
},
"medium": {
"w": 1024,
"h": 1024,
"resize": "fit"
}
}
}
]
},
"source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 525,
"friends_count": 285,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1007,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5582,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Thu Aug 15 17:11:01 +0000 2019",
"id": 1162049063426121700,
"id_str": "1162049063426121728",
"text": "It only took 3 years, 4 months and 10 days from reservation to a much sexier drive. And it was worth every second o… https://t.co/A58itpZU7V",
"truncated": true,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [
{
"url": "https://t.co/A58itpZU7V",
"expanded_url": "https://twitter.com/i/web/status/1162049063426121728",
"display_url": "twitter.com/i/web/status/1…",
"indices": [
117,
140
]
}
]
},
"source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 525,
"friends_count": 285,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1007,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5581,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 5,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Sat Aug 10 17:40:57 +0000 2019",
"id": 1160244659412770800,
"id_str": "1160244659412770816",
"text": "The oompah band in the Harbour bar @lcbfestival is definitely the best entertainment, pity the Brit coordination su… https://t.co/5j2UMKFrdJ",
"truncated": true,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "LCBFestival",
"name": "LDN Craft Beer Fest",
"id": 1128202848,
"id_str": "1128202848",
"indices": [
35,
47
]
}
],
"urls": [
{
"url": "https://t.co/5j2UMKFrdJ",
"expanded_url": "https://twitter.com/i/web/status/1160244659412770816",
"display_url": "twitter.com/i/web/status/1…",
"indices": [
117,
140
]
}
]
},
"source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 525,
"friends_count": 287,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1007,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5580,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 2,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Sun Aug 04 17:32:42 +0000 2019",
"id": 1158068255631839200,
"id_str": "1158068255631839232",
"text": "Oh shit. I've just realised Jacob Rees-Mogg probably drew inspiration for his Esq language requirement from me 🤭 I… https://t.co/uiZW0cfPeN",
"truncated": true,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [
{
"url": "https://t.co/uiZW0cfPeN",
"expanded_url": "https://twitter.com/i/web/status/1158068255631839232",
"display_url": "twitter.com/i/web/status/1…",
"indices": [
116,
139
]
}
]
},
"source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 525,
"friends_count": 287,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1007,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5580,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 1,
"favorited": false,
"retweeted": false,
"lang": "en"
},
{
"created_at": "Sun Aug 04 16:41:05 +0000 2019",
"id": 1158055266165940200,
"id_str": "1158055266165940224",
"text": "@RoundReading I'd DM you but I can't. Thanks for the quick turnaround on the results however they reveal a little t… https://t.co/31e2M3487y",
"truncated": true,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "RoundReading",
"name": "Round Reading Ultra",
"id": 853328865770516500,
"id_str": "853328865770516480",
"indices": [
0,
13
]
}
],
"urls": [
{
"url": "https://t.co/31e2M3487y",
"expanded_url": "https://twitter.com/i/web/status/1158055266165940224",
"display_url": "twitter.com/i/web/status/1…",
"indices": [
117,
140
]
}
]
},
"source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": 853328865770516500,
"in_reply_to_user_id_str": "853328865770516480",
"in_reply_to_screen_name": "RoundReading",
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 525,
"friends_count": 287,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1007,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5580,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"lang": "en"
},
{
"created_at": "Sat Aug 03 19:37:30 +0000 2019",
"id": 1157737273485615000,
"id_str": "1157737273485615105",
"text": "Celebratory dark 'n stormy in the best glasses from @sirencraftbrew. Thanks @roundreading #rrum #ultramarathon #rum… https://t.co/zvl1Tlg4Qz",
"truncated": true,
"entities": {
"hashtags": [
{
"text": "rrum",
"indices": [
90,
95
]
},
{
"text": "ultramarathon",
"indices": [
96,
110
]
},
{
"text": "rum",
"indices": [
111,
115
]
}
],
"symbols": [],
"user_mentions": [
{
"screen_name": "SirenCraftBrew",
"name": "Siren Craft Brew",
"id": 945733406,
"id_str": "945733406",
"indices": [
52,
67
]
},
{
"screen_name": "RoundReading",
"name": "Round Reading Ultra",
"id": 853328865770516500,
"id_str": "853328865770516480",
"indices": [
76,
89
]
}
],
"urls": [
{
"url": "https://t.co/zvl1Tlg4Qz",
"expanded_url": "https://twitter.com/i/web/status/1157737273485615105",
"display_url": "twitter.com/i/web/status/1…",
"indices": [
117,
140
]
}
]
},
"source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 526,
"friends_count": 287,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1006,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5578,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 2,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Sat Aug 03 16:01:54 +0000 2019",
"id": 1157683017990791200,
"id_str": "1157683017990791168",
"text": "Winner!! Winner!! Chicken Dinner!! My first race victory came today at the @RoundReading Ultra Marathon (RRUM50). I… https://t.co/3JlhmSzfj5",
"truncated": true,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "RoundReading",
"name": "Round Reading Ultra",
"id": 853328865770516500,
"id_str": "853328865770516480",
"indices": [
75,
88
]
}
],
"urls": [
{
"url": "https://t.co/3JlhmSzfj5",
"expanded_url": "https://twitter.com/i/web/status/1157683017990791168",
"display_url": "twitter.com/i/web/status/1…",
"indices": [
117,
140
]
}
]
},
"source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 526,
"friends_count": 287,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1006,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5578,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 12,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Sat Aug 03 14:56:42 +0000 2019",
"id": 1157666610385215500,
"id_str": "1157666610385215488",
"text": "Getting our swing on Market Place Reading https://t.co/V9BmhfixRa",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"id": 1157666482463154200,
"id_str": "1157666482463154181",
"indices": [
42,
65
],
"media_url": "http://pbs.twimg.com/ext_tw_video_thumb/1157666482463154181/pu/img/joxaDN53pC-cTAnm.jpg",
"media_url_https": "https://pbs.twimg.com/ext_tw_video_thumb/1157666482463154181/pu/img/joxaDN53pC-cTAnm.jpg",
"url": "https://t.co/V9BmhfixRa",
"display_url": "pic.twitter.com/V9BmhfixRa",
"expanded_url": "https://twitter.com/lildude/status/1157666610385215488/video/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 680,
"h": 680,
"resize": "fit"
},
"medium": {
"w": 720,
"h": 720,
"resize": "fit"
},
"large": {
"w": 720,
"h": 720,
"resize": "fit"
}
}
}
]
},
"extended_entities": {
"media": [
{
"id": 1157666482463154200,
"id_str": "1157666482463154181",
"indices": [
42,
65
],
"media_url": "http://pbs.twimg.com/ext_tw_video_thumb/1157666482463154181/pu/img/joxaDN53pC-cTAnm.jpg",
"media_url_https": "https://pbs.twimg.com/ext_tw_video_thumb/1157666482463154181/pu/img/joxaDN53pC-cTAnm.jpg",
"url": "https://t.co/V9BmhfixRa",
"display_url": "pic.twitter.com/V9BmhfixRa",
"expanded_url": "https://twitter.com/lildude/status/1157666610385215488/video/1",
"type": "video",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 680,
"h": 680,
"resize": "fit"
},
"medium": {
"w": 720,
"h": 720,
"resize": "fit"
},
"large": {
"w": 720,
"h": 720,
"resize": "fit"
}
},
"video_info": {
"aspect_ratio": [
1,
1
],
"duration_millis": 3550,
"variants": [
{
"bitrate": 832000,
"content_type": "video/mp4",
"url": "https://video.twimg.com/ext_tw_video/1157666482463154181/pu/vid/480x480/3LyreS1NhQWrmxV-.mp4?tag=10"
},
{
"bitrate": 432000,
"content_type": "video/mp4",
"url": "https://video.twimg.com/ext_tw_video/1157666482463154181/pu/vid/320x320/zRK7z2C72Jy7gBk2.mp4?tag=10"
},
{
"content_type": "application/x-mpegURL",
"url": "https://video.twimg.com/ext_tw_video/1157666482463154181/pu/pl/yumMZXKgvrx1PLJW.m3u8?tag=10"
},
{
"bitrate": 1280000,
"content_type": "video/mp4",
"url": "https://video.twimg.com/ext_tw_video/1157666482463154181/pu/vid/720x720/2JI3V2V0qNcR5dYy.mp4?tag=10"
}
]
},
"additional_media_info": {
"monetizable": false
}
}
]
},
"source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 526,
"friends_count": 287,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1006,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5578,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 1,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Sat Aug 03 05:09:42 +0000 2019",
"id": 1157518883168948200,
"id_str": "1157518883168948224",
"text": "@jnewland 🤫 I merged into master without deploying first on a^h this Friday 🤭",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"screen_name": "jnewland",
"name": "Jesse Newland",
"id": 13518,
"id_str": "13518",
"indices": [
0,
9
]
}
],
"urls": []
},
"source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>",
"in_reply_to_status_id": 1157399998109290500,
"in_reply_to_status_id_str": "1157399998109290496",
"in_reply_to_user_id": 13518,
"in_reply_to_user_id_str": "13518",
"in_reply_to_screen_name": "jnewland",
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 526,
"friends_count": 287,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1006,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5578,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 1,
"favorited": false,
"retweeted": false,
"lang": "en"
},
{
"created_at": "Thu Aug 01 18:11:07 +0000 2019",
"id": 1156990757556932600,
"id_str": "1156990757556932608",
"text": "I guess that means my 🚗 _is_ on the #TriumphAce 🥳🎉🎊 #ImSoExcited https://t.co/IZqbvMzT0C",
"truncated": false,
"entities": {
"hashtags": [
{
"text": "TriumphAce",
"indices": [
36,
47
]
},
{
"text": "ImSoExcited",
"indices": [
53,
65
]
}
],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"id": 1156990748371423200,
"id_str": "1156990748371423233",
"indices": [
66,
89
],
"media_url": "http://pbs.twimg.com/media/EA509KUXkAEgtQK.jpg",
"media_url_https": "https://pbs.twimg.com/media/EA509KUXkAEgtQK.jpg",
"url": "https://t.co/IZqbvMzT0C",
"display_url": "pic.twitter.com/IZqbvMzT0C",
"expanded_url": "https://twitter.com/lildude/status/1156990757556932608/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"medium": {
"w": 894,
"h": 787,
"resize": "fit"
},
"large": {
"w": 894,
"h": 787,
"resize": "fit"
},
"small": {
"w": 680,
"h": 599,
"resize": "fit"
}
}
}
]
},
"extended_entities": {
"media": [
{
"id": 1156990748371423200,
"id_str": "1156990748371423233",
"indices": [
66,
89
],
"media_url": "http://pbs.twimg.com/media/EA509KUXkAEgtQK.jpg",
"media_url_https": "https://pbs.twimg.com/media/EA509KUXkAEgtQK.jpg",
"url": "https://t.co/IZqbvMzT0C",
"display_url": "pic.twitter.com/IZqbvMzT0C",
"expanded_url": "https://twitter.com/lildude/status/1156990757556932608/photo/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"medium": {
"w": 894,
"h": 787,
"resize": "fit"
},
"large": {
"w": 894,
"h": 787,
"resize": "fit"
},
"small": {
"w": 680,
"h": 599,
"resize": "fit"
}
}
}
]
},
"source": "<a href=\"http://tapbots.com/tweetbot\" rel=\"nofollow\">Tweetbot for iΟS</a>",
"in_reply_to_status_id": 1150387108609167400,
"in_reply_to_status_id_str": "1150387108609167360",
"in_reply_to_user_id": 8812362,
"in_reply_to_user_id_str": "8812362",
"in_reply_to_screen_name": "lildude",
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 527,
"friends_count": 287,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1005,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5574,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
},
{
"created_at": "Thu Aug 01 10:13:05 +0000 2019",
"id": 1156870456928067600,
"id_str": "1156870456928067584",
"text": "Tokyo Marathon 2020 ballot entry in. 🤞 I get drawn. #run #marathon #TokyoMarathon #AbbottWMM",
"truncated": false,
"entities": {
"hashtags": [
{
"text": "run",
"indices": [
52,
56
]
},
{
"text": "marathon",
"indices": [
57,
66
]
},
{
"text": "TokyoMarathon",
"indices": [
67,
81
]
},
{
"text": "AbbottWMM",
"indices": [
83,
93
]
}
],
"symbols": [],
"user_mentions": [],
"urls": []
},
"source": "<a href=\"https://about.twitter.com/products/tweetdeck\" rel=\"nofollow\">TweetDeck</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 8812362,
"id_str": "8812362",
"name": "Lildude Esquire 🤘at 🏃♂️",
"screen_name": "lildude",
"location": "Everywhere. Wha ha ha ha haaa!",
"description": "GitHub developing, beer drinking, running fundi and stay-at-home astronaut. Run stuffs at https://t.co/OlEtj7TstY",
"url": "https://t.co/3MoMsEOqye",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/3MoMsEOqye",
"expanded_url": "https://lildude.co.uk",
"display_url": "lildude.co.uk",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/OlEtj7TstY",
"expanded_url": "http://gonefora.run",
"display_url": "gonefora.run",
"indices": [
90,
113
]
}
]
}
},
"protected": false,
"followers_count": 527,
"friends_count": 287,
"listed_count": 17,
"created_at": "Tue Sep 11 15:19:08 +0000 2007",
"favourites_count": 1005,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 5574,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "000000",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/964993178230288384/vi8iEvhL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/8812362/1558126627",
"profile_link_color": "1B95E0",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 3,
"favorited": false,
"retweeted": false,
"lang": "en"
}
]
|
/*
Next-Gen Events
Copyright (c) 2015 - 2021 Cédric Ronvel
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
"use strict" ;
function Proxy() {
this.localServices = {} ;
this.remoteServices = {} ;
this.nextAckId = 1 ;
}
module.exports = Proxy ;
var NextGenEvents = require( './NextGenEvents.js' ) ;
var MESSAGE_TYPE = 'NextGenEvents/message' ;
function noop() {}
// Backward compatibility
Proxy.create = ( ... args ) => new Proxy( ... args ) ;
// Add a local service accessible remotely
Proxy.prototype.addLocalService = function( id , emitter , options ) {
this.localServices[ id ] = LocalService.create( this , id , emitter , options ) ;
return this.localServices[ id ] ;
} ;
// Add a remote service accessible locally
Proxy.prototype.addRemoteService = function( id ) {
this.remoteServices[ id ] = RemoteService.create( this , id ) ;
return this.remoteServices[ id ] ;
} ;
// Destroy the proxy
Proxy.prototype.destroy = function() {
Object.keys( this.localServices ).forEach( ( id ) => {
this.localServices[ id ].destroy() ;
delete this.localServices[ id ] ;
} ) ;
Object.keys( this.remoteServices ).forEach( ( id ) => {
this.remoteServices[ id ].destroy() ;
delete this.remoteServices[ id ] ;
} ) ;
this.receive = this.send = noop ;
} ;
// Push an event message.
Proxy.prototype.push = function( message ) {
if (
message.__type !== MESSAGE_TYPE ||
! message.service || typeof message.service !== 'string' ||
! message.event || typeof message.event !== 'string' ||
! message.method
) {
return ;
}
switch ( message.method ) {
// Those methods target a remote service
case 'event' :
return this.remoteServices[ message.service ] && this.remoteServices[ message.service ].receiveEvent( message ) ;
case 'ackEmit' :
return this.remoteServices[ message.service ] && this.remoteServices[ message.service ].receiveAckEmit( message ) ;
// Those methods target a local service
case 'emit' :
return this.localServices[ message.service ] && this.localServices[ message.service ].receiveEmit( message ) ;
case 'listen' :
return this.localServices[ message.service ] && this.localServices[ message.service ].receiveListen( message ) ;
case 'ignore' :
return this.localServices[ message.service ] && this.localServices[ message.service ].receiveIgnore( message ) ;
case 'ackEvent' :
return this.localServices[ message.service ] && this.localServices[ message.service ].receiveAckEvent( message ) ;
default :
return ;
}
} ;
// This is the method to receive and decode data from the other side of the communication channel, most of time another proxy.
// In most case, this should be overwritten.
Proxy.prototype.receive = function( raw ) {
this.push( raw ) ;
} ;
// This is the method used to send data to the other side of the communication channel, most of time another proxy.
// This MUST be overwritten in any case.
Proxy.prototype.send = function() {
throw new Error( 'The send() method of the Proxy MUST be extended/overwritten' ) ;
} ;
/* Local Service */
function LocalService( proxy , id , emitter , options ) { return LocalService.create( proxy , id , emitter , options ) ; }
Proxy.LocalService = LocalService ;
LocalService.create = function( proxy , id , emitter , options ) {
var self = Object.create( LocalService.prototype , {
proxy: { value: proxy , enumerable: true } ,
id: { value: id , enumerable: true } ,
emitter: { value: emitter , writable: true , enumerable: true } ,
internalEvents: { value: Object.create( NextGenEvents.prototype ) , writable: true , enumerable: true } ,
events: { value: {} , enumerable: true } ,
canListen: { value: !! options.listen , writable: true , enumerable: true } ,
canEmit: { value: !! options.emit , writable: true , enumerable: true } ,
canAck: { value: !! options.ack , writable: true , enumerable: true } ,
canRpc: { value: !! options.rpc , writable: true , enumerable: true } ,
destroyed: { value: false , writable: true , enumerable: true }
} ) ;
return self ;
} ;
// Destroy a service
LocalService.prototype.destroy = function() {
Object.keys( this.events ).forEach( ( eventName ) => {
this.emitter.off( eventName , this.events[ eventName ] ) ;
delete this.events[ eventName ] ;
} ) ;
this.emitter = null ;
this.destroyed = true ;
} ;
// Remote want to emit on the local service
LocalService.prototype.receiveEmit = function( message ) {
if ( this.destroyed || ! this.canEmit || ( message.ack && ! this.canAck ) ) { return ; }
var event = {
emitter: this.emitter ,
name: message.event ,
args: message.args || []
} ;
if ( message.ack ) {
event.callback = ( interruption ) => {
this.proxy.send( {
__type: MESSAGE_TYPE ,
service: this.id ,
method: 'ackEmit' ,
ack: message.ack ,
event: message.event ,
interruption: interruption
} ) ;
} ;
}
NextGenEvents.emitEvent( event ) ;
} ;
// Remote want to listen to an event of the local service
LocalService.prototype.receiveListen = function( message ) {
if ( this.destroyed || ! this.canListen || ( message.ack && ! this.canAck ) ) { return ; }
if ( message.ack ) {
if ( this.events[ message.event ] ) {
if ( this.events[ message.event ].ack ) { return ; }
// There is already an event, but not featuring ack, remove that listener now
this.emitter.off( message.event , this.events[ message.event ] ) ;
}
this.events[ message.event ] = LocalService.forwardWithAck.bind( this ) ;
this.events[ message.event ].ack = true ;
this.emitter.on( message.event , this.events[ message.event ] , { eventObject: true , async: true } ) ;
}
else {
if ( this.events[ message.event ] ) {
if ( ! this.events[ message.event ].ack ) { return ; }
// Remote want to downgrade:
// there is already an event, but featuring ack so we remove that listener now
this.emitter.off( message.event , this.events[ message.event ] ) ;
}
this.events[ message.event ] = LocalService.forward.bind( this ) ;
this.events[ message.event ].ack = false ;
this.emitter.on( message.event , this.events[ message.event ] , { eventObject: true } ) ;
}
} ;
// Remote do not want to listen to that event of the local service anymore
LocalService.prototype.receiveIgnore = function( message ) {
if ( this.destroyed || ! this.canListen ) { return ; }
if ( ! this.events[ message.event ] ) { return ; }
this.emitter.off( message.event , this.events[ message.event ] ) ;
this.events[ message.event ] = null ;
} ;
//
LocalService.prototype.receiveAckEvent = function( message ) {
if (
this.destroyed || ! this.canListen || ! this.canAck || ! message.ack ||
! this.events[ message.event ] || ! this.events[ message.event ].ack
) {
return ;
}
this.internalEvents.emit( 'ack' , message ) ;
} ;
// Send an event from the local service to remote
LocalService.forward = function( event ) {
if ( this.destroyed ) { return ; }
this.proxy.send( {
__type: MESSAGE_TYPE ,
service: this.id ,
method: 'event' ,
event: event.name ,
args: event.args
} ) ;
} ;
LocalService.forward.ack = false ;
// Send an event from the local service to remote, with ACK
LocalService.forwardWithAck = function( event , callback ) {
if ( this.destroyed ) { return ; }
if ( ! event.callback ) {
// There is no emit callback, no need to ack this one
this.proxy.send( {
__type: MESSAGE_TYPE ,
service: this.id ,
method: 'event' ,
event: event.name ,
args: event.args
} ) ;
callback() ;
return ;
}
var triggered = false ;
var ackId = this.proxy.nextAckId ++ ;
var onAck = ( message ) => {
if ( triggered || message.ack !== ackId ) { return ; } // Not our ack...
//if ( message.event !== event ) { return ; } // Do we care?
triggered = true ;
this.internalEvents.off( 'ack' , onAck ) ;
callback() ;
} ;
this.internalEvents.on( 'ack' , onAck ) ;
this.proxy.send( {
__type: MESSAGE_TYPE ,
service: this.id ,
method: 'event' ,
event: event.name ,
ack: ackId ,
args: event.args
} ) ;
} ;
LocalService.forwardWithAck.ack = true ;
/* Remote Service */
function RemoteService( proxy , id ) { return RemoteService.create( proxy , id ) ; }
//RemoteService.prototype = Object.create( NextGenEvents.prototype ) ;
//RemoteService.prototype.constructor = RemoteService ;
Proxy.RemoteService = RemoteService ;
var EVENT_NO_ACK = 1 ;
var EVENT_ACK = 2 ;
RemoteService.create = function( proxy , id ) {
var self = Object.create( RemoteService.prototype , {
proxy: { value: proxy , enumerable: true } ,
id: { value: id , enumerable: true } ,
// This is the emitter where everything is routed to
emitter: { value: Object.create( NextGenEvents.prototype ) , writable: true , enumerable: true } ,
internalEvents: { value: Object.create( NextGenEvents.prototype ) , writable: true , enumerable: true } ,
events: { value: {} , enumerable: true } ,
destroyed: { value: false , writable: true , enumerable: true }
/* Useless for instance, unless some kind of service capabilities discovery mechanism exists
canListen: { value: !! options.listen , writable: true , enumerable: true } ,
canEmit: { value: !! options.emit , writable: true , enumerable: true } ,
canAck: { value: !! options.ack , writable: true , enumerable: true } ,
canRpc: { value: !! options.rpc , writable: true , enumerable: true } ,
*/
} ) ;
return self ;
} ;
// Destroy a service
RemoteService.prototype.destroy = function() {
this.emitter.removeAllListeners() ;
this.emitter = null ;
Object.keys( this.events ).forEach( ( eventName ) => { delete this.events[ eventName ] ; } ) ;
this.destroyed = true ;
} ;
// Local code want to emit to remote service
RemoteService.prototype.emit = function( eventName , ... args ) {
if ( this.destroyed ) { return ; }
var callback , ackId , triggered ;
if ( typeof eventName === 'number' ) { throw new TypeError( 'Cannot emit with a nice value on a remote service' ) ; }
if ( typeof args[ args.length - 1 ] !== 'function' ) {
this.proxy.send( {
__type: MESSAGE_TYPE ,
service: this.id ,
method: 'emit' ,
event: eventName ,
args: args
} ) ;
return ;
}
callback = args.pop() ;
ackId = this.proxy.nextAckId ++ ;
triggered = false ;
var onAck = ( message ) => {
if ( triggered || message.ack !== ackId ) { return ; } // Not our ack...
//if ( message.event !== event ) { return ; } // Do we care?
triggered = true ;
this.internalEvents.off( 'ack' , onAck ) ;
callback( message.interruption ) ;
} ;
this.internalEvents.on( 'ack' , onAck ) ;
this.proxy.send( {
__type: MESSAGE_TYPE ,
service: this.id ,
method: 'emit' ,
ack: ackId ,
event: eventName ,
args: args
} ) ;
} ;
// Local code want to listen to an event of remote service
RemoteService.prototype.addListener = function( eventName , fn , options ) {
if ( this.destroyed ) { return ; }
// Manage arguments the same way NextGenEvents#addListener() does
if ( typeof fn !== 'function' ) { options = fn ; fn = undefined ; }
if ( ! options || typeof options !== 'object' ) { options = {} ; }
options.fn = fn || options.fn ;
this.emitter.addListener( eventName , options ) ;
// No event was added...
if ( ! this.emitter.__ngev.listeners[ eventName ] || ! this.emitter.__ngev.listeners[ eventName ].length ) { return ; }
// If the event is successfully listened to and was not remotely listened...
if ( options.async && this.events[ eventName ] !== EVENT_ACK ) {
// We need to listen to or upgrade this event
this.events[ eventName ] = EVENT_ACK ;
this.proxy.send( {
__type: MESSAGE_TYPE ,
service: this.id ,
method: 'listen' ,
ack: true ,
event: eventName
} ) ;
}
else if ( ! options.async && ! this.events[ eventName ] ) {
// We need to listen to this event
this.events[ eventName ] = EVENT_NO_ACK ;
this.proxy.send( {
__type: MESSAGE_TYPE ,
service: this.id ,
method: 'listen' ,
event: eventName
} ) ;
}
} ;
RemoteService.prototype.on = RemoteService.prototype.addListener ;
// This is a shortcut to this.addListener()
RemoteService.prototype.once = NextGenEvents.prototype.once ;
// Local code want to ignore an event of remote service
RemoteService.prototype.removeListener = function( eventName , id ) {
if ( this.destroyed ) { return ; }
this.emitter.removeListener( eventName , id ) ;
// If no more listener are locally tied to with event and the event was remotely listened...
if (
( ! this.emitter.__ngev.listeners[ eventName ] || ! this.emitter.__ngev.listeners[ eventName ].length ) &&
this.events[ eventName ]
) {
this.events[ eventName ] = 0 ;
this.proxy.send( {
__type: MESSAGE_TYPE ,
service: this.id ,
method: 'ignore' ,
event: eventName
} ) ;
}
} ;
RemoteService.prototype.off = RemoteService.prototype.removeListener ;
// A remote service sent an event we are listening to, emit on the service representing the remote
RemoteService.prototype.receiveEvent = function( message ) {
if ( this.destroyed || ! this.events[ message.event ] ) { return ; }
var event = {
emitter: this.emitter ,
name: message.event ,
args: message.args || []
} ;
if ( message.ack ) {
event.callback = () => {
this.proxy.send( {
__type: MESSAGE_TYPE ,
service: this.id ,
method: 'ackEvent' ,
ack: message.ack ,
event: message.event
} ) ;
} ;
}
NextGenEvents.emitEvent( event ) ;
var eventName = event.name ;
// Here we should catch if the event is still listened to ('once' type listeners)
//if ( this.events[ eventName ] ) // not needed, already checked at the begining of the function
if ( ! this.emitter.__ngev.listeners[ eventName ] || ! this.emitter.__ngev.listeners[ eventName ].length ) {
this.events[ eventName ] = 0 ;
this.proxy.send( {
__type: MESSAGE_TYPE ,
service: this.id ,
method: 'ignore' ,
event: eventName
} ) ;
}
} ;
//
RemoteService.prototype.receiveAckEmit = function( message ) {
if ( this.destroyed || ! message.ack || this.events[ message.event ] !== EVENT_ACK ) {
return ;
}
this.internalEvents.emit( 'ack' , message ) ;
} ;
|
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
errorHandler = require('./errors.server.controller.js'),
mongoose = require('mongoose'),
passport = require('passport'),
User = mongoose.model('User');
/**
* List of Users
*/
exports.userList = function(req, res) {
User.find().sort('-created').select('created displayName').exec(function(err, user) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(user);
}
});
};
/**
* Show the current User
*/
exports.userRead = function(req, res) {
res.jsonp(req.user);
};
/**
* Update an User
*/
exports.userUpdate = function(req, res) {
var user = req.user ;
user = _.extend(user , req.body);
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(user);
}
});
};
/**
* User middleware
*/
exports.userByID = function(req, res, next, id) {
User.findById(id).select('username roles').exec(function(err, user) {
if (err) return next(err);
if (! user) return next(new Error('Failed to load User ' + id));
req.user = user ;
next();
});
};
|
'use strict';
// Setting up route
angular.module('users').config(['$stateProvider',
function($stateProvider) {
// Users state routing
$stateProvider.
state('update-prof-pic', {
url: '/update-prof-pic',
templateUrl: 'modules/users/views/update-prof-pic.client.view.html'
}).
state('upload-prof-pic', {
url: '/upload-prof-pic',
templateUrl: 'modules/users/views/upload-prof-pic.client.view.html'
}).
state('create-user', {
url: '/create-user',
templateUrl: 'modules/users/views/create-user.client.view.html'
}).
state('profile', {
url: '/settings/profile',
templateUrl: 'modules/users/views/settings/edit-profile.client.view.html'
}).
state('password', {
url: '/settings/password',
templateUrl: 'modules/users/views/settings/change-password.client.view.html'
}).
state('accounts', {
url: '/settings/accounts',
templateUrl: 'modules/users/views/settings/social-accounts.client.view.html'
}).
state('signup', {
url: '/signup',
templateUrl: 'modules/users/views/authentication/signup.client.view.html'
}).
state('signin', {
url: '/signin',
templateUrl: 'modules/users/views/authentication/signin.client.view.html'
}).
state('forgot', {
url: '/password/forgot',
templateUrl: 'modules/users/views/password/forgot-password.client.view.html'
}).
state('reset-invalid', {
url: '/password/reset/invalid',
templateUrl: 'modules/users/views/password/reset-password-invalid.client.view.html'
}).
state('reset-success', {
url: '/password/reset/success',
templateUrl: 'modules/users/views/password/reset-password-success.client.view.html'
}).
state('reset', {
url: '/password/reset/:token',
templateUrl: 'modules/users/views/password/reset-password.client.view.html'
}).
state('listUsers', {
url: '/users',
templateUrl: 'modules/users/views/list-users.client.view.html'
}).
state('viewUser', {
url: '/users/:userId',
templateUrl: 'modules/users/views/view-user.client.view.html'
}).
state('editUser', {
url: '/users/:userId/edit',
templateUrl: 'modules/users/views/edit-user.client.view.html'
});
}
]);
|
require('./proof')(1, prove)
function prove (async, okay) {
var strata = createStrata({ directory: tmp, leafSize: 3, branchSize: 3 })
async(function () {
serialize(__dirname + '/fixtures/propagate.before.json', tmp, async())
}, function () {
strata.open(async())
}, function () {
strata.mutator('zz', async())
}, function (cursor) {
cursor.insert('zz', 'zz', ~cursor.index)
cursor.unlock(async())
}, function () {
strata.balance(async())
}, function () {
vivify(tmp, async())
load(__dirname + '/fixtures/propagate.after.json', async())
}, function (actual, expected) {
okay(actual, expected, 'split')
strata.close(async())
})
}
|
/*
* jQuery Iframe Transport Plugin 1.5
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint unparam: true, nomen: true */
/*global define, window, document */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['jquery'], factory);
} else {
// Browser globals:
factory(window.jQuery);
}
}(function ($) {
'use strict';
// Helper variable to create unique names for the transport iframes:
var counter = 0;
// The iframe transport accepts three additional options:
// options.fileInput: a jQuery collection of file input fields
// options.paramName: the parameter name for the file form data,
// overrides the name property of the file input field(s),
// can be a string or an array of strings.
// options.formData: an array of objects with name and value properties,
// equivalent to the return data of .serializeArray(), e.g.:
// [{name: 'a', value: 1}, {name: 'b', value: 2}]
$.ajaxTransport('iframe', function (options) {
if (options.async && (options.type === 'POST' || options.type === 'GET')) {
var form,
iframe;
return {
send : function (_, completeCallback) {
form = $('<form style="display:none;"></form>');
form.attr('accept-charset', options.formAcceptCharset);
// javascript:false as initial iframe src
// prevents warning popups on HTTPS in IE6.
// IE versions below IE8 cannot set the name property of
// elements that have already been added to the DOM,
// so we set the name along with the iframe HTML markup:
iframe = $(
'<iframe src="javascript:false;" name="iframe-transport-' +
(counter += 1) + '"></iframe>'
).bind('load', function () {
var fileInputClones,
paramNames = $.isArray(options.paramName) ?
options.paramName : [options.paramName];
iframe
.unbind('load')
.bind('load', function () {
var response;
// Wrap in a try/catch block to catch exceptions thrown
// when trying to access cross-domain iframe contents:
try {
response = iframe.contents();
// Google Chrome and Firefox do not throw an
// exception when calling iframe.contents() on
// cross-domain requests, so we unify the response:
if (!response.length || !response[0].firstChild) {
throw new Error();
}
} catch (e) {
response = undefined;
}
// The complete callback returns the
// iframe content document as response object:
completeCallback(
200,
'success',
{'iframe': response}
);
// Fix for IE endless progress bar activity bug
// (happens on form submits to iframe targets):
$('<iframe src="javascript:false;"></iframe>')
.appendTo(form);
form.remove();
});
form
.prop('target', iframe.prop('name'))
.prop('action', options.url)
.prop('method', options.type);
if (options.formData) {
$.each(options.formData, function (index, field) {
$('<input type="hidden"/>')
.prop('name', field.name)
.val(field.value)
.appendTo(form);
});
}
if (options.fileInput && options.fileInput.length &&
options.type === 'POST') {
fileInputClones = options.fileInput.clone();
// Insert a clone for each file input field:
options.fileInput.after(function (index) {
return fileInputClones[index];
});
if (options.paramName) {
options.fileInput.each(function (index) {
$(this).prop(
'name',
paramNames[index] || options.paramName
);
});
}
// Appending the file input fields to the hidden form
// removes them from their original location:
form
.append(options.fileInput)
.prop('enctype', 'multipart/form-data')
// enctype must be set as encoding for IE:
.prop('encoding', 'multipart/form-data');
}
form.submit();
// Insert the file input fields at their original location
// by replacing the clones with the originals:
if (fileInputClones && fileInputClones.length) {
options.fileInput.each(function (index, input) {
var clone = $(fileInputClones[index]);
$(input).prop('name', clone.prop('name'));
clone.replaceWith(input);
});
}
});
form.append(iframe).appendTo(document.body);
},
abort: function () {
if (iframe) {
// javascript:false as iframe src aborts the request
// and prevents warning popups on HTTPS in IE6.
// concat is used to avoid the "Script URL" JSLint error:
iframe
.unbind('load')
.prop('src', 'javascript'.concat(':false;'));
}
if (form) {
form.remove();
}
}
};
}
});
// The iframe transport returns the iframe content document as response.
// The following adds converters from iframe to text, json, html, and script:
$.ajaxSetup({
converters: {
'iframe text' : function (iframe) {
return $(iframe[0].body).text();
},
'iframe json' : function (iframe) {
return $.parseJSON($(iframe[0].body).text());
},
'iframe html' : function (iframe) {
return $(iframe[0].body).html();
},
'iframe script': function (iframe) {
return $.globalEval($(iframe[0].body).text());
}
}
});
}));
|
import 'babel-polyfill';
import {
getScriptNameList,
getScript,
createScript,
renameScript,
updateScript,
deleteScript
} from '../aiRepoService.js';
beforeEach(() => {
global.localStorage.getItem.mockReset();
global.localStorage.setItem.mockReset();
global.localStorage.clear.mockReset();
global.localStorage.removeItem.mockReset();
});
test('get script', async () => {
global.localStorage.getItem.mockReturnValue(JSON.stringify({
'alplha873': {
name: 'alplha873',
code: '// code 97734'
}
}))
let result = await getScript('local_alplha873');
expect(result).toHaveProperty('id', 'local_alplha873')
expect(result).toHaveProperty('scriptName', 'alplha873')
expect(result).toHaveProperty('code', '// code 97734')
});
test('thorw error when getting not existing script', () => {
return expect(getScript('local_z01210a')).rejects.toThrow(/not exist/);
});
test('create script with sugested name', async () => {
let testValues = ['alpha897', 'abc', '123456789012345', 'ABC_def-123']
let result;
for(let testValue of testValues) {
result = await createScript(testValue);
expect(result).toHaveProperty('name', testValue);
expect(result).toHaveProperty('code');
}
});
test('create script with unique sugested name', async () => {
global.localStorage.getItem.mockReturnValue(JSON.stringify({
'bravo98707321': {
name: 'bravo98707321',
code: '// code 97734'
}
}))
let result = await createScript('bravo98707321');
expect(result).not.toHaveProperty('name', 'bravo98707321');
expect(result).toHaveProperty('code');
});
test('create script with unique name', async () => {
let result1 = await createScript();
let result2 = await createScript();
expect(result1).toHaveProperty('name');
expect(result2).toHaveProperty('name');
expect(result1.name).not.toBe(result2.name)
expect(result1).toHaveProperty('code');
expect(result2).toHaveProperty('code');
});
test('limit amount of created scripts', async () => {
const script = {
name: 'gamma882345',
code: '// code 5342'
}
const sixScripts = {};
const sevenScripts = {};
for(let i=0; i < 6; i ++) {
sixScripts[script.name + "_" + i] = script;
sevenScripts[script.name + "_" + i] = script;
}
sevenScripts[script.name + "_6"] = script;
global.localStorage.getItem.mockReturnValue(JSON.stringify(sixScripts))
let result = await createScript();
expect(result).toHaveProperty('name');
expect(result).toHaveProperty('code');
global.localStorage.getItem.mockReturnValue(JSON.stringify(sevenScripts))
return expect(createScript()).rejects.toThrow(/limit/);
});
test('rename script', async () => {
global.localStorage.getItem.mockReturnValue(JSON.stringify({
'zetta8847': {
name: 'zetta8847',
code: '// code 0983'
},
'black590983': {
name: 'black590983',
code: '// code 2953'
}
}));
let result = await renameScript("omega7743", 'local_zetta8847')
expect(result).toHaveProperty('id', 'local_omega7743');
expect(result).toHaveProperty('scriptName', 'omega7743');
expect(global.localStorage.setItem.mock.calls[0][0]).toBe('scriptMap')
let outcome = JSON.parse(global.localStorage.setItem.mock.calls[0][1])
expect(outcome).toHaveProperty('omega7743');
expect(outcome.omega7743).toHaveProperty('name', 'omega7743');
expect(outcome.omega7743).toHaveProperty('code', '// code 0983');
});
test('reject too short names', async () => {
global.localStorage.getItem.mockReturnValue(JSON.stringify({
'zetta26574': {
name: 'zetta26574',
code: '// code 8934'
},
'reserved7842': {
name: 'reserved7842',
code: '// code 19295'
}
}));
let testValues = ['', 'xx', '1234567890123456', {}, 'alpha~', 'do.t', 'specia/', '@nother', 'reserved7842', 'no space']
let testResults = [];
for(let testValue of testValues) {
testResults.push(expect(renameScript(testValue, 'local_zetta26574')).rejects.toThrow(/wrong script name/i))
}
return Promise.all(testResults)
});
test('throw error when renaming not existing script', async () => {
return expect(renameScript('new_name', 'local_alpha1329')).rejects.toThrow(/not exist/);
});
test('list scripts is empty by default', async () => {
global.localStorage.getItem.mockReturnValue(JSON.stringify({
'duck873': {
name: 'duck873',
code: '// code 921'
},
'cat762': {
name: 'cat762',
code: '// code 013'
}
}));
let result = await getScriptNameList();
expect(result).toHaveLength(2);
expect(result[0]).toHaveProperty('id', 'local_duck873');
expect(result[0]).toHaveProperty('scriptName', 'duck873');
expect(result[0]).not.toHaveProperty('code');
expect(result[1]).toHaveProperty('id', 'local_cat762');
expect(result[1]).toHaveProperty('scriptName', 'cat762');
expect(result[1]).not.toHaveProperty('code');
});
test('update script', async () => {
global.localStorage.getItem.mockReturnValue(JSON.stringify({
'orange8874': {
name: 'orange8874',
code: '// code 19823'
}
}));
let result = await updateScript('local_orange8874', '// new code 188273');
expect(result).toHaveProperty('id', 'local_orange8874');
expect(result).toHaveProperty('name', 'orange8874');
expect(result).toHaveProperty('code', '// new code 188273');
expect(global.localStorage.setItem.mock.calls[0][0]).toBe('scriptMap')
let outcome = JSON.parse(global.localStorage.setItem.mock.calls[0][1])
expect(outcome).toHaveProperty('orange8874');
expect(outcome.orange8874).toHaveProperty('name', 'orange8874');
expect(outcome.orange8874).toHaveProperty('code', '// new code 188273');
});
test('throw error when updatinig not existing script', async () => {
return expect(updateScript('new_name', 'local_nothing89732')).rejects.toThrow(/not exist/);
});
test('delete script', async () => {
global.localStorage.getItem.mockReturnValue(JSON.stringify({
'blue717663': {
name: 'blue717663',
code: '// code 8302'
},
'pink6232': {
name: 'pink6232',
code: '// code 1453'
}
}));
await deleteScript('local_blue717663');
expect(global.localStorage.setItem.mock.calls[0][0]).toBe('scriptMap')
let outcome = JSON.parse(global.localStorage.setItem.mock.calls[0][1])
expect(Object.keys(outcome)).toHaveLength(1);
expect(outcome.pink6232).toHaveProperty('name', 'pink6232')
});
test('throw error when deletinig not existing script', async () => {
return expect(updateScript('new_name', 'local_nothing2707332')).rejects.toThrow(/not exist/);
});
|
import axios from 'axios';
import { Message } from 'element-ui';
import store from '../store';
import { getToken } from 'utils/auth';
const base_api = "http://m.ctrip.com/restapi/soa2/11796"
// 创建axios实例
const service = axios.create({
baseURL: base_api || process.env.BASE_API, // api的base_url
timeout: 5000 // 请求超时时间
});
// request拦截器
service.interceptors.request.use(config => {
// Do something before request is sent
if (store.getters.token) {
config.headers['X-Token'] = getToken(); // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
}
return config;
}, error => {
// Do something with request error
console.log(error); // for debug
Promise.reject(error);
})
// respone拦截器
service.interceptors.response.use(
response => response,
/**
* 下面的注释为通过response自定义code来标示请求状态,当code返回如下情况为权限有问题,登出并返回到登录页
* 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
*/
// const res = response.data;
// if (res.code !== 20000) {
// Message({
// message: res.message,
// type: 'error',
// duration: 5 * 1000
// });
// // 50008:非法的token; 50012:其他客户端登录了; 50014:Token 过期了;
// if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', {
// confirmButtonText: '重新登录',
// cancelButtonText: '取消',
// type: 'warning'
// }).then(() => {
// store.dispatch('FedLogOut').then(() => {
// location.reload();// 为了重新实例化vue-router对象 避免bug
// });
// })
// }
// return Promise.reject('error');
// } else {
// return response.data;
// }
error => {
console.log('err' + error);// for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
});
return Promise.reject(error);
}
)
export default service;
|
import React from 'react';
import injectSheet from 'react-jss';
// import { compose, withHandlers, withState } from 'recompose';
const styles = {
AutoComplete: {
textAlign: 'center',
},
ComboBox: {},
ListBox: {
listStyle: 'none',
margin: '0',
padding: '0',
},
ListItem: {
border: '1px solid lightgray',
cursor: 'pointer',
padding: '.5em',
},
};
// const enhance = compose(
// withState('value', 'inputValue', ''),
// withHandlers({
// onChange: props => event => {
// props.updateValue(event.target.value);
// }
// })
// )
const AutoComplete = ({
classes,
handleChange,
handleKeyDown,
inputValue,
isOpen,
options,
}) =>
<div className={classes.AutoComplete}>
<div className={classes.ComboBox}>
<input
aria-autocomplete="list"
aria-label="input"
onChange={handleChange} //
onKeyDown={handleKeyDown} //
type="text"
value={inputValue} //
/>
</div>
{isOpen ?
<div className={classes.ListBox} role="listbox">
{options.map((option, idx) =>
<div className={classes.ListItem} key={idx}>
{option}
</div>
)}
</div> :
null}
</div>;
export default injectSheet(styles)(AutoComplete);
/*
<div
aria-label="Tag"
role="combobox"
aria-expanded="true"
aria-owns="owned_listbox"
aria-haspopup="listbox"
>
<input
type="text"
aria-autocomplete="list"
aria-controls="owned_listbox"
aria-activedescendant="selected_option"
>
</div>
<ul role="listbox" id="owned_listbox">
<li role="option">Zebra</li>
<li role="option" id="selected_option">Zoom</li>
</ul>
const addCounting = compose(
withState('counter', 'setCounter', 0),
withHandlers({
increment: ({ setCounter }) => () => setCounter(n => n + 1),
decrement: ({ setCounter }) => () => setCounter(n => n - 1),
reset: ({ setCounter }) => () => setCounter(0)
})
)
const withCondition = conditionalRenderingFn => Component => props =>
conditionalRenderingFn(props) ? null : <Component {...props} />;
*/
|
'use strict';
const debug = require('debug')('Backend-Portfolio:message-router.js');
const Router = require('express').Router;
const jsonParser = require('body-parser').json();
const createError = require('http-errors');
const bearerAuth = require('../lib/bearer-auth-middleware.js');
const Message = require('../model/Message.js');
const messageRouter = module.exports = Router();
messageRouter.post('/api/message', bearerAuth, jsonParser, (req, res, next) => {
debug('POST: /api/message');
if(!req.body || !req.body.title) return next(createError(400, 'bad request: missing minimum content requirments'));
if(!req.user || !req.user._id) return next(createError(401, 'unauthorized: json web token failure, your token either doesn\'t exist or is invalid'));
const message = new Message({
author_id: req.user._id,
title: req.body.title,
text: req.body.text || null
});
message.save()
.then((message) => res.json(message))
.catch((err) => next(err));
});
// NOTE: I'm thinking of combining all get routes into one big route that handles everything
// based on certain query parameters that can be handed in
messageRouter.get('/api/message/fetch', bearerAuth, jsonParser, (req, res, next) => {
debug('GET: /api/message/fetch');
if(!req.query || !req.query.type) return next(createError(400, 'bad request: no queries were provided for the route', req.query));
if(!req.user || !req.user._id) return next(createError(401, 'unauthorized: json web token failure, your token saved in cookies does not match your user id'));
// NOTE: what if I updated this again to work with only one query param and change things
// based on it's type?
console.log('type', req.query.type);
console.log('id', req.query.id);
if(req.query.type == 'all'){
Message.find({})
.then((message) => {
if(!message) return next(createError(404, 'not found: no items were found'));
return res.json(message);
})
.catch((err) => next(err));
}else if(req.query.type == 'me'){
Message.find({'author_id': req.user._id})
.then((message) => {
if(!message) return next(createError(404, 'not found: no items were found'));
return res.json(message);
})
.catch((err) => next(err));
// NOTE: adding aditional query option for finding another user's posts
}else if(req.query.type == 'user'){
Message.find({'author_id': req.query.id})
.then((message) => {
if(!message) return next(createError(404, 'not found: no items were found'));
return res.json(message);
})
.catch((err) => next(err));
}else if(req.query.type == 'singular'){
Message.findById({'_id': req.query.id})
.then((message) => {
if(!message) return next(createError(404, 'not found: no items were found'));
return res.json(message);
})
.catch((err) => next(err));
}else{
// NOTE: throw error?
return next(createError(400, `bad request: invalid query type: ${req.query.type}. Query type for this route must be of type: 'all', 'me', 'user' with a valid user id, or 'singular' with a valid item id`));
}
// NOTE: switch seems kinda dumb in this situation
// switch(req.query.type){
// case 'all':
// Message.find({})
// .then((messages) => {
// if(!messages) return next(createError(404, 'not found: no items were found'));
// return res.json(messages);
// })
// .catch((err) => next(err));
// break;
// case 'me':
// break;
// case 'singular':
// break;
// default:
// break;
// }
// NOTE: old method with different query options:
// if(req.query.all){
// Message.find({})
// .then((messages) => {
// if(!messages) return next(createError(404, 'not found: no items were found'));
// return res.json(messages);
// })
// .catch((err) => next(err));
// }else if(req.query.me){
// Message.find({'author_id': req.user._id})
// .then((messages) => {
// if(!messages) return next(createError(404, 'not found: no items were found'));
// return res.json(messages);
// })
// .catch((err) => next(err));
// }else if(req.query.message_id){
// Message.findById({'_id': req.query.message_id})
// .then((message) => {
// if(!message) return next(createError(404, 'not found: no items were found'));
// return res.json(message);
// })
// .catch((err) => next(err));
// }else{
// return next(createError(400, 'bad request: something went wrong with the query parameters', req.query));
// }
// query parameter:
// id: if an id is provided we just try to fetch that message and return it
// self: if this is provided we return all items with this user's id
// all: if this is provided we return all messages
});
messageRouter.put('/api/message/edit/:message_id', bearerAuth, jsonParser, (req, res, next) => {
debug('PUT: /api/message/edit/:message_id');
if(!req.params || !req.params.message_id) return next(createError(400, 'an _id must be provided, got:', req.params.id));
if(!req.body || (!req.body.photos && (!req.body.title && !req.body.text))) return next(createError(400, 'bad request: missing minimum content requirments'));
if(!req.user || !req.user._id) return next(createError(401, 'unauthorized: json web token failure, your token saved in cookies does not match your user id'));
Message.findById({'_id': req.params.message_id})
.then((message) => {
if(!message) return next(createError(404, 'not found: no message was found:', message));
if(req.user._id != message.author_id) return next(createError(401, 'unauthorized: json web token failure, your token saved in cookies does not match your user id'));
if(req.body.title) message.title = req.body.title;
if(req.body.text) message.text = req.body.text;
message.updated_at = Date.now();
message.save();
return message;
})
.then((message) => res.json(message))
.catch((err) => next(err));
});
messageRouter.delete('/api/message/remove/:message_id', bearerAuth, (req, res, next) => {
debug('DELETE: /api/message/remove/:message_id');
if(!req.params || !req.params.message_id) return next(createError(400, 'an _id must be provided, got:', req.params.id));
if(!req.user || !req.user._id) return next(createError(401, 'unauthorized: json web token failure, your token saved in cookies does not match your user id'));
Message.findById({'_id': req.params.message_id})
.then((message) => {
if(!message) return next(createError(404, 'not found: no message was found:', message));
if(req.user._id != message.author_id) return next(createError(401, 'unauthorized: json web token failure, your token saved in cookies does not match your user id'));
if(message.next.length > 0){
message.handleDelete()
.then(() => {
Message.deleteOne({'_id': req.params.message_id})
.then(() => res.status(204).send())
.catch((err) => next(createError(500, 'failed delete', err)));
})
.catch((err) => next(createError(500, 'failed delete', err)));
}else{
Message.deleteOne({'_id': req.params.message_id})
.then(() => res.status(204).send())
.catch((err) => next(createError(500, 'failed delete', err)));
}
});
});
|
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/App';
import HomePage from './components/home/HomePage';
import AboutPage from './components/about/AboutPage';
import CoursesPage from './components/course/CoursesPage';
import ManageCoursePage from './components/course/ManageCoursePage';
export default (
<Route path="/" component={App}>
<IndexRoute component={HomePage}/>
<Route path="about" component={AboutPage}/>
<Route path="courses" component={CoursesPage}/>
<Route path="course" component={ManageCoursePage}/>
<Route path="course/:id" component={ManageCoursePage}/>
</Route>
);
|
// ------------------------------------
// Constants
// ------------------------------------
// export const GAME_SHOW_NOTIFICATION = 'GAME_SHOW_NOTIFICATION'
// export const COUNTER_DOUBLE_ASYNC = 'COUNTER_DOUBLE_ASYNC'
// ------------------------------------
// Actions
// ------------------------------------
// export const showNotification = (notification) => {
// return {
// type : GAME_SHOW_NOTIFICATION,
// payload : notification
// }
// }
/* This is a thunk, meaning it is a function that immediately
returns a function for lazy evaluation. It is incredibly useful for
creating async actions, especially when combined with redux-thunk! */
// export const submitGuess = (guess, taken, gameid, taken, bank, authid) => {
// return (dispatch, getState, getFirebase) => {
// const firebase = getFirebase()
// let guessTaken = Object.keys(taken).filter(i => (taken[i] !== undefined && taken[i].word === guess))
// let bankWordKey = Object.keys(bank).filter(i => bank[i].word === guess)
// if (guessTaken.length === 0 && bankWordKey.length === 1) {
// // Guess is a word and it's not taken
// // TODO: add notification "+{point value}"
// let currentScore = currentPlayers[authid].score,
// playerColor = currentPlayers[authid].color,
// newScore = currentScore + bank[bankWordKey].value
// update(GAMES_PATH+'/'+gameid+'/taken', {[bankWordKey]:{word:guess,color:playerColor}})
// update('gamePlayers/'+gameid+'/'+auth.uid, {score:newScore})
// }else if(guessTaken.length === 1 && bankWordKey.length === 1){
// // TODO: add notification "Too Slow! That word is taken"
// }else if (bankWordKey.length === 0) {
// // TODO: add notification "Nice try, that's not a word"
// }
// return new Promise((resolve) => {
// setTimeout(() => {
// dispatch({
// type : COUNTER_DOUBLE_ASYNC,
// payload : getState().counter
// })
// resolve()
// }, 200)
// })
// }
// }
// export const actions = {
// showNotification
// }
// ------------------------------------
// Action Handlers
// ------------------------------------
// const ACTION_HANDLERS = {
// [GAME_SHOW_NOTIFICATION] : (state, action) => action.payload
// }
// ------------------------------------
// Reducer
// ------------------------------------
// const initialState = { text:'',type:'success' }
// export default function gameReducer (state = initialState, action) {
// const handler = ACTION_HANDLERS[action.type]
// return handler ? handler(state, action) : state
// }
|
({
baseUrl: "modules",
paths: {
'ceylon/language/1.1.0/ceylon.language-1.1.0':'../assets/js/ceylon.language-1.1.0'
},
name: "main",
out: "main-built.js"
})
|
module.exports = {
root: true,
plugins: ['prettier', '@typescript-eslint'],
extends: ['tui/es6', 'plugin:prettier/recommended', 'plugin:@typescript-eslint/recommended'],
parser: '@typescript-eslint/parser',
parserOptions: {
parser: 'typescript-eslint-parser',
},
env: {
browser: true,
node: true,
jest: true,
},
globals: {
jest: true,
},
ignorePatterns: ['node_modules/*', 'dist'],
rules: {
'@typescript-eslint/no-non-null-assertion': 0,
'@typescript-eslint/explicit-function-return-type': 0,
'@typescript-eslint/explicit-module-boundary-types': 0,
'@typescript-eslint/no-explicit-any': 0,
'@typescript-eslint/ban-types': 0,
'@typescript-eslint/ban-ts-comment': 0,
'@typescript-eslint/no-useless-constructor': 2,
'lines-around-directive': 0,
'newline-before-return': 0,
'no-use-before-define': 0,
'no-useless-constructor': 0,
'padding-line-between-statements': [
2,
{ blankLine: 'always', prev: ['const', 'let', 'var'], next: '*' },
{ blankLine: 'any', prev: ['const', 'let', 'var'], next: ['const', 'let', 'var'] },
],
'no-useless-rename': 'error',
'no-duplicate-imports': ['error', { includeExports: true }],
'dot-notation': ['error', { allowKeywords: true }],
'prefer-destructuring': [
'error',
{
VariableDeclarator: {
array: true,
object: true,
},
AssignmentExpression: {
array: false,
object: false,
},
},
{
enforceForRenamedProperties: false,
},
],
'arrow-body-style': ['error', 'as-needed', { requireReturnForObjectLiteral: true }],
'object-property-newline': ['error', { allowMultiplePropertiesPerLine: true }],
'no-sync': 0,
complexity: 0,
'max-nested-callbacks': ['error', 4],
'no-cond-assign': 0,
'max-depth': ['error', 4],
'no-return-assign': 0,
},
};
|
import React from 'react'
import renderer from 'react-test-renderer'
import { ButtonBase, IconButton, Button } from '../../lib'
test('Button.js component renders without crashing', () => {
const component = renderer.create(
<Button>I am a button</Button>
)
expect(component).toMatchSnapshot()
})
test('IconButton.js component renders without crashing', () => {
const component = renderer.create(
<IconButton>I am an icon</IconButton>
)
expect(component).toMatchSnapshot()
})
|
import {
bootstrapDiagram,
inject
} from 'test/TestHelper';
import { forEach } from 'min-dash';
import distributeElementsModule from 'lib/features/distribute-elements';
import modelingModule from 'lib/features/modeling';
function expectRanges(rangeGroups, expectedRanges) {
expect(rangeGroups).to.have.length(expectedRanges.length);
forEach(rangeGroups, function(group, idx) {
expect(group.range).to.eql({
min: expectedRanges[idx].min,
max: expectedRanges[idx].max
});
expect(group.elements).to.eql(expectedRanges[idx].elements);
});
}
describe('features/distribute-elements', function() {
beforeEach(bootstrapDiagram({
modules: [ distributeElementsModule, modelingModule ]
}));
describe('methods', function() {
var s1 = {
id: 's1',
x: -200,
y: -200,
width: 100,
height: 100
},
s2 = {
id: 's2',
x: -150,
y: -100,
width: 100,
height: 100
},
s3 = {
id: 's3',
x: 325,
y: 250,
width: 100,
height: 100
},
s4 = {
id: 's4',
x: 600,
y: 350,
width: 100,
height: 100
},
s5 = {
id: 's5',
x: 650,
y: 451,
width: 100,
height: 100
};
var elements = [ s1, s2, s3, s4, s5 ];
describe('#createGroups', function() {
it('should group elements horizontally', inject(function(distributeElements) {
// given
distributeElements._setOrientation('horizontal');
// when
var rangeGroups = distributeElements._createGroups(elements);
// then
expectRanges(rangeGroups, [
{ min: -195, max: -105, elements: [ s1, s2 ] },
{ min: 330, max: 420, elements: [ s3 ] },
{ min: 605, max: 695, elements: [ s4, s5 ] }
]);
}));
it('should group elements vertically', inject(function(distributeElements) {
// given
distributeElements._setOrientation('vertical');
// when
var rangeGroups = distributeElements._createGroups(elements);
// then
expectRanges(rangeGroups, [
{ min: -195, max: -105, elements: [ s1 ] },
{ min: -95, max: -5, elements: [ s2 ] },
{ min: 255, max: 345, elements: [ s3 ] },
{ min: 355, max: 445, elements: [ s4 ] },
{ min: 456, max: 546, elements: [ s5 ] }
]);
}));
});
describe('hasIntersection', function() {
it('should return true for intersecting ranges', inject(function(distributeElements) {
// when
var result = distributeElements._hasIntersection({ min: 100, max: 200 }, { min: 150, max: 200 });
// then
expect(result).to.be.true;
}));
it('should return false for NON intersecting ranges', inject(function(distributeElements) {
// when
var result = distributeElements._hasIntersection({ min: 100, max: 200 }, { min: 250, max: 300 });
// then
expect(result).to.be.false;
}));
it('should return true for negative intersecting ranges', inject(function(distributeElements) {
// when
var result = distributeElements._hasIntersection({ min: -200, max: -100 }, { min: -150, max: -50 });
// then
expect(result).to.be.true;
}));
});
});
describe('integration', function() {
var rootShape, shape1, shape2, shape3, shape4, shape5, shapeBig;
beforeEach(inject(function(elementFactory, canvas) {
rootShape = elementFactory.createRoot({
id: 'root'
});
canvas.setRootElement(rootShape);
shape1 = elementFactory.createShape({
id: 's1',
x: 100, y: 100, width: 100, height: 100
});
canvas.addShape(shape1, rootShape);
shape2 = elementFactory.createShape({
id: 's2',
x: 250, y: 100, width: 100, height: 100
});
canvas.addShape(shape2, rootShape);
shape3 = elementFactory.createShape({
id: 's3',
x: 325, y: 250, width: 100, height: 100
});
canvas.addShape(shape3, rootShape);
shape4 = elementFactory.createShape({
id: 's4',
x: 600, y: 350, width: 100, height: 100
});
canvas.addShape(shape4, rootShape);
shape5 = elementFactory.createShape({
id: 's5',
x: 650, y: 451, width: 100, height: 100
});
canvas.addShape(shape5, rootShape);
shapeBig = elementFactory.createShape({
id: 'sBig',
x: 150, y: 400, width: 200, height: 200
});
canvas.addShape(shapeBig, rootShape);
}));
it('should align shapes of same size horizontally', inject(function(distributeElements) {
// given
var elements = [ shape5, shape3, shape1, shape4, shape2, shapeBig ];
// when
distributeElements.trigger(elements, 'horizontal');
expect(shape1.x).to.equal(100);
expect(shape1.y).to.equal(100);
expect(shape2.x).to.equal(373);
expect(shape2.y).to.equal(100);
expect(shape3.x).to.equal(373);
expect(shape3.y).to.equal(250);
expect(shape4.x).to.equal(650);
expect(shape4.y).to.equal(350);
expect(shape5.x).to.equal(650);
expect(shape5.y).to.equal(451);
expect(shapeBig.x).to.equal(150);
expect(shapeBig.y).to.equal(400);
}));
it('should align shapes of same size vertically', inject(function(distributeElements) {
// given
var elements = [ shape5, shape3, shape1, shape4, shape2, shapeBig ];
// when
distributeElements.trigger(elements, 'vertical');
expect(shape1.x).to.equal(100);
expect(shape1.y).to.equal(100);
expect(shape2.x).to.equal(250);
expect(shape2.y).to.equal(100);
expect(shape3.x).to.equal(325);
expect(shape3.y).to.equal(219);
expect(shape4.x).to.equal(600);
expect(shape4.y).to.equal(338);
expect(shape5.x).to.equal(650);
expect(shape5.y).to.equal(451);
expect(shapeBig.x).to.equal(150);
expect(shapeBig.y).to.equal(400);
}));
});
});
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M17 4h3v16h-3V4zM5 14h3v6H5v-6zm6-5h3v11h-3V9z"
}), 'SignalCellularAltSharp');
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'you-rockstar',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.locationType = 'hash';
ENV.baseUrl = '/you-rockstar/';
}
return ENV;
};
|
datab = [{},{"Application Entity":{"colspan":"1","rowspan":"1","text":"STORAGE-SCU"},"Role":{"colspan":"1","rowspan":"1","text":"SCU"},"Default AE Title":{"colspan":"1","rowspan":"1","text":"EX_STORE_SCU"},"Default TCP/IP Port":{"colspan":"1","rowspan":"1","text":"None"}},{"Application Entity":{"colspan":"1","rowspan":"1","text":"STORAGE-SCP"},"Role":{"colspan":"1","rowspan":"1","text":"SCP"},"Default AE Title":{"colspan":"1","rowspan":"1","text":"EX_STORE_SCP"},"Default TCP/IP Port":{"colspan":"1","rowspan":"1","text":"4000"}},{"Application Entity":{"colspan":"1","rowspan":"1","text":"QUERY-RETRIEVE-SCP"},"Role":{"colspan":"1","rowspan":"1","text":"SCP"},"Default AE Title":{"colspan":"1","rowspan":"1","text":"EX_QUERY_SCP"},"Default TCP/IP Port":{"colspan":"1","rowspan":"1","text":"5000"}}];
|
/**
* Allows configuration of wip and schedule state mapping for kanban columns
*
* @example
* Ext.create('Ext.Container', {
* items: [{
* xtype: 'kanbancolumnsettingsfield',
* value: {}
* }],
* renderTo: Ext.getBody().dom
* });
*
*/
Ext.define('Rally.technicalservices.ColumnSettingsField', {
extend: 'Ext.form.field.Base',
alias: 'widget.tscolumnsettingsfield',
requires: [
'Rally.ui.combobox.ComboBox',
'Rally.ui.TextField',
'Rally.ui.combobox.FieldValueComboBox'
],
fieldSubTpl: '<div id="{id}" class="settings-grid"></div>',
width: 400,
cls: 'column-settings',
config: {
/**
* @cfg {Object}
*
* The column settings value for this field
*/
value: undefined,
/**
*
* @cfg [{Object}] rallygrid column definition ({dataIndex:....})
*/
gridColumns: []
},
onDestroy: function() {
if (this._grid) {
this._grid.destroy();
delete this._grid;
}
this.callParent(arguments);
},
onRender: function() {
this.callParent(arguments);
var data = Ext.Array.map(this.gridColumns, this._recordToGridRow, this);
this._store = Ext.create('Ext.data.Store', {
fields: ['column', 'show'],
data: data
});
this._grid = Ext.create('Rally.ui.grid.Grid', {
autoWidth: true,
renderTo: this.inputEl,
columnCfgs: this._getColumnCfgs(),
showPagingToolbar: false,
showRowActionsColumn: false,
enableRanking: false,
store: this._store,
editingConfig: {
publishMessages: false
}
});
},
_getColumnCfgs: function() {
var columns = [
{
text: 'Column',
dataIndex: 'column',
emptyCellText: 'None',
flex: 2
},
{
text: 'Show',
dataIndex: 'show',
flex: 1,
renderer: function (value) {
return value === true ? 'Yes' : 'No';
},
editor: {
xtype: 'rallycombobox',
displayField: 'name',
valueField: 'value',
editable: false,
storeType: 'Ext.data.Store',
storeConfig: {
remoteFilter: false,
fields: ['name', 'value'],
data: [
{'name': 'Yes', 'value': true},
{'name': 'No', 'value': false}
]
}
}
}
];
return columns;
},
/**
* When a form asks for the data this field represents,
* give it the name of this field and the ref of the selected project (or an empty string).
* Used when persisting the value of this field.
* @return {Object}
*/
getSubmitData: function() {
var data = {};
data[this.name] = Ext.JSON.encode(this._buildSettingValue());
return data;
},
_buildSettingValue: function() {
var columns = {};
this._store.each(function(record) {
if (record.get('show')) {
columns[record.get('column')] = {
show: record.get('show')
};
}
}, this);
return columns;
},
getErrors: function() {
var errors = [];
if (this._storeLoaded && !Ext.Object.getSize(this._buildSettingValue())) {
errors.push('At least one column must be shown.');
}
return errors;
},
setValue: function(value) {
this.callParent(arguments);
this._value = value;
},
_getColumnValue: function(columnName) {
var value = this._value;
if ( Ext.isString(value) ) {
value = Ext.JSON.decode(value);
}
if ( Ext.isEmpty(value) || Ext.isEmpty(value[columnName])) {
return null;
}
return value[columnName];
},
_recordToGridRow: function(grid_column) {
var column_name = grid_column['text'];
var show = this._getColumnValue(column_name) && this._getColumnValue(column_name)['show'];
var column = {
column: column_name,
show: show
};
return column;
}
});
|
import { combineReducers } from 'redux';
import CardsReducer from './reducer_cards';
const rootReducer = combineReducers({
cards: CardsReducer
});
export default rootReducer;
|
/*
Ratings and how they work:
-2: Extremely detrimental
The sort of ability that relegates Pokemon with Uber-level BSTs into NU.
ex. Slow Start, Truant
-1: Detrimental
An ability that does more harm than good.
ex. Defeatist, Normalize
0: Useless
An ability with no net effect during a singles battle.
ex. Healer, Illuminate
1: Ineffective
An ability that has a minimal effect. Should not be chosen over any other ability.
ex. Damp, Shell Armor
2: Situationally useful
An ability that can be useful in certain situations.
ex. Blaze, Insomnia
3: Useful
An ability that is generally useful.
ex. Infiltrator, Sturdy
4: Very useful
One of the most popular abilities. The difference between 3 and 4 can be ambiguous.
ex. Protean, Regenerator
5: Essential
The sort of ability that defines metagames.
ex. Desolate Land, Shadow Tag
*/
exports.BattleAbilities = {
"adaptability": {
desc: "This Pokemon's moves that match one of its types have a same-type attack bonus (STAB) of 2 instead of 1.5.",
shortDesc: "This Pokemon's same-type attack bonus (STAB) is 2 instead of 1.5.",
onModifyMove: function (move) {
move.stab = 2;
},
id: "adaptability",
name: "Adaptability",
rating: 3.5,
num: 91
},
"aftermath": {
desc: "If this Pokemon is knocked out with a contact move, that move's user loses 1/4 of its maximum HP, rounded down. If any active Pokemon has the Ability Damp, this effect is prevented.",
shortDesc: "If this Pokemon is KOed with a contact move, that move's user loses 1/4 its max HP.",
id: "aftermath",
name: "Aftermath",
onAfterDamageOrder: 1,
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.flags['contact'] && !target.hp) {
this.damage(source.maxhp / 4, source, target, null, true);
}
},
rating: 2.5,
num: 106
},
"aerilate": {
desc: "This Pokemon's Normal-type moves become Flying-type moves and have their power multiplied by 1.3. This effect comes after other effects that change a move's type, but before Ion Deluge and Electrify's effects.",
shortDesc: "This Pokemon's Normal-type moves become Flying type and have 1.3x power.",
onModifyMovePriority: -1,
onModifyMove: function (move, pokemon) {
if (move.type === 'Normal' && move.id !== 'naturalgift') {
move.type = 'Flying';
if (move.category !== 'Status') pokemon.addVolatile('aerilate');
}
},
effect: {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower, pokemon, target, move) {
return this.chainModify([0x14CD, 0x1000]);
}
},
id: "aerilate",
name: "Aerilate",
rating: 4,
num: 185
},
"airlock": {
shortDesc: "While this Pokemon is active, the effects of weather conditions are disabled.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Air Lock');
},
suppressWeather: true,
id: "airlock",
name: "Air Lock",
rating: 3,
num: 76
},
"analytic": {
desc: "The power of this Pokemon's move is multiplied by 1.3 if it is the last to move in a turn. Does not affect Doom Desire and Future Sight.",
shortDesc: "This Pokemon's attacks have 1.3x power if it is the last to move in a turn.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (!this.willMove(defender)) {
this.debug('Analytic boost');
return this.chainModify([0x14CD, 0x1000]); // The Analytic modifier is slightly higher than the normal 1.3 (0x14CC)
}
},
id: "analytic",
name: "Analytic",
rating: 2,
num: 148
},
"angerpoint": {
desc: "If this Pokemon, but not its substitute, is struck by a critical hit, its Attack is raised by 12 stages.",
shortDesc: "If this Pokemon (not its substitute) takes a critical hit, its Attack is raised 12 stages.",
onAfterDamage: function (damage, target, source, move) {
if (!target.hp) return;
if (move && move.effectType === 'Move' && move.crit) {
target.setBoost({atk: 6});
this.add('-setboost', target, 'atk', 12, '[from] ability: Anger Point');
}
},
id: "angerpoint",
name: "Anger Point",
rating: 2,
num: 83
},
"anticipation": {
desc: "On switch-in, this Pokemon is alerted if any opposing Pokemon has an attack that is super effective on this Pokemon, or an OHKO move. Counter, Metal Burst, and Mirror Coat count as attacking moves of their respective types, while Hidden Power, Judgment, Natural Gift, Techno Blast, and Weather Ball are considered Normal-type moves.",
shortDesc: "On switch-in, this Pokemon shudders if any foe has a supereffective or OHKO move.",
onStart: function (pokemon) {
var targets = pokemon.side.foe.active;
for (var i = 0; i < targets.length; i++) {
if (!targets[i] || targets[i].fainted) continue;
for (var j = 0; j < targets[i].moveset.length; j++) {
var move = this.getMove(targets[i].moveset[j].move);
if (move.category !== 'Status' && (this.getImmunity(move.type, pokemon) && this.getEffectiveness(move.type, pokemon) > 0 || move.ohko)) {
this.add('-activate', pokemon, 'ability: Anticipation');
return;
}
}
}
},
id: "anticipation",
name: "Anticipation",
rating: 1,
num: 107
},
"arenatrap": {
desc: "Prevents adjacent opposing Pokemon from choosing to switch out unless they are immune to trapping or are airborne.",
shortDesc: "Prevents adjacent foes from choosing to switch unless they are airborne.",
onFoeModifyPokemon: function (pokemon) {
if (!this.isAdjacent(pokemon, this.effectData.target)) return;
if (pokemon.isGrounded()) {
pokemon.tryTrap(true);
}
},
onFoeMaybeTrapPokemon: function (pokemon, source) {
if (!source) source = this.effectData.target;
if (!this.isAdjacent(pokemon, source)) return;
if (pokemon.isGrounded()) {
pokemon.maybeTrapped = true;
}
},
id: "arenatrap",
name: "Arena Trap",
rating: 4.5,
num: 71
},
"aromaveil": {
desc: "This Pokemon and its allies cannot be affected by Attract, Disable, Encore, Heal Block, Taunt, or Torment.",
shortDesc: "Protects user/allies from Attract, Disable, Encore, Heal Block, Taunt, and Torment.",
onAllyTryHit: function (target, source, move) {
if (move && move.id in {attract:1, disable:1, encore:1, healblock:1, taunt:1, torment:1}) {
return false;
}
},
id: "aromaveil",
name: "Aroma Veil",
rating: 1.5,
num: 165
},
"aurabreak": {
desc: "While this Pokemon is active, the effects of the Abilities Dark Aura and Fairy Aura are reversed, multiplying the power of Dark- and Fairy-type moves, respectively, by 3/4 instead of 1.33.",
shortDesc: "While this Pokemon is active, the Dark Aura and Fairy Aura power modifier is 0.75x.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Aura Break');
},
onAnyTryPrimaryHit: function (target, source, move) {
if (target === source || move.category === 'Status') return;
source.addVolatile('aurabreak');
},
effect: {
duration: 1
},
id: "aurabreak",
name: "Aura Break",
rating: 2,
num: 188
},
"baddreams": {
desc: "Causes adjacent opposing Pokemon to lose 1/8 of their maximum HP, rounded down, at the end of each turn if they are asleep.",
shortDesc: "Causes sleeping adjacent foes to lose 1/8 of their max HP at the end of each turn.",
onResidualOrder: 26,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
if (!pokemon.hp) return;
for (var i = 0; i < pokemon.side.foe.active.length; i++) {
var target = pokemon.side.foe.active[i];
if (!target || !target.hp) continue;
if (target.status === 'slp') {
this.damage(target.maxhp / 8, target);
}
}
},
id: "baddreams",
name: "Bad Dreams",
rating: 2,
num: 123
},
"battlearmor": {
shortDesc: "This Pokemon cannot be struck by a critical hit.",
onCriticalHit: false,
id: "battlearmor",
name: "Battle Armor",
rating: 1,
num: 4
},
"bigpecks": {
shortDesc: "Prevents other Pokemon from lowering this Pokemon's Defense stat stage.",
onBoost: function (boost, target, source, effect) {
if (source && target === source) return;
if (boost['def'] && boost['def'] < 0) {
boost['def'] = 0;
if (!effect.secondaries) this.add("-fail", target, "unboost", "Defense", "[from] ability: Big Pecks", "[of] " + target);
}
},
id: "bigpecks",
name: "Big Pecks",
rating: 0.5,
num: 145
},
"blaze": {
desc: "When this Pokemon has 1/3 or less of its maximum HP, rounded down, its attacking stat is multiplied by 1.5 while using a Fire-type attack.",
shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Fire attacks do 1.5x damage.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk, attacker, defender, move) {
if (move.type === 'Fire' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Blaze boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function (atk, attacker, defender, move) {
if (move.type === 'Fire' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Blaze boost');
return this.chainModify(1.5);
}
},
id: "blaze",
name: "Blaze",
rating: 2,
num: 66
},
"bulletproof": {
shortDesc: "This Pokemon is immune to bullet moves.",
onTryHit: function (pokemon, target, move) {
if (move.flags['bullet']) {
this.add('-immune', pokemon, '[msg]', '[from] Bulletproof');
return null;
}
},
id: "bulletproof",
name: "Bulletproof",
rating: 3,
num: 171
},
"cheekpouch": {
desc: "If this Pokemon eats a Berry, it restores 1/3 of its maximum HP, rounded down, in addition to the Berry's effect.",
shortDesc: "If this Pokemon eats a Berry, it restores 1/3 of its max HP after the Berry's effect.",
onEatItem: function (item, pokemon) {
this.heal(pokemon.maxhp / 3);
},
id: "cheekpouch",
name: "Cheek Pouch",
rating: 2,
num: 167
},
"chlorophyll": {
shortDesc: "If Sunny Day is active, this Pokemon's Speed is doubled.",
onModifySpe: function (speMod) {
if (this.isWeather(['sunnyday', 'desolateland'])) {
return this.chain(speMod, 2);
}
},
id: "chlorophyll",
name: "Chlorophyll",
rating: 2.5,
num: 34
},
"clearbody": {
shortDesc: "Prevents other Pokemon from lowering this Pokemon's stat stages.",
onBoost: function (boost, target, source, effect) {
if (source && target === source) return;
var showMsg = false;
for (var i in boost) {
if (boost[i] < 0) {
delete boost[i];
showMsg = true;
}
}
if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: Clear Body", "[of] " + target);
},
id: "clearbody",
name: "Clear Body",
rating: 2,
num: 29
},
"cloudnine": {
shortDesc: "While this Pokemon is active, the effects of weather conditions are disabled.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Cloud Nine');
},
suppressWeather: true,
id: "cloudnine",
name: "Cloud Nine",
rating: 3,
num: 13
},
"colorchange": {
desc: "This Pokemon's type changes to match the type of the last move that hit it, unless that type is already one of its types. This effect applies after all hits from a multi-hit move; Sheer Force prevents it from activating if the move has a secondary effect.",
shortDesc: "This Pokemon's type changes to the type of a move it's hit by, unless it has the type.",
onAfterMoveSecondary: function (target, source, move) {
var type = move.type;
if (target.isActive && move.effectType === 'Move' && move.category !== 'Status' && type !== '???' && !target.hasType(type)) {
if (!target.setType(type)) return false;
this.add('-start', target, 'typechange', type, '[from] Color Change');
target.update();
}
},
id: "colorchange",
name: "Color Change",
rating: 1,
num: 16
},
"competitive": {
desc: "This Pokemon's Special Attack is raised by 2 stages for each of its stat stages that is lowered by an opposing Pokemon.",
shortDesc: "This Pokemon's Sp. Atk is raised by 2 for each of its stats that is lowered by a foe.",
onAfterEachBoost: function (boost, target, source) {
if (!source || target.side === source.side) {
return;
}
var statsLowered = false;
for (var i in boost) {
if (boost[i] < 0) {
statsLowered = true;
}
}
if (statsLowered) {
this.boost({spa: 2});
}
},
id: "competitive",
name: "Competitive",
rating: 2.5,
num: 172
},
"compoundeyes": {
shortDesc: "This Pokemon's moves have their accuracy multiplied by 1.3.",
onSourceModifyAccuracy: function (accuracy) {
if (typeof accuracy !== 'number') return;
this.debug('compoundeyes - enhancing accuracy');
return accuracy * 1.3;
},
id: "compoundeyes",
name: "Compound Eyes",
rating: 3.5,
num: 14
},
"contrary": {
shortDesc: "If this Pokemon has a stat stage raised it is lowered instead, and vice versa.",
onBoost: function (boost) {
for (var i in boost) {
boost[i] *= -1;
}
},
id: "contrary",
name: "Contrary",
rating: 4,
num: 126
},
"cursedbody": {
desc: "If this Pokemon is hit by an attack, there is a 30% chance that move gets disabled unless one of the attacker's moves is already disabled.",
shortDesc: "If this Pokemon is hit by an attack, there is a 30% chance that move gets disabled.",
onAfterDamage: function (damage, target, source, move) {
if (!source || source.volatiles['disable']) return;
if (source !== target && move && move.effectType === 'Move') {
if (this.random(10) < 3) {
source.addVolatile('disable');
}
}
},
id: "cursedbody",
name: "Cursed Body",
rating: 2,
num: 130
},
"cutecharm": {
desc: "There is a 30% chance a Pokemon making contact with this Pokemon will become infatuated if it is of the opposite gender.",
shortDesc: "30% chance of infatuating Pokemon of the opposite gender if they make contact.",
onAfterDamage: function (damage, target, source, move) {
if (move && move.flags['contact']) {
if (this.random(10) < 3) {
source.addVolatile('attract', target);
}
}
},
id: "cutecharm",
name: "Cute Charm",
rating: 1,
num: 56
},
"damp": {
desc: "While this Pokemon is active, Self-Destruct, Explosion, and the Ability Aftermath are prevented from having an effect.",
shortDesc: "While this Pokemon is active, Self-Destruct, Explosion, and Aftermath have no effect.",
id: "damp",
onAnyTryMove: function (target, source, effect) {
if (effect.id === 'selfdestruct' || effect.id === 'explosion') {
this.attrLastMove('[still]');
this.add('-activate', this.effectData.target, 'ability: Damp');
return false;
}
},
onAnyDamage: function (damage, target, source, effect) {
if (effect && effect.id === 'aftermath') {
return false;
}
},
name: "Damp",
rating: 1,
num: 6
},
"darkaura": {
desc: "While this Pokemon is active, the power of Dark-type moves used by active Pokemon is multiplied by 1.33.",
shortDesc: "While this Pokemon is active, a Dark move used by any Pokemon has 1.33x power.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Dark Aura');
},
onAnyTryPrimaryHit: function (target, source, move) {
if (target === source || move.category === 'Status') return;
if (move.type === 'Dark') {
source.addVolatile('aura');
}
},
id: "darkaura",
name: "Dark Aura",
rating: 3,
num: 186
},
"defeatist": {
desc: "While this Pokemon has 1/2 or less of its maximum HP, its Attack and Special Attack are halved.",
shortDesc: "While this Pokemon has 1/2 or less of its max HP, its Attack and Sp. Atk are halved.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk, pokemon) {
if (pokemon.hp < pokemon.maxhp / 2) {
return this.chainModify(0.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function (atk, pokemon) {
if (pokemon.hp < pokemon.maxhp / 2) {
return this.chainModify(0.5);
}
},
onResidual: function (pokemon) {
pokemon.update();
},
id: "defeatist",
name: "Defeatist",
rating: -1,
num: 129
},
"defiant": {
desc: "This Pokemon's Attack is raised by 2 stages for each of its stat stages that is lowered by an opposing Pokemon.",
shortDesc: "This Pokemon's Attack is raised by 2 for each of its stats that is lowered by a foe.",
onAfterEachBoost: function (boost, target, source) {
if (!source || target.side === source.side) {
return;
}
var statsLowered = false;
for (var i in boost) {
if (boost[i] < 0) {
statsLowered = true;
}
}
if (statsLowered) {
this.boost({atk: 2});
}
},
id: "defiant",
name: "Defiant",
rating: 2.5,
num: 128
},
"deltastream": {
desc: "On switch-in, the weather becomes strong winds that remove the weaknesses of the Flying type from Flying-type Pokemon. This weather remains in effect until this Ability is no longer active for any Pokemon, or the weather is changed by Desolate Land or Primordial Sea.",
shortDesc: "On switch-in, strong winds begin until this Ability is not active in battle.",
onStart: function (source) {
this.setWeather('deltastream');
},
onAnySetWeather: function (target, source, weather) {
if (this.getWeather().id === 'deltastream' && !(weather.id in {desolateland:1, primordialsea:1, deltastream:1})) return false;
},
onEnd: function (pokemon) {
if (this.weatherData.source !== pokemon) return;
for (var i = 0; i < this.sides.length; i++) {
for (var j = 0; j < this.sides[i].active.length; j++) {
var target = this.sides[i].active[j];
if (target === pokemon) continue;
if (target && target.hp && target.hasAbility('deltastream')) {
this.weatherData.source = target;
return;
}
}
}
this.clearWeather();
},
id: "deltastream",
name: "Delta Stream",
rating: 5,
num: 191
},
"desolateland": {
desc: "On switch-in, the weather becomes extremely harsh sunlight that prevents damaging Water-type moves from executing, in addition to all the effects of Sunny Day. This weather remains in effect until this Ability is no longer active for any Pokemon, or the weather is changed by Delta Stream or Primordial Sea.",
shortDesc: "On switch-in, extremely harsh sunlight begins until this Ability is not active in battle.",
onStart: function (source) {
this.setWeather('desolateland');
},
onAnySetWeather: function (target, source, weather) {
if (this.getWeather().id === 'desolateland' && !(weather.id in {desolateland:1, primordialsea:1, deltastream:1})) return false;
},
onEnd: function (pokemon) {
if (this.weatherData.source !== pokemon) return;
for (var i = 0; i < this.sides.length; i++) {
for (var j = 0; j < this.sides[i].active.length; j++) {
var target = this.sides[i].active[j];
if (target === pokemon) continue;
if (target && target.hp && target.hasAbility('desolateland')) {
this.weatherData.source = target;
return;
}
}
}
this.clearWeather();
},
id: "desolateland",
name: "Desolate Land",
rating: 5,
num: 190
},
"download": {
desc: "On switch-in, this Pokemon's Attack or Special Attack is raised by 1 stage based on the weaker combined defensive stat of all opposing Pokemon. Attack is raised if their Defense is lower, and Special Attack is raised if their Special Defense is the same or lower.",
shortDesc: "On switch-in, Attack or Sp. Atk is raised 1 stage based on the foes' weaker Defense.",
onStart: function (pokemon) {
var foeactive = pokemon.side.foe.active;
var totaldef = 0;
var totalspd = 0;
for (var i = 0; i < foeactive.length; i++) {
if (!foeactive[i] || foeactive[i].fainted) continue;
totaldef += foeactive[i].getStat('def', false, true);
totalspd += foeactive[i].getStat('spd', false, true);
}
if (totaldef && totaldef >= totalspd) {
this.boost({spa:1});
} else if (totalspd) {
this.boost({atk:1});
}
},
id: "download",
name: "Download",
rating: 4,
num: 88
},
"drizzle": {
shortDesc: "On switch-in, this Pokemon summons Rain Dance.",
onStart: function (source) {
this.setWeather('raindance');
},
id: "drizzle",
name: "Drizzle",
rating: 4,
num: 2
},
"drought": {
shortDesc: "On switch-in, this Pokemon summons Sunny Day.",
onStart: function (source) {
this.setWeather('sunnyday');
},
id: "drought",
name: "Drought",
rating: 4,
num: 70
},
"dryskin": {
desc: "This Pokemon is immune to Water-type moves and restores 1/4 of its maximum HP, rounded down, when hit by a Water-type move. The power of Fire-type moves is multiplied by 1.25 when used on this Pokemon. At the end of each turn, this Pokemon restores 1/8 of its maximum HP, rounded down, if the weather is Rain Dance, and loses 1/8 of its maximum HP, rounded down, if the weather is Sunny Day.",
shortDesc: "This Pokemon is healed 1/4 by Water, 1/8 by Rain; is hurt 1.25x by Fire, 1/8 by Sun.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Water') {
if (!this.heal(target.maxhp / 4)) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
onBasePowerPriority: 7,
onFoeBasePower: function (basePower, attacker, defender, move) {
if (this.effectData.target !== defender) return;
if (move.type === 'Fire') {
return this.chainModify(1.25);
}
},
onWeather: function (target, source, effect) {
if (effect.id === 'raindance' || effect.id === 'primordialsea') {
this.heal(target.maxhp / 8);
} else if (effect.id === 'sunnyday' || effect.id === 'desolateland') {
this.damage(target.maxhp / 8);
}
},
id: "dryskin",
name: "Dry Skin",
rating: 3.5,
num: 87
},
"earlybird": {
shortDesc: "This Pokemon's sleep counter drops by 2 instead of 1.",
id: "earlybird",
name: "Early Bird",
// Implemented in statuses.js
rating: 2.5,
num: 48
},
"effectspore": {
desc: "30% chance a Pokemon making contact with this Pokemon will be poisoned, paralyzed, or fall asleep.",
shortDesc: "30% chance of poison/paralysis/sleep on others making contact with this Pokemon.",
onAfterDamage: function (damage, target, source, move) {
if (move && move.flags['contact'] && !source.status && source.runImmunity('powder')) {
var r = this.random(100);
if (r < 11) {
source.setStatus('slp', target);
} else if (r < 21) {
source.setStatus('par', target);
} else if (r < 30) {
source.setStatus('psn', target);
}
}
},
id: "effectspore",
name: "Effect Spore",
rating: 2,
num: 27
},
"fairyaura": {
desc: "While this Pokemon is active, the power of Fairy-type moves used by active Pokemon is multiplied by 1.33.",
shortDesc: "While this Pokemon is active, a Fairy move used by any Pokemon has 1.33x power.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Fairy Aura');
},
onAnyTryPrimaryHit: function (target, source, move) {
if (target === source || move.category === 'Status') return;
if (move.type === 'Fairy') {
source.addVolatile('aura');
}
},
id: "fairyaura",
name: "Fairy Aura",
rating: 3,
num: 187
},
"filter": {
shortDesc: "This Pokemon receives 3/4 damage from supereffective attacks.",
onSourceModifyDamage: function (damage, source, target, move) {
if (move.typeMod > 0) {
this.debug('Filter neutralize');
return this.chainModify(0.75);
}
},
id: "filter",
name: "Filter",
rating: 3,
num: 111
},
"flamebody": {
shortDesc: "30% chance a Pokemon making contact with this Pokemon will be burned.",
onAfterDamage: function (damage, target, source, move) {
if (move && move.flags['contact']) {
if (this.random(10) < 3) {
source.trySetStatus('brn', target, move);
}
}
},
id: "flamebody",
name: "Flame Body",
rating: 2,
num: 49
},
"flareboost": {
desc: "While this Pokemon is burned, the power of its special attacks is multiplied by 1.5.",
shortDesc: "While this Pokemon is burned, its special attacks have 1.5x power.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (attacker.status === 'brn' && move.category === 'Special') {
return this.chainModify(1.5);
}
},
id: "flareboost",
name: "Flare Boost",
rating: 2.5,
num: 138
},
"flashfire": {
desc: "This Pokemon is immune to Fire-type moves. The first time it is hit by a Fire-type move, its attacking stat is multiplied by 1.5 while using a Fire-type attack as long as it remains active and has this Ability. If this Pokemon is frozen, it cannot be defrosted by Fire-type attacks.",
shortDesc: "This Pokemon's Fire attacks do 1.5x damage if hit by one Fire move; Fire immunity.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Fire') {
move.accuracy = true;
if (!target.addVolatile('flashfire')) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
onEnd: function (pokemon) {
pokemon.removeVolatile('flashfire');
},
effect: {
noCopy: true, // doesn't get copied by Baton Pass
onStart: function (target) {
this.add('-start', target, 'ability: Flash Fire');
},
onModifyAtkPriority: 5,
onModifyAtk: function (atk, attacker, defender, move) {
if (move.type === 'Fire') {
this.debug('Flash Fire boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function (atk, attacker, defender, move) {
if (move.type === 'Fire') {
this.debug('Flash Fire boost');
return this.chainModify(1.5);
}
},
onEnd: function (target) {
this.add('-end', target, 'ability: Flash Fire', '[silent]');
}
},
id: "flashfire",
name: "Flash Fire",
rating: 3,
num: 18
},
"flowergift": {
desc: "If this Pokemon is a Cherrim and Sunny Day is active, it changes to Sunshine Form and the Attack and Special Defense of it and its allies are multiplied by 1.5.",
shortDesc: "If user is Cherrim and Sunny Day is active, it and allies' Attack and Sp. Def are 1.5x.",
onStart: function (pokemon) {
delete this.effectData.forme;
},
onUpdate: function (pokemon) {
if (!pokemon.isActive || pokemon.baseTemplate.speciesid !== 'cherrim') return;
if (this.isWeather(['sunnyday', 'desolateland'])) {
if (pokemon.template.speciesid !== 'cherrimsunshine') {
pokemon.formeChange('Cherrim-Sunshine');
this.add('-formechange', pokemon, 'Cherrim-Sunshine', '[msg]');
}
} else {
if (pokemon.template.speciesid === 'cherrimsunshine') {
pokemon.formeChange('Cherrim');
this.add('-formechange', pokemon, 'Cherrim', '[msg]');
}
}
},
onModifyAtkPriority: 3,
onAllyModifyAtk: function (atk) {
if (this.effectData.target.template.speciesid !== 'cherrim') return;
if (this.isWeather(['sunnyday', 'desolateland'])) {
return this.chainModify(1.5);
}
},
onModifySpDPriority: 4,
onAllyModifySpD: function (spd) {
if (this.effectData.target.template.speciesid !== 'cherrim') return;
if (this.isWeather(['sunnyday', 'desolateland'])) {
return this.chainModify(1.5);
}
},
id: "flowergift",
name: "Flower Gift",
rating: 2.5,
num: 122
},
"flowerveil": {
desc: "Grass-type Pokemon on this Pokemon's side cannot have their stat stages lowered by other Pokemon or have a major status condition inflicted on them by other Pokemon.",
shortDesc: "This side's Grass types can't have stats lowered or status inflicted by other Pokemon.",
onAllyBoost: function (boost, target, source, effect) {
if ((source && target === source) || !target.hasType('Grass')) return;
var showMsg = false;
for (var i in boost) {
if (boost[i] < 0) {
delete boost[i];
showMsg = true;
}
}
if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: Flower Veil", "[of] " + target);
},
onAllySetStatus: function (status, target) {
if (target.hasType('Grass')) return false;
},
id: "flowerveil",
name: "Flower Veil",
rating: 0,
num: 166
},
"forecast": {
desc: "If this Pokemon is a Castform, its type changes to the current weather condition's type, except Sandstorm.",
shortDesc: "Castform's type changes to the current weather condition's type, except Sandstorm.",
onUpdate: function (pokemon) {
if (pokemon.baseTemplate.species !== 'Castform' || pokemon.transformed) return;
var forme = null;
switch (this.effectiveWeather()) {
case 'sunnyday':
case 'desolateland':
if (pokemon.template.speciesid !== 'castformsunny') forme = 'Castform-Sunny';
break;
case 'raindance':
case 'primordialsea':
if (pokemon.template.speciesid !== 'castformrainy') forme = 'Castform-Rainy';
break;
case 'hail':
if (pokemon.template.speciesid !== 'castformsnowy') forme = 'Castform-Snowy';
break;
default:
if (pokemon.template.speciesid !== 'castform') forme = 'Castform';
break;
}
if (pokemon.isActive && forme) {
pokemon.formeChange(forme);
this.add('-formechange', pokemon, forme, '[msg]');
}
},
id: "forecast",
name: "Forecast",
rating: 3,
num: 59
},
"forewarn": {
desc: "On switch-in, this Pokemon is alerted to the move with the highest power, at random, known by an opposing Pokemon.",
shortDesc: "On switch-in, this Pokemon is alerted to the foes' move with the highest power.",
onStart: function (pokemon) {
var targets = pokemon.side.foe.active;
var warnMoves = [];
var warnBp = 1;
for (var i = 0; i < targets.length; i++) {
if (targets[i].fainted) continue;
for (var j = 0; j < targets[i].moveset.length; j++) {
var move = this.getMove(targets[i].moveset[j].move);
var bp = move.basePower;
if (move.ohko) bp = 160;
if (move.id === 'counter' || move.id === 'metalburst' || move.id === 'mirrorcoat') bp = 120;
if (!bp && move.category !== 'Status') bp = 80;
if (bp > warnBp) {
warnMoves = [[move, targets[i]]];
warnBp = bp;
} else if (bp === warnBp) {
warnMoves.push([move, targets[i]]);
}
}
}
if (!warnMoves.length) return;
var warnMove = warnMoves[this.random(warnMoves.length)];
this.add('-activate', pokemon, 'ability: Forewarn', warnMove[0], warnMove[1]);
},
id: "forewarn",
name: "Forewarn",
rating: 1,
num: 108
},
"friendguard": {
shortDesc: "This Pokemon's allies receive 3/4 damage from other Pokemon's attacks.",
id: "friendguard",
name: "Friend Guard",
onAnyModifyDamage: function (damage, source, target, move) {
if (target !== this.effectData.target && target.side === this.effectData.target.side) {
this.debug('Friend Guard weaken');
return this.chainModify(0.75);
}
},
rating: 0,
num: 132
},
"frisk": {
shortDesc: "On switch-in, this Pokemon identifies the held items of all opposing Pokemon.",
onStart: function (pokemon) {
var foeactive = pokemon.side.foe.active;
for (var i = 0; i < foeactive.length; i++) {
if (!foeactive[i] || foeactive[i].fainted) continue;
if (foeactive[i].item) {
this.add('-item', foeactive[i], foeactive[i].getItem().name, '[from] ability: Frisk', '[of] ' + pokemon, '[identify]');
}
}
},
id: "frisk",
name: "Frisk",
rating: 1.5,
num: 119
},
"furcoat": {
shortDesc: "This Pokemon's Defense is doubled.",
onModifyDefPriority: 6,
onModifyDef: function (def) {
return this.chainModify(2);
},
id: "furcoat",
name: "Fur Coat",
rating: 3.5,
num: 169
},
"galewings": {
shortDesc: "This Pokemon's Flying-type moves have their priority increased by 1.",
onModifyPriority: function (priority, pokemon, target, move) {
if (move && move.type === 'Flying') return priority + 1;
},
id: "galewings",
name: "Gale Wings",
rating: 4.5,
num: 177
},
"gluttony": {
shortDesc: "When this Pokemon has 1/2 or less of its maximum HP, it uses certain Berries early.",
id: "gluttony",
name: "Gluttony",
rating: 1,
num: 82
},
"gooey": {
shortDesc: "Pokemon making contact with this Pokemon have their Speed lowered by 1 stage.",
onAfterDamage: function (damage, target, source, effect) {
if (effect && effect.flags['contact']) this.boost({spe: -1}, source, target);
},
id: "gooey",
name: "Gooey",
rating: 2.5,
num: 183
},
"grasspelt": {
shortDesc: "If Grassy Terrain is active, this Pokemon's Defense is multiplied by 1.5.",
onModifyDefPriority: 6,
onModifyDef: function (pokemon) {
if (this.isTerrain('grassyterrain')) return this.chainModify(1.5);
},
id: "grasspelt",
name: "Grass Pelt",
rating: 0.5,
num: 179
},
"guts": {
desc: "If this Pokemon has a major status condition, its Attack is multiplied by 1.5; burn's physical damage halving is ignored.",
shortDesc: "If this Pokemon is statused, its Attack is 1.5x; ignores burn halving physical damage.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk, pokemon) {
if (pokemon.status) {
return this.chainModify(1.5);
}
},
id: "guts",
name: "Guts",
rating: 3,
num: 62
},
"harvest": {
desc: "If the last item this Pokemon used is a Berry, there is a 50% chance it gets restored at the end of each turn. If Sunny Day is active, this chance is 100%.",
shortDesc: "If last item used is a Berry, 50% chance to restore it each end of turn. 100% in Sun.",
id: "harvest",
name: "Harvest",
onResidualOrder: 26,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
if (this.isWeather(['sunnyday', 'desolateland']) || this.random(2) === 0) {
if (pokemon.hp && !pokemon.item && this.getItem(pokemon.lastItem).isBerry) {
pokemon.setItem(pokemon.lastItem);
this.add('-item', pokemon, pokemon.getItem(), '[from] ability: Harvest');
}
}
},
rating: 2.5,
num: 139
},
"healer": {
desc: "There is a 30% chance of curing an adjacent ally's major status condition at the end of each turn.",
shortDesc: "30% chance of curing an adjacent ally's status at the end of each turn.",
id: "healer",
name: "Healer",
onResidualOrder: 5,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
var allyActive = pokemon.side.active;
if (allyActive.length === 1) {
return;
}
for (var i = 0; i < allyActive.length; i++) {
if (allyActive[i] && this.isAdjacent(pokemon, allyActive[i]) && allyActive[i].status && this.random(10) < 3) {
allyActive[i].cureStatus();
}
}
},
rating: 0,
num: 131
},
"heatproof": {
desc: "The power of Fire-type attacks against this Pokemon is halved, and any burn damage taken is 1/16 of its maximum HP, rounded down.",
shortDesc: "The power of Fire-type attacks against this Pokemon is halved; burn damage halved.",
onBasePowerPriority: 7,
onSourceBasePower: function (basePower, attacker, defender, move) {
if (move.type === 'Fire') {
return this.chainModify(0.5);
}
},
onDamage: function (damage, target, source, effect) {
if (effect && effect.id === 'brn') {
return damage / 2;
}
},
id: "heatproof",
name: "Heatproof",
rating: 2.5,
num: 85
},
"heavymetal": {
shortDesc: "This Pokemon's weight is doubled.",
onModifyWeight: function (weight) {
return weight * 2;
},
id: "heavymetal",
name: "Heavy Metal",
rating: -1,
num: 134
},
"honeygather": {
shortDesc: "No competitive use.",
id: "honeygather",
name: "Honey Gather",
rating: 0,
num: 118
},
"hugepower": {
shortDesc: "This Pokemon's Attack is doubled.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk) {
return this.chainModify(2);
},
id: "hugepower",
name: "Huge Power",
rating: 5,
num: 37
},
"hustle": {
desc: "This Pokemon's Attack is multiplied by 1.5 and the accuracy of its physical attacks is multiplied by 0.8.",
shortDesc: "This Pokemon's Attack is 1.5x and accuracy of its physical attacks is 0.8x.",
// This should be applied directly to the stat as opposed to chaining witht he others
onModifyAtkPriority: 5,
onModifyAtk: function (atk) {
return this.modify(atk, 1.5);
},
onModifyMove: function (move) {
if (move.category === 'Physical' && typeof move.accuracy === 'number') {
move.accuracy *= 0.8;
}
},
id: "hustle",
name: "Hustle",
rating: 3,
num: 55
},
"hydration": {
desc: "This Pokemon has its major status condition cured at the end of each turn if Rain Dance is active.",
shortDesc: "This Pokemon has its status cured at the end of each turn if Rain Dance is active.",
onResidualOrder: 5,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
if (pokemon.status && this.isWeather(['raindance', 'primordialsea'])) {
this.debug('hydration');
pokemon.cureStatus();
}
},
id: "hydration",
name: "Hydration",
rating: 2,
num: 93
},
"hypercutter": {
shortDesc: "Prevents other Pokemon from lowering this Pokemon's Attack stat stage.",
onBoost: function (boost, target, source, effect) {
if (source && target === source) return;
if (boost['atk'] && boost['atk'] < 0) {
boost['atk'] = 0;
if (!effect.secondaries) this.add("-fail", target, "unboost", "Attack", "[from] ability: Hyper Cutter", "[of] " + target);
}
},
id: "hypercutter",
name: "Hyper Cutter",
rating: 1.5,
num: 52
},
"icebody": {
desc: "If Hail is active, this Pokemon restores 1/16 of its maximum HP, rounded down, at the end of each turn. This Pokemon takes no damage from Hail.",
shortDesc: "If Hail is active, this Pokemon heals 1/16 of its max HP each turn; immunity to Hail.",
onWeather: function (target, source, effect) {
if (effect.id === 'hail') {
this.heal(target.maxhp / 16);
}
},
onImmunity: function (type, pokemon) {
if (type === 'hail') return false;
},
id: "icebody",
name: "Ice Body",
rating: 1.5,
num: 115
},
"illuminate": {
shortDesc: "No competitive use.",
id: "illuminate",
name: "Illuminate",
rating: 0,
num: 35
},
"illusion": {
desc: "When this Pokemon switches in, it appears as the last unfainted Pokemon in its party until it takes direct damage from another Pokemon's attack. This Pokemon's actual level and HP are displayed instead of those of the mimicked Pokemon.",
shortDesc: "This Pokemon appears as the last Pokemon in the party until it takes direct damage.",
onBeforeSwitchIn: function (pokemon) {
pokemon.illusion = null;
var i;
for (i = pokemon.side.pokemon.length - 1; i > pokemon.position; i--) {
if (!pokemon.side.pokemon[i]) continue;
if (!pokemon.side.pokemon[i].fainted) break;
}
if (!pokemon.side.pokemon[i]) return;
if (pokemon === pokemon.side.pokemon[i]) return;
pokemon.illusion = pokemon.side.pokemon[i];
},
// illusion clearing is hardcoded in the damage function
id: "illusion",
name: "Illusion",
rating: 4.5,
num: 149
},
"immunity": {
shortDesc: "This Pokemon cannot be poisoned. Gaining this Ability while poisoned cures it.",
onUpdate: function (pokemon) {
if (pokemon.status === 'psn' || pokemon.status === 'tox') {
pokemon.cureStatus();
}
},
onImmunity: function (type) {
if (type === 'psn') return false;
},
id: "immunity",
name: "Immunity",
rating: 2,
num: 17
},
"imposter": {
desc: "On switch-in, this Pokemon Transforms into the opposing Pokemon that is facing it. If there is no Pokemon at that position, this Pokemon does not Transform.",
shortDesc: "On switch-in, this Pokemon Transforms into the opposing Pokemon that is facing it.",
onStart: function (pokemon) {
var target = pokemon.side.foe.active[pokemon.side.foe.active.length - 1 - pokemon.position];
if (target) {
pokemon.transformInto(target, pokemon);
}
},
id: "imposter",
name: "Imposter",
rating: 4.5,
num: 150
},
"infiltrator": {
desc: "This Pokemon's moves ignore substitutes and the opposing side's Reflect, Light Screen, Safeguard, and Mist.",
shortDesc: "Moves ignore substitutes and opposing Reflect, Light Screen, Safeguard, and Mist.",
onModifyMove: function (move) {
move.infiltrates = true;
},
id: "infiltrator",
name: "Infiltrator",
rating: 3,
num: 151
},
"innerfocus": {
shortDesc: "This Pokemon cannot be made to flinch.",
onFlinch: false,
id: "innerfocus",
name: "Inner Focus",
rating: 1.5,
num: 39
},
"insomnia": {
shortDesc: "This Pokemon cannot fall asleep. Gaining this Ability while asleep cures it.",
onUpdate: function (pokemon) {
if (pokemon.status === 'slp') {
pokemon.cureStatus();
}
},
onImmunity: function (type, pokemon) {
if (type === 'slp') return false;
},
id: "insomnia",
name: "Insomnia",
rating: 2,
num: 15
},
"intimidate": {
desc: "On switch-in, this Pokemon lowers the Attack of adjacent opposing Pokemon by 1 stage. Pokemon behind a substitute are immune.",
shortDesc: "On switch-in, this Pokemon lowers the Attack of adjacent opponents by 1 stage.",
onStart: function (pokemon) {
var foeactive = pokemon.side.foe.active;
for (var i = 0; i < foeactive.length; i++) {
if (!foeactive[i] || !this.isAdjacent(foeactive[i], pokemon)) continue;
if (foeactive[i].volatiles['substitute']) {
// does it give a message?
this.add('-activate', foeactive[i], 'Substitute', 'ability: Intimidate', '[of] ' + pokemon);
} else {
this.add('-ability', pokemon, 'Intimidate', '[of] ' + foeactive[i]);
this.boost({atk: -1}, foeactive[i], pokemon);
}
}
},
id: "intimidate",
name: "Intimidate",
rating: 3.5,
num: 22
},
"ironbarbs": {
desc: "Pokemon making contact with this Pokemon lose 1/8 of their maximum HP, rounded down.",
shortDesc: "Pokemon making contact with this Pokemon lose 1/8 of their max HP.",
onAfterDamageOrder: 1,
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.flags['contact']) {
this.damage(source.maxhp / 8, source, target, null, true);
}
},
id: "ironbarbs",
name: "Iron Barbs",
rating: 3,
num: 160
},
"ironfist": {
desc: "This Pokemon's punch-based attacks have their power multiplied by 1.2.",
shortDesc: "This Pokemon's punch-based attacks have 1.2x power. Sucker Punch is not boosted.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (move.flags['punch']) {
this.debug('Iron Fist boost');
return this.chainModify(1.2);
}
},
id: "ironfist",
name: "Iron Fist",
rating: 3,
num: 89
},
"justified": {
shortDesc: "This Pokemon's Attack is raised by 1 stage after it is damaged by a Dark-type move.",
onAfterDamage: function (damage, target, source, effect) {
if (effect && effect.type === 'Dark') {
this.boost({atk:1});
}
},
id: "justified",
name: "Justified",
rating: 2,
num: 154
},
"keeneye": {
desc: "Prevents other Pokemon from lowering this Pokemon's accuracy stat stage. This Pokemon ignores a target's evasiveness stat stage.",
shortDesc: "This Pokemon's accuracy can't be lowered by others; ignores their evasiveness stat.",
onBoost: function (boost, target, source, effect) {
if (source && target === source) return;
if (boost['accuracy'] && boost['accuracy'] < 0) {
boost['accuracy'] = 0;
if (!effect.secondaries) this.add("-fail", target, "unboost", "accuracy", "[from] ability: Keen Eye", "[of] " + target);
}
},
onModifyMove: function (move) {
move.ignoreEvasion = true;
},
id: "keeneye",
name: "Keen Eye",
rating: 1,
num: 51
},
"klutz": {
desc: "This Pokemon's held item has no effect. This Pokemon cannot use Fling successfully. Macho Brace, Power Anklet, Power Band, Power Belt, Power Bracer, Power Lens, and Power Weight still have their effects.",
shortDesc: "This Pokemon's held item has no effect, except Macho Brace. Fling cannot be used.",
// Item suppression implemented in BattlePokemon.ignoringItem() within battle-engine.js
id: "klutz",
name: "Klutz",
rating: -1,
num: 103
},
"leafguard": {
desc: "If Sunny Day is active, this Pokemon cannot gain a major status condition and Rest will fail for it.",
shortDesc: "If Sunny Day is active, this Pokemon cannot be statused and Rest will fail for it.",
onSetStatus: function (pokemon) {
if (this.isWeather(['sunnyday', 'desolateland'])) {
return false;
}
},
onTryHit: function (target, source, move) {
if (move && move.id === 'yawn' && this.isWeather(['sunnyday', 'desolateland'])) {
return false;
}
},
id: "leafguard",
name: "Leaf Guard",
rating: 1,
num: 102
},
"levitate": {
desc: "This Pokemon is immune to Ground. Gravity, Ingrain, Smack Down, Thousand Arrows, and Iron Ball nullify the immunity.",
shortDesc: "This Pokemon is immune to Ground; Gravity/Ingrain/Smack Down/Iron Ball nullify it.",
onImmunity: function (type) {
if (type === 'Ground') return false;
},
id: "levitate",
name: "Levitate",
rating: 3.5,
num: 26
},
"lightmetal": {
shortDesc: "This Pokemon's weight is halved.",
onModifyWeight: function (weight) {
return weight / 2;
},
id: "lightmetal",
name: "Light Metal",
rating: 1,
num: 135
},
"lightningrod": {
desc: "This Pokemon is immune to Electric-type moves and raises its Special Attack by 1 stage when hit by an Electric-type move. If this Pokemon is not the target of a single-target Electric-type move used by another Pokemon, this Pokemon redirects that move to itself if it is within the range of that move.",
shortDesc: "This Pokemon draws Electric moves to itself to raise Sp. Atk by 1; Electric immunity.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Electric') {
if (!this.boost({spa:1})) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
onAnyRedirectTargetPriority: 1,
onAnyRedirectTarget: function (target, source, source2, move) {
if (move.type !== 'Electric' || move.id in {firepledge:1, grasspledge:1, waterpledge:1}) return;
if (this.validTarget(this.effectData.target, source, move.target)) {
return this.effectData.target;
}
},
id: "lightningrod",
name: "Lightning Rod",
rating: 3.5,
num: 32
},
"limber": {
shortDesc: "This Pokemon cannot be paralyzed. Gaining this Ability while paralyzed cures it.",
onUpdate: function (pokemon) {
if (pokemon.status === 'par') {
pokemon.cureStatus();
}
},
onImmunity: function (type, pokemon) {
if (type === 'par') return false;
},
id: "limber",
name: "Limber",
rating: 1.5,
num: 7
},
"liquidooze": {
shortDesc: "This Pokemon damages those draining HP from it for as much as they would heal.",
id: "liquidooze",
onSourceTryHeal: function (damage, target, source, effect) {
this.debug("Heal is occurring: " + target + " <- " + source + " :: " + effect.id);
var canOoze = {drain: 1, leechseed: 1};
if (canOoze[effect.id]) {
this.damage(damage, null, null, null, true);
return 0;
}
},
name: "Liquid Ooze",
rating: 1.5,
num: 64
},
"magicbounce": {
desc: "This Pokemon blocks certain status moves and instead uses the move against the original user.",
shortDesc: "This Pokemon blocks certain status moves and bounces them back to the user.",
id: "magicbounce",
name: "Magic Bounce",
onTryHitPriority: 1,
onTryHit: function (target, source, move) {
if (target === source || move.hasBounced || !move.flags['reflectable']) {
return;
}
var newMove = this.getMoveCopy(move.id);
newMove.hasBounced = true;
this.useMove(newMove, target, source);
return null;
},
onAllyTryHitSide: function (target, source, move) {
if (target.side === source.side || move.hasBounced || !move.flags['reflectable']) {
return;
}
var newMove = this.getMoveCopy(move.id);
newMove.hasBounced = true;
this.useMove(newMove, target, source);
return null;
},
effect: {
duration: 1
},
rating: 4.5,
num: 156
},
"magicguard": {
desc: "This Pokemon can only be damaged by direct attacks. Curse and Substitute on use, Belly Drum, Pain Split, Struggle recoil, and confusion damage are considered direct damage.",
shortDesc: "This Pokemon can only be damaged by direct attacks.",
onDamage: function (damage, target, source, effect) {
if (effect.effectType !== 'Move') {
return false;
}
},
id: "magicguard",
name: "Magic Guard",
rating: 4.5,
num: 98
},
"magician": {
desc: "If this Pokemon has no item, it steals the item off a Pokemon it hits with an attack. Does not affect Doom Desire and Future Sight.",
shortDesc: "If this Pokemon has no item, it steals the item off a Pokemon it hits with an attack.",
onSourceHit: function (target, source, move) {
if (!move || !target) return;
if (target !== source && move.category !== 'Status') {
if (source.item) return;
var yourItem = target.takeItem(source);
if (!yourItem) return;
if (!source.setItem(yourItem)) {
target.item = yourItem.id; // bypass setItem so we don't break choicelock or anything
return;
}
this.add('-item', source, yourItem, '[from] ability: Magician', '[of] ' + target);
}
},
id: "magician",
name: "Magician",
rating: 1.5,
num: 170
},
"magmaarmor": {
shortDesc: "This Pokemon cannot be frozen. Gaining this Ability while frozen cures it.",
onUpdate: function (pokemon) {
if (pokemon.status === 'frz') {
pokemon.cureStatus();
}
},
onImmunity: function (type, pokemon) {
if (type === 'frz') return false;
},
id: "magmaarmor",
name: "Magma Armor",
rating: 0.5,
num: 40
},
"magnetpull": {
desc: "Prevents adjacent opposing Steel-type Pokemon from choosing to switch out unless they are immune to trapping.",
shortDesc: "Prevents adjacent Steel-type foes from choosing to switch.",
onFoeModifyPokemon: function (pokemon) {
if (pokemon.hasType('Steel') && this.isAdjacent(pokemon, this.effectData.target)) {
pokemon.tryTrap(true);
}
},
onFoeMaybeTrapPokemon: function (pokemon, source) {
if (!source) source = this.effectData.target;
if (pokemon.hasType('Steel') && this.isAdjacent(pokemon, source)) {
pokemon.maybeTrapped = true;
}
},
id: "magnetpull",
name: "Magnet Pull",
rating: 4.5,
num: 42
},
"marvelscale": {
desc: "If this Pokemon has a major status condition, its Defense is multiplied by 1.5.",
shortDesc: "If this Pokemon is statused, its Defense is 1.5x.",
onModifyDefPriority: 6,
onModifyDef: function (def, pokemon) {
if (pokemon.status) {
return this.chainModify(1.5);
}
},
id: "marvelscale",
name: "Marvel Scale",
rating: 2.5,
num: 63
},
"megalauncher": {
desc: "This Pokemon's pulse moves have their power multiplied by 1.5. Heal Pulse restores 3/4 of a target's maximum HP, rounded half down.",
shortDesc: "This Pokemon's pulse moves have 1.5x power. Heal Pulse heals 3/4 target's max HP.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (move.flags['pulse']) {
return this.chainModify(1.5);
}
},
id: "megalauncher",
name: "Mega Launcher",
rating: 3.5,
num: 178
},
"minus": {
desc: "If an active ally has this Ability or the Ability Plus, this Pokemon's Special Attack is multiplied by 1.5.",
shortDesc: "If an active ally has this Ability or the Ability Plus, this Pokemon's Sp. Atk is 1.5x.",
onModifySpAPriority: 5,
onModifySpA: function (spa, pokemon) {
var allyActive = pokemon.side.active;
if (allyActive.length === 1) {
return;
}
for (var i = 0; i < allyActive.length; i++) {
if (allyActive[i] && allyActive[i].position !== pokemon.position && !allyActive[i].fainted && allyActive[i].hasAbility(['minus', 'plus'])) {
return this.chainModify(1.5);
}
}
},
id: "minus",
name: "Minus",
rating: 0,
num: 58
},
"moldbreaker": {
shortDesc: "This Pokemon's moves and their effects ignore the Abilities of other Pokemon.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Mold Breaker');
},
stopAttackEvents: true,
id: "moldbreaker",
name: "Mold Breaker",
rating: 3.5,
num: 104
},
"moody": {
desc: "This Pokemon has a random stat raised by 2 stages and another stat lowered by 1 stage at the end of each turn.",
shortDesc: "Raises a random stat by 2 and lowers another stat by 1 at the end of each turn.",
onResidualOrder: 26,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
var stats = [], i = '';
var boost = {};
for (var i in pokemon.boosts) {
if (pokemon.boosts[i] < 6) {
stats.push(i);
}
}
if (stats.length) {
i = stats[this.random(stats.length)];
boost[i] = 2;
}
stats = [];
for (var j in pokemon.boosts) {
if (pokemon.boosts[j] > -6 && j !== i) {
stats.push(j);
}
}
if (stats.length) {
i = stats[this.random(stats.length)];
boost[i] = -1;
}
this.boost(boost);
},
id: "moody",
name: "Moody",
rating: 5,
num: 141
},
"motordrive": {
desc: "This Pokemon is immune to Electric-type moves and raises its Speed by 1 stage when hit by an Electric-type move.",
shortDesc: "This Pokemon's Speed is raised 1 stage if hit by an Electric move; Electric immunity.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Electric') {
if (!this.boost({spe:1})) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
id: "motordrive",
name: "Motor Drive",
rating: 3,
num: 78
},
"moxie": {
desc: "This Pokemon's Attack is raised by 1 stage if it attacks and knocks out another Pokemon.",
shortDesc: "This Pokemon's Attack is raised by 1 stage if it attacks and KOes another Pokemon.",
onSourceFaint: function (target, source, effect) {
if (effect && effect.effectType === 'Move') {
this.boost({atk:1}, source);
}
},
id: "moxie",
name: "Moxie",
rating: 3.5,
num: 153
},
"multiscale": {
shortDesc: "If this Pokemon is at full HP, damage taken from attacks is halved.",
onSourceModifyDamage: function (damage, source, target, move) {
if (target.hp >= target.maxhp) {
this.debug('Multiscale weaken');
return this.chainModify(0.5);
}
},
id: "multiscale",
name: "Multiscale",
rating: 4,
num: 136
},
"multitype": {
shortDesc: "If this Pokemon is an Arceus, its type changes to match its held Plate.",
// Multitype's type-changing itself is implemented in statuses.js
id: "multitype",
name: "Multitype",
rating: 4,
num: 121
},
"mummy": {
desc: "Pokemon making contact with this Pokemon have their Ability changed to Mummy. Does not affect the Abilities Multitype or Stance Change.",
shortDesc: "Pokemon making contact with this Pokemon have their Ability changed to Mummy.",
id: "mummy",
name: "Mummy",
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.flags['contact']) {
var oldAbility = source.setAbility('mummy', source, 'mummy', true);
if (oldAbility) {
this.add('-endability', source, oldAbility, '[from] Mummy');
this.add('-ability', source, 'Mummy', '[from] Mummy');
}
}
},
rating: 2,
num: 152
},
"naturalcure": {
shortDesc: "This Pokemon has its major status condition cured when it switches out.",
onSwitchOut: function (pokemon) {
pokemon.setStatus('');
},
id: "naturalcure",
name: "Natural Cure",
rating: 3.5,
num: 30
},
"noguard": {
shortDesc: "Every move used by or against this Pokemon will always hit.",
onAnyAccuracy: function (accuracy, target, source, move) {
if (move && (source === this.effectData.target || target === this.effectData.target)) {
return true;
}
return accuracy;
},
id: "noguard",
name: "No Guard",
rating: 4,
num: 99
},
"normalize": {
desc: "This Pokemon's moves are changed to be Normal type. This effect comes before other effects that change a move's type.",
shortDesc: "This Pokemon's moves are changed to be Normal type.",
onModifyMovePriority: 1,
onModifyMove: function (move) {
if (move.id !== 'struggle') {
move.type = 'Normal';
}
},
id: "normalize",
name: "Normalize",
rating: -1,
num: 96
},
"oblivious": {
desc: "This Pokemon cannot be infatuated or taunted. Gaining this Ability while affected cures it.",
shortDesc: "This Pokemon cannot be infatuated or taunted. Gaining this Ability cures it.",
onUpdate: function (pokemon) {
if (pokemon.volatiles['attract']) {
pokemon.removeVolatile('attract');
this.add('-end', pokemon, 'move: Attract', '[from] ability: Oblivious');
}
if (pokemon.volatiles['taunt']) {
pokemon.removeVolatile('taunt');
// Taunt's volatile already sends the -end message when removed
}
},
onImmunity: function (type, pokemon) {
if (type === 'attract') {
this.add('-immune', pokemon, '[from] Oblivious');
return false;
}
},
onTryHit: function (pokemon, target, move) {
if (move.id === 'captivate' || move.id === 'taunt') {
this.add('-immune', pokemon, '[msg]', '[from] Oblivious');
return null;
}
},
id: "oblivious",
name: "Oblivious",
rating: 1,
num: 12
},
"overcoat": {
shortDesc: "This Pokemon is immune to powder moves and damage from Sandstorm or Hail.",
onImmunity: function (type, pokemon) {
if (type === 'sandstorm' || type === 'hail' || type === 'powder') return false;
},
id: "overcoat",
name: "Overcoat",
rating: 2.5,
num: 142
},
"overgrow": {
desc: "When this Pokemon has 1/3 or less of its maximum HP, its attacking stat is multiplied by 1.5 while using a Grass-type attack.",
shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Grass attacks do 1.5x damage.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk, attacker, defender, move) {
if (move.type === 'Grass' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Overgrow boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function (atk, attacker, defender, move) {
if (move.type === 'Grass' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Overgrow boost');
return this.chainModify(1.5);
}
},
id: "overgrow",
name: "Overgrow",
rating: 2,
num: 65
},
"owntempo": {
shortDesc: "This Pokemon cannot be confused. Gaining this Ability while confused cures it.",
onUpdate: function (pokemon) {
if (pokemon.volatiles['confusion']) {
pokemon.removeVolatile('confusion');
}
},
onImmunity: function (type, pokemon) {
if (type === 'confusion') {
this.add('-immune', pokemon, 'confusion');
return false;
}
},
id: "owntempo",
name: "Own Tempo",
rating: 1,
num: 20
},
"parentalbond": {
desc: "This Pokemon's damaging moves become multi-hit moves that hit twice. The second hit has its damage halved. Does not affect multi-hit moves or moves that have multiple targets.",
shortDesc: "This Pokemon's damaging moves hit twice. The second hit has its damage halved.",
onModifyMove: function (move, pokemon, target) {
if (move.category !== 'Status' && !move.selfdestruct && !move.multihit && ((target.side && target.side.active.length < 2) || move.target in {any:1, normal:1, randomNormal:1})) {
move.multihit = 2;
pokemon.addVolatile('parentalbond');
}
},
effect: {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower) {
if (this.effectData.hit) {
return this.chainModify(0.5);
} else {
this.effectData.hit = true;
}
}
},
id: "parentalbond",
name: "Parental Bond",
rating: 5,
num: 184
},
"pickup": {
shortDesc: "If this Pokemon has no item, it finds one used by an adjacent Pokemon this turn.",
onResidualOrder: 26,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
if (pokemon.item) return;
var pickupTargets = [];
var target;
for (var i = 0; i < pokemon.side.active.length; i++) {
target = pokemon.side.active[i];
if (target.lastItem && target.usedItemThisTurn && this.isAdjacent(pokemon, target)) {
pickupTargets.push(target);
}
}
for (var i = 0; i < pokemon.side.foe.active.length; i++) {
target = pokemon.side.foe.active[i];
if (target.lastItem && target.usedItemThisTurn && this.isAdjacent(pokemon, target)) {
pickupTargets.push(target);
}
}
if (!pickupTargets.length) return;
target = pickupTargets[this.random(pickupTargets.length)];
pokemon.setItem(target.lastItem);
target.lastItem = '';
var item = pokemon.getItem();
this.add('-item', pokemon, item, '[from] Pickup');
if (item.isBerry) pokemon.update();
},
id: "pickup",
name: "Pickup",
rating: 0.5,
num: 53
},
"pickpocket": {
desc: "If this Pokemon has no item, it steals the item off a Pokemon that makes contact with it. This effect applies after all hits from a multi-hit move; Sheer Force prevents it from activating if the move has a secondary effect.",
shortDesc: "If this Pokemon has no item, it steals the item off a Pokemon making contact with it.",
onAfterMoveSecondary: function (target, source, move) {
if (source && source !== target && move && move.flags['contact']) {
if (target.item) {
return;
}
var yourItem = source.takeItem(target);
if (!yourItem) {
return;
}
if (!target.setItem(yourItem)) {
source.item = yourItem.id;
return;
}
this.add('-item', target, yourItem, '[from] ability: Pickpocket', '[of] ' + source);
}
},
id: "pickpocket",
name: "Pickpocket",
rating: 1,
num: 124
},
"pixilate": {
desc: "This Pokemon's Normal-type moves become Fairy-type moves and have their power multiplied by 1.3. This effect comes after other effects that change a move's type, but before Ion Deluge and Electrify's effects.",
shortDesc: "This Pokemon's Normal-type moves become Fairy type and have 1.3x power.",
onModifyMovePriority: -1,
onModifyMove: function (move, pokemon) {
if (move.type === 'Normal' && move.id !== 'naturalgift') {
move.type = 'Fairy';
if (move.category !== 'Status') pokemon.addVolatile('pixilate');
}
},
effect: {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower, pokemon, target, move) {
return this.chainModify([0x14CD, 0x1000]);
}
},
id: "pixilate",
name: "Pixilate",
rating: 4,
num: 182
},
"plus": {
desc: "If an active ally has this Ability or the Ability Minus, this Pokemon's Special Attack is multiplied by 1.5.",
shortDesc: "If an active ally has this Ability or the Ability Minus, this Pokemon's Sp. Atk is 1.5x.",
onModifySpAPriority: 5,
onModifySpA: function (spa, pokemon) {
var allyActive = pokemon.side.active;
if (allyActive.length === 1) {
return;
}
for (var i = 0; i < allyActive.length; i++) {
if (allyActive[i] && allyActive[i].position !== pokemon.position && !allyActive[i].fainted && allyActive[i].hasAbility(['minus', 'plus'])) {
return this.chainModify(1.5);
}
}
},
id: "plus",
name: "Plus",
rating: 0,
num: 57
},
"poisonheal": {
desc: "If this Pokemon is poisoned, it restores 1/8 of its maximum HP, rounded down, at the end of each turn instead of losing HP.",
shortDesc: "This Pokemon is healed by 1/8 of its max HP each turn when poisoned; no HP loss.",
onDamage: function (damage, target, source, effect) {
if (effect.id === 'psn' || effect.id === 'tox') {
this.heal(target.maxhp / 8);
return false;
}
},
id: "poisonheal",
name: "Poison Heal",
rating: 4,
num: 90
},
"poisonpoint": {
shortDesc: "30% chance a Pokemon making contact with this Pokemon will be poisoned.",
onAfterDamage: function (damage, target, source, move) {
if (move && move.flags['contact']) {
if (this.random(10) < 3) {
source.trySetStatus('psn', target, move);
}
}
},
id: "poisonpoint",
name: "Poison Point",
rating: 2,
num: 38
},
"poisontouch": {
shortDesc: "This Pokemon's contact moves have a 30% chance of poisoning.",
// upokecenter says this is implemented as an added secondary effect
onModifyMove: function (move) {
if (!move || !move.flags['contact']) return;
if (!move.secondaries) {
move.secondaries = [];
}
move.secondaries.push({
chance: 30,
status: 'psn'
});
},
id: "poisontouch",
name: "Poison Touch",
rating: 2,
num: 143
},
"prankster": {
shortDesc: "This Pokemon's non-damaging moves have their priority increased by 1.",
onModifyPriority: function (priority, pokemon, target, move) {
if (move && move.category === 'Status') {
return priority + 1;
}
},
id: "prankster",
name: "Prankster",
rating: 4.5,
num: 158
},
"pressure": {
desc: "If this Pokemon is the target of an opposing Pokemon's move, that move loses one additional PP.",
shortDesc: "If this Pokemon is the target of a foe's move, that move loses one additional PP.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Pressure');
},
onDeductPP: function (target, source) {
if (target.side === source.side) return;
return 1;
},
id: "pressure",
name: "Pressure",
rating: 1.5,
num: 46
},
"primordialsea": {
desc: "On switch-in, the weather becomes heavy rain that prevents damaging Fire-type moves from executing, in addition to all the effects of Rain Dance. This weather remains in effect until this Ability is no longer active for any Pokemon, or the weather is changed by Delta Stream or Desolate Land.",
shortDesc: "On switch-in, heavy rain begins until this Ability is not active in battle.",
onStart: function (source) {
this.setWeather('primordialsea');
},
onAnySetWeather: function (target, source, weather) {
if (this.getWeather().id === 'primordialsea' && !(weather.id in {desolateland:1, primordialsea:1, deltastream:1})) return false;
},
onEnd: function (pokemon) {
if (this.weatherData.source !== pokemon) return;
for (var i = 0; i < this.sides.length; i++) {
for (var j = 0; j < this.sides[i].active.length; j++) {
var target = this.sides[i].active[j];
if (target === pokemon) continue;
if (target && target.hp && target.hasAbility('primordialsea')) {
this.weatherData.source = target;
return;
}
}
}
this.clearWeather();
},
id: "primordialsea",
name: "Primordial Sea",
rating: 5,
num: 189
},
"protean": {
desc: "This Pokemon's type changes to match the type of the move it is about to use. This effect comes after all effects that change a move's type.",
shortDesc: "This Pokemon's type changes to match the type of the move it is about to use.",
onPrepareHit: function (source, target, move) {
var type = move.type;
if (type && type !== '???' && source.getTypes().join() !== type) {
if (!source.setType(type)) return;
this.add('-start', source, 'typechange', type, '[from] Protean');
}
},
id: "protean",
name: "Protean",
rating: 4,
num: 168
},
"purepower": {
shortDesc: "This Pokemon's Attack is doubled.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk) {
return this.chainModify(2);
},
id: "purepower",
name: "Pure Power",
rating: 5,
num: 74
},
"quickfeet": {
desc: "If this Pokemon has a major status condition, its Speed is multiplied by 1.5; the Speed drop from paralysis is ignored.",
shortDesc: "If this Pokemon is statused, its Speed is 1.5x; ignores Speed drop from paralysis.",
onModifySpe: function (speMod, pokemon) {
if (pokemon.status) {
return this.chain(speMod, 1.5);
}
},
id: "quickfeet",
name: "Quick Feet",
rating: 2.5,
num: 95
},
"raindish": {
desc: "If Rain Dance is active, this Pokemon restores 1/16 of its maximum HP, rounded down, at the end of each turn.",
shortDesc: "If Rain Dance is active, this Pokemon heals 1/16 of its max HP each turn.",
onWeather: function (target, source, effect) {
if (effect.id === 'raindance' || effect.id === 'primordialsea') {
this.heal(target.maxhp / 16);
}
},
id: "raindish",
name: "Rain Dish",
rating: 1.5,
num: 44
},
"rattled": {
desc: "This Pokemon's Speed is raised by 1 stage if hit by a Bug-, Dark-, or Ghost-type attack.",
shortDesc: "This Pokemon's Speed is raised 1 stage if hit by a Bug-, Dark-, or Ghost-type attack.",
onAfterDamage: function (damage, target, source, effect) {
if (effect && (effect.type === 'Dark' || effect.type === 'Bug' || effect.type === 'Ghost')) {
this.boost({spe:1});
}
},
id: "rattled",
name: "Rattled",
rating: 1.5,
num: 155
},
"reckless": {
desc: "This Pokemon's attacks with recoil or crash damage have their power multiplied by 1.2. Does not affect Struggle.",
shortDesc: "This Pokemon's attacks with recoil or crash damage have 1.2x power; not Struggle.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (move.recoil || move.hasCustomRecoil) {
this.debug('Reckless boost');
return this.chainModify(1.2);
}
},
id: "reckless",
name: "Reckless",
rating: 3,
num: 120
},
"refrigerate": {
desc: "This Pokemon's Normal-type moves become Ice-type moves and have their power multiplied by 1.3. This effect comes after other effects that change a move's type, but before Ion Deluge and Electrify's effects.",
shortDesc: "This Pokemon's Normal-type moves become Ice type and have 1.3x power.",
onModifyMovePriority: -1,
onModifyMove: function (move, pokemon) {
if (move.type === 'Normal' && move.id !== 'naturalgift') {
move.type = 'Ice';
if (move.category !== 'Status') pokemon.addVolatile('refrigerate');
}
},
effect: {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower, pokemon, target, move) {
return this.chainModify([0x14CD, 0x1000]);
}
},
id: "refrigerate",
name: "Refrigerate",
rating: 4,
num: 174
},
"regenerator": {
shortDesc: "This Pokemon restores 1/3 of its maximum HP, rounded down, when it switches out.",
onSwitchOut: function (pokemon) {
pokemon.heal(pokemon.maxhp / 3);
},
id: "regenerator",
name: "Regenerator",
rating: 4,
num: 144
},
"rivalry": {
desc: "This Pokemon's attacks have their power multiplied by 1.25 against targets of the same gender or multiplied by 0.75 against targets of the opposite gender. There is no modifier if either this Pokemon or the target is genderless.",
shortDesc: "This Pokemon's attacks do 1.25x on same gender targets; 0.75x on opposite gender.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (attacker.gender && defender.gender) {
if (attacker.gender === defender.gender) {
this.debug('Rivalry boost');
return this.chainModify(1.25);
} else {
this.debug('Rivalry weaken');
return this.chainModify(0.75);
}
}
},
id: "rivalry",
name: "Rivalry",
rating: 0.5,
num: 79
},
"rockhead": {
desc: "This Pokemon does not take recoil damage besides Struggle, Life Orb, and crash damage.",
shortDesc: "This Pokemon does not take recoil damage besides Struggle/Life Orb/crash damage.",
onDamage: function (damage, target, source, effect) {
if (effect.id === 'recoil' && this.activeMove.id !== 'struggle') return null;
},
id: "rockhead",
name: "Rock Head",
rating: 3,
num: 69
},
"roughskin": {
desc: "Pokemon making contact with this Pokemon lose 1/8 of their maximum HP, rounded down.",
shortDesc: "Pokemon making contact with this Pokemon lose 1/8 of their max HP.",
onAfterDamageOrder: 1,
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.flags['contact']) {
this.damage(source.maxhp / 8, source, target, null, true);
}
},
id: "roughskin",
name: "Rough Skin",
rating: 3,
num: 24
},
"runaway": {
shortDesc: "No competitive use.",
id: "runaway",
name: "Run Away",
rating: 0,
num: 50
},
"sandforce": {
desc: "If Sandstorm is active, this Pokemon's Ground-, Rock-, and Steel-type attacks have their power multiplied by 1.3. This Pokemon takes no damage from Sandstorm.",
shortDesc: "This Pokemon's Ground/Rock/Steel attacks do 1.3x in Sandstorm; immunity to it.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (this.isWeather('sandstorm')) {
if (move.type === 'Rock' || move.type === 'Ground' || move.type === 'Steel') {
this.debug('Sand Force boost');
return this.chainModify([0x14CD, 0x1000]); // The Sand Force modifier is slightly higher than the normal 1.3 (0x14CC)
}
}
},
onImmunity: function (type, pokemon) {
if (type === 'sandstorm') return false;
},
id: "sandforce",
name: "Sand Force",
rating: 2,
num: 159
},
"sandrush": {
desc: "If Sandstorm is active, this Pokemon's Speed is doubled. This Pokemon takes no damage from Sandstorm.",
shortDesc: "If Sandstorm is active, this Pokemon's Speed is doubled; immunity to Sandstorm.",
onModifySpe: function (speMod, pokemon) {
if (this.isWeather('sandstorm')) {
return this.chain(speMod, 2);
}
},
onImmunity: function (type, pokemon) {
if (type === 'sandstorm') return false;
},
id: "sandrush",
name: "Sand Rush",
rating: 2.5,
num: 146
},
"sandstream": {
shortDesc: "On switch-in, this Pokemon summons Sandstorm.",
onStart: function (source) {
this.setWeather('sandstorm');
},
id: "sandstream",
name: "Sand Stream",
rating: 4,
num: 45
},
"sandveil": {
desc: "If Sandstorm is active, this Pokemon's evasiveness is multiplied by 1.25. This Pokemon takes no damage from Sandstorm.",
shortDesc: "If Sandstorm is active, this Pokemon's evasiveness is 1.25x; immunity to Sandstorm.",
onImmunity: function (type, pokemon) {
if (type === 'sandstorm') return false;
},
onModifyAccuracy: function (accuracy) {
if (typeof accuracy !== 'number') return;
if (this.isWeather('sandstorm')) {
this.debug('Sand Veil - decreasing accuracy');
return accuracy * 0.8;
}
},
id: "sandveil",
name: "Sand Veil",
rating: 1.5,
num: 8
},
"sapsipper": {
desc: "This Pokemon is immune to Grass-type moves and raises its Attack by 1 stage when hit by a Grass-type move.",
shortDesc: "This Pokemon's Attack is raised 1 stage if hit by a Grass move; Grass immunity.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Grass') {
if (!this.boost({atk:1})) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
onAllyTryHitSide: function (target, source, move) {
if (target === this.effectData.target || target.side !== source.side) return;
if (move.type === 'Grass') {
this.boost({atk:1}, this.effectData.target);
}
},
id: "sapsipper",
name: "Sap Sipper",
rating: 3.5,
num: 157
},
"scrappy": {
shortDesc: "This Pokemon can hit Ghost types with Normal- and Fighting-type moves.",
onModifyMovePriority: -5,
onModifyMove: function (move) {
if (!move.ignoreImmunity) move.ignoreImmunity = {};
if (move.ignoreImmunity !== true) {
move.ignoreImmunity['Fighting'] = true;
move.ignoreImmunity['Normal'] = true;
}
},
id: "scrappy",
name: "Scrappy",
rating: 3,
num: 113
},
"serenegrace": {
shortDesc: "This Pokemon's moves have their secondary effect chance doubled.",
onModifyMove: function (move) {
if (move.secondaries && move.id !== 'secretpower') {
this.debug('doubling secondary chance');
for (var i = 0; i < move.secondaries.length; i++) {
move.secondaries[i].chance *= 2;
}
}
},
id: "serenegrace",
name: "Serene Grace",
rating: 4,
num: 32
},
"shadowtag": {
desc: "Prevents adjacent opposing Pokemon from choosing to switch out unless they are immune to trapping or also have this Ability.",
shortDesc: "Prevents adjacent foes from choosing to switch unless they also have this Ability.",
onFoeModifyPokemon: function (pokemon) {
if (!pokemon.hasAbility('shadowtag') && this.isAdjacent(pokemon, this.effectData.target)) {
pokemon.tryTrap(true);
}
},
onFoeMaybeTrapPokemon: function (pokemon, source) {
if (!source) source = this.effectData.target;
if (!pokemon.hasAbility('shadowtag') && this.isAdjacent(pokemon, source)) {
pokemon.maybeTrapped = true;
}
},
id: "shadowtag",
name: "Shadow Tag",
rating: 5,
num: 23
},
"shedskin": {
desc: "This Pokemon has a 33% chance to have its major status condition cured at the end of each turn.",
shortDesc: "This Pokemon has a 33% chance to have its status cured at the end of each turn.",
onResidualOrder: 5,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
if (pokemon.hp && pokemon.status && this.random(3) === 0) {
this.debug('shed skin');
this.add('-activate', pokemon, 'ability: Shed Skin');
pokemon.cureStatus();
}
},
id: "shedskin",
name: "Shed Skin",
rating: 3.5,
num: 61
},
"sheerforce": {
desc: "This Pokemon's attacks with secondary effects have their power multiplied by 1.3, but the secondary effects are removed.",
shortDesc: "This Pokemon's attacks with secondary effects have 1.3x power; nullifies the effects.",
onModifyMove: function (move, pokemon) {
if (move.secondaries) {
delete move.secondaries;
// Actual negation of `AfterMoveSecondary` effects implemented in scripts.js
pokemon.addVolatile('sheerforce');
}
},
effect: {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower, pokemon, target, move) {
return this.chainModify([0x14CD, 0x1000]); // The Sheer Force modifier is slightly higher than the normal 1.3 (0x14CC)
}
},
id: "sheerforce",
name: "Sheer Force",
rating: 4,
num: 125
},
"shellarmor": {
shortDesc: "This Pokemon cannot be struck by a critical hit.",
onCriticalHit: false,
id: "shellarmor",
name: "Shell Armor",
rating: 1,
num: 75
},
"shielddust": {
shortDesc: "This Pokemon is not affected by the secondary effect of another Pokemon's attack.",
onTrySecondaryHit: function () {
this.debug('Shield Dust prevent secondary');
return null;
},
id: "shielddust",
name: "Shield Dust",
rating: 2.5,
num: 19
},
"simple": {
shortDesc: "If this Pokemon's stat stages are raised or lowered, the effect is doubled instead.",
onBoost: function (boost) {
for (var i in boost) {
boost[i] *= 2;
}
},
id: "simple",
name: "Simple",
rating: 4,
num: 86
},
"skilllink": {
shortDesc: "This Pokemon's multi-hit attacks always hit the maximum number of times.",
onModifyMove: function (move) {
if (move.multihit && move.multihit.length) {
move.multihit = move.multihit[1];
}
},
id: "skilllink",
name: "Skill Link",
rating: 4,
num: 92
},
"slowstart": {
shortDesc: "On switch-in, this Pokemon's Attack and Speed are halved for 5 turns.",
onStart: function (pokemon) {
pokemon.addVolatile('slowstart');
},
onEnd: function (pokemon) {
delete pokemon.volatiles['slowstart'];
this.add('-end', pokemon, 'Slow Start', '[silent]');
},
effect: {
duration: 5,
onStart: function (target) {
this.add('-start', target, 'Slow Start');
},
onModifyAtkPriority: 5,
onModifyAtk: function (atk, pokemon) {
return this.chainModify(0.5);
},
onModifySpe: function (speMod, pokemon) {
return this.chain(speMod, 0.5);
},
onEnd: function (target) {
this.add('-end', target, 'Slow Start');
}
},
id: "slowstart",
name: "Slow Start",
rating: -2,
num: 112
},
"sniper": {
shortDesc: "If this Pokemon strikes with a critical hit, the damage is multiplied by 1.5.",
onModifyDamage: function (damage, source, target, move) {
if (move.crit) {
this.debug('Sniper boost');
return this.chainModify(1.5);
}
},
id: "sniper",
name: "Sniper",
rating: 1,
num: 97
},
"snowcloak": {
desc: "If Hail is active, this Pokemon's evasiveness is multiplied by 1.25. This Pokemon takes no damage from Hail.",
shortDesc: "If Hail is active, this Pokemon's evasiveness is 1.25x; immunity to Hail.",
onImmunity: function (type, pokemon) {
if (type === 'hail') return false;
},
onModifyAccuracy: function (accuracy) {
if (typeof accuracy !== 'number') return;
if (this.isWeather('hail')) {
this.debug('Snow Cloak - decreasing accuracy');
return accuracy * 0.8;
}
},
id: "snowcloak",
name: "Snow Cloak",
rating: 1.5,
num: 81
},
"snowwarning": {
shortDesc: "On switch-in, this Pokemon summons Hail.",
onStart: function (source) {
this.setWeather('hail');
},
id: "snowwarning",
name: "Snow Warning",
rating: 3.5,
num: 117
},
"solarpower": {
desc: "If Sunny Day is active, this Pokemon's Special Attack is multiplied by 1.5 and it loses 1/8 of its maximum HP, rounded down, at the end of each turn.",
shortDesc: "If Sunny Day is active, this Pokemon's Sp. Atk is 1.5x; loses 1/8 max HP per turn.",
onModifySpAPriority: 5,
onModifySpA: function (spa, pokemon) {
if (this.isWeather(['sunnyday', 'desolateland'])) {
return this.chainModify(1.5);
}
},
onWeather: function (target, source, effect) {
if (effect.id === 'sunnyday' || effect.id === 'desolateland') {
this.damage(target.maxhp / 8);
}
},
id: "solarpower",
name: "Solar Power",
rating: 1.5,
num: 94
},
"solidrock": {
shortDesc: "This Pokemon receives 3/4 damage from supereffective attacks.",
onSourceModifyDamage: function (damage, source, target, move) {
if (move.typeMod > 0) {
this.debug('Solid Rock neutralize');
return this.chainModify(0.75);
}
},
id: "solidrock",
name: "Solid Rock",
rating: 3,
num: 116
},
"soundproof": {
shortDesc: "This Pokemon is immune to sound-based moves, including Heal Bell.",
onTryHit: function (target, source, move) {
if (target !== source && move.flags['sound']) {
this.add('-immune', target, '[msg]');
return null;
}
},
id: "soundproof",
name: "Soundproof",
rating: 2,
num: 43
},
"speedboost": {
desc: "This Pokemon's Speed is raised by 1 stage at the end of each full turn it has been on the field.",
shortDesc: "This Pokemon's Speed is raised 1 stage at the end of each full turn on the field.",
onResidualOrder: 26,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
if (pokemon.activeTurns) {
this.boost({spe:1});
}
},
id: "speedboost",
name: "Speed Boost",
rating: 4.5,
num: 3
},
"stall": {
shortDesc: "This Pokemon moves last among Pokemon using the same or greater priority moves.",
onModifyPriority: function (priority) {
return priority - 0.1;
},
id: "stall",
name: "Stall",
rating: -1,
num: 100
},
"stancechange": {
desc: "If this Pokemon is an Aegislash, it changes to Blade Forme before attempting to use an attacking move, and changes to Shield Forme before attempting to use King's Shield.",
shortDesc: "If Aegislash, changes Forme to Blade before attacks and Shield before King's Shield.",
onBeforeMovePriority: 11,
onBeforeMove: function (attacker, defender, move) {
if (attacker.template.baseSpecies !== 'Aegislash') return;
if (move.category === 'Status' && move.id !== 'kingsshield') return;
var targetSpecies = (move.id === 'kingsshield' ? 'Aegislash' : 'Aegislash-Blade');
if (attacker.template.species !== targetSpecies && attacker.formeChange(targetSpecies)) {
this.add('-formechange', attacker, targetSpecies);
}
},
id: "stancechange",
name: "Stance Change",
rating: 5,
num: 176
},
"static": {
shortDesc: "30% chance a Pokemon making contact with this Pokemon will be paralyzed.",
onAfterDamage: function (damage, target, source, effect) {
if (effect && effect.flags['contact']) {
if (this.random(10) < 3) {
source.trySetStatus('par', target, effect);
}
}
},
id: "static",
name: "Static",
rating: 2,
num: 9
},
"steadfast": {
shortDesc: "If this Pokemon flinches, its Speed is raised by 1 stage.",
onFlinch: function (pokemon) {
this.boost({spe: 1});
},
id: "steadfast",
name: "Steadfast",
rating: 1,
num: 80
},
"stench": {
shortDesc: "This Pokemon's attacks without a chance to flinch have a 10% chance to flinch.",
onModifyMove: function (move) {
if (move.category !== "Status") {
this.debug('Adding Stench flinch');
if (!move.secondaries) move.secondaries = [];
for (var i = 0; i < move.secondaries.length; i++) {
if (move.secondaries[i].volatileStatus === 'flinch') return;
}
move.secondaries.push({
chance: 10,
volatileStatus: 'flinch'
});
}
},
id: "stench",
name: "Stench",
rating: 0.5,
num: 1
},
"stickyhold": {
shortDesc: "This Pokemon cannot lose its held item due to another Pokemon's attack.",
onTakeItem: function (item, pokemon, source) {
if (this.suppressingAttackEvents() && pokemon !== this.activePokemon) return;
if ((source && source !== pokemon) || this.activeMove.id === 'knockoff') {
this.add('-activate', pokemon, 'ability: Sticky Hold');
return false;
}
},
id: "stickyhold",
name: "Sticky Hold",
rating: 1.5,
num: 60
},
"stormdrain": {
desc: "This Pokemon is immune to Water-type moves and raises its Special Attack by 1 stage when hit by a Water-type move. If this Pokemon is not the target of a single-target Water-type move used by another Pokemon, this Pokemon redirects that move to itself if it is within the range of that move.",
shortDesc: "This Pokemon draws Water moves to itself to raise Sp. Atk by 1; Water immunity.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Water') {
if (!this.boost({spa:1})) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
onAnyRedirectTargetPriority: 1,
onAnyRedirectTarget: function (target, source, source2, move) {
if (move.type !== 'Water' || move.id in {firepledge:1, grasspledge:1, waterpledge:1}) return;
if (this.validTarget(this.effectData.target, source, move.target)) {
move.accuracy = true;
return this.effectData.target;
}
},
id: "stormdrain",
name: "Storm Drain",
rating: 3.5,
num: 114
},
"strongjaw": {
desc: "This Pokemon's bite-based attacks have their power multiplied by 1.5.",
shortDesc: "This Pokemon's bite-based attacks have 1.5x power. Bug Bite is not boosted.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (move.flags['bite']) {
return this.chainModify(1.5);
}
},
id: "strongjaw",
name: "Strong Jaw",
rating: 3,
num: 173
},
"sturdy": {
desc: "If this Pokemon is at full HP, it survives one hit with at least 1 HP. OHKO moves fail when used against this Pokemon.",
shortDesc: "If this Pokemon is at full HP, it survives one hit with at least 1 HP. Immune to OHKO.",
onTryHit: function (pokemon, target, move) {
if (move.ohko) {
this.add('-immune', pokemon, '[msg]');
return null;
}
},
onDamagePriority: -100,
onDamage: function (damage, target, source, effect) {
if (target.hp === target.maxhp && damage >= target.hp && effect && effect.effectType === 'Move') {
this.add('-activate', target, 'Sturdy');
return target.hp - 1;
}
},
id: "sturdy",
name: "Sturdy",
rating: 3,
num: 5
},
"suctioncups": {
shortDesc: "This Pokemon cannot be forced to switch out by another Pokemon's attack or item.",
onDragOutPriority: 1,
onDragOut: function (pokemon) {
this.add('-activate', pokemon, 'ability: Suction Cups');
return null;
},
id: "suctioncups",
name: "Suction Cups",
rating: 2,
num: 21
},
"superluck": {
shortDesc: "This Pokemon's critical hit ratio is raised by 1 stage.",
onModifyMove: function (move) {
move.critRatio++;
},
id: "superluck",
name: "Super Luck",
rating: 1.5,
num: 105
},
"swarm": {
desc: "When this Pokemon has 1/3 or less of its maximum HP, rounded down, its attacking stat is multiplied by 1.5 while using a Bug-type attack.",
shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Bug attacks do 1.5x damage.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk, attacker, defender, move) {
if (move.type === 'Bug' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Swarm boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function (atk, attacker, defender, move) {
if (move.type === 'Bug' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Swarm boost');
return this.chainModify(1.5);
}
},
id: "swarm",
name: "Swarm",
rating: 2,
num: 68
},
"sweetveil": {
shortDesc: "This Pokemon and its allies cannot fall asleep.",
id: "sweetveil",
name: "Sweet Veil",
onAllySetStatus: function (status, target, source, effect) {
if (status.id === 'slp') {
this.debug('Sweet Veil interrupts sleep');
return false;
}
},
onAllyTryHit: function (target, source, move) {
if (move && move.id === 'yawn') {
this.debug('Sweet Veil blocking yawn');
return false;
}
},
rating: 2,
num: 175
},
"swiftswim": {
shortDesc: "If Rain Dance is active, this Pokemon's Speed is doubled.",
onModifySpe: function (speMod, pokemon) {
if (this.isWeather(['raindance', 'primordialsea'])) {
return this.chain(speMod, 2);
}
},
id: "swiftswim",
name: "Swift Swim",
rating: 2.5,
num: 33
},
"symbiosis": {
desc: "If an ally uses its item, this Pokemon gives its item to that ally immediately. Does not activate if the ally's item was stolen or knocked off.",
shortDesc: "If an ally uses its item, this Pokemon gives its item to that ally immediately.",
onAllyAfterUseItem: function (item, pokemon) {
var sourceItem = this.effectData.target.getItem();
var noSharing = sourceItem.onTakeItem && sourceItem.onTakeItem(sourceItem, pokemon) === false;
if (!sourceItem || noSharing) {
return;
}
sourceItem = this.effectData.target.takeItem();
if (!sourceItem) {
return;
}
if (pokemon.setItem(sourceItem)) {
this.add('-activate', pokemon, 'ability: Symbiosis', sourceItem, '[of] ' + this.effectData.target);
}
},
id: "symbiosis",
name: "Symbiosis",
rating: 0,
num: 180
},
"synchronize": {
desc: "If another Pokemon burns, paralyzes, poisons, or badly poisons this Pokemon, that Pokemon receives the same major status condition.",
shortDesc: "If another Pokemon burns/poisons/paralyzes this Pokemon, it also gets that status.",
onAfterSetStatus: function (status, target, source, effect) {
if (!source || source === target) return;
if (effect && effect.id === 'toxicspikes') return;
if (status.id === 'slp' || status.id === 'frz') return;
source.trySetStatus(status, target);
},
id: "synchronize",
name: "Synchronize",
rating: 2.5,
num: 28
},
"tangledfeet": {
shortDesc: "This Pokemon's evasiveness is doubled as long as it is confused.",
onModifyAccuracy: function (accuracy, target) {
if (typeof accuracy !== 'number') return;
if (target && target.volatiles['confusion']) {
this.debug('Tangled Feet - decreasing accuracy');
return accuracy * 0.5;
}
},
id: "tangledfeet",
name: "Tangled Feet",
rating: 1,
num: 77
},
"technician": {
desc: "This Pokemon's moves of 60 power or less have their power multiplied by 1.5. Does affect Struggle.",
shortDesc: "This Pokemon's moves of 60 power or less have 1.5x power. Includes Struggle.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (basePower <= 60) {
this.debug('Technician boost');
return this.chainModify(1.5);
}
},
id: "technician",
name: "Technician",
rating: 4,
num: 101
},
"telepathy": {
shortDesc: "This Pokemon does not take damage from attacks made by its allies.",
onTryHit: function (target, source, move) {
if (target !== source && target.side === source.side && move.category !== 'Status') {
this.add('-activate', target, 'ability: Telepathy');
return null;
}
},
id: "telepathy",
name: "Telepathy",
rating: 0,
num: 140
},
"teravolt": {
shortDesc: "This Pokemon's moves and their effects ignore the Abilities of other Pokemon.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Teravolt');
},
stopAttackEvents: true,
id: "teravolt",
name: "Teravolt",
rating: 3.5,
num: 164
},
"thickfat": {
desc: "If a Pokemon uses a Fire- or Ice-type attack against this Pokemon, that Pokemon's attacking stat is halved when calculating the damage to this Pokemon.",
shortDesc: "Fire/Ice-type moves against this Pokemon deal damage with a halved attacking stat.",
onModifyAtkPriority: 6,
onSourceModifyAtk: function (atk, attacker, defender, move) {
if (move.type === 'Ice' || move.type === 'Fire') {
this.debug('Thick Fat weaken');
return this.chainModify(0.5);
}
},
onModifySpAPriority: 5,
onSourceModifySpA: function (atk, attacker, defender, move) {
if (move.type === 'Ice' || move.type === 'Fire') {
this.debug('Thick Fat weaken');
return this.chainModify(0.5);
}
},
id: "thickfat",
name: "Thick Fat",
rating: 3.5,
num: 47
},
"tintedlens": {
shortDesc: "This Pokemon's attacks that are not very effective on a target deal double damage.",
onModifyDamage: function (damage, source, target, move) {
if (move.typeMod < 0) {
this.debug('Tinted Lens boost');
return this.chainModify(2);
}
},
id: "tintedlens",
name: "Tinted Lens",
rating: 3.5,
num: 110
},
"torrent": {
desc: "When this Pokemon has 1/3 or less of its maximum HP, rounded down, its attacking stat is multiplied by 1.5 while using a Water-type attack.",
shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Water attacks do 1.5x damage.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk, attacker, defender, move) {
if (move.type === 'Water' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Torrent boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function (atk, attacker, defender, move) {
if (move.type === 'Water' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Torrent boost');
return this.chainModify(1.5);
}
},
id: "torrent",
name: "Torrent",
rating: 2,
num: 67
},
"toxicboost": {
desc: "While this Pokemon is poisoned, the power of its physical attacks is multiplied by 1.5.",
shortDesc: "While this Pokemon is poisoned, its physical attacks have 1.5x power.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if ((attacker.status === 'psn' || attacker.status === 'tox') && move.category === 'Physical') {
return this.chainModify(1.5);
}
},
id: "toxicboost",
name: "Toxic Boost",
rating: 3,
num: 137
},
"toughclaws": {
shortDesc: "This Pokemon's contact moves have their power multiplied by 1.3.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (move.flags['contact']) {
return this.chainModify([0x14CD, 0x1000]);
}
},
id: "toughclaws",
name: "Tough Claws",
rating: 3.5,
num: 181
},
"trace": {
desc: "On switch-in, this Pokemon copies a random adjacent opposing Pokemon's Ability. If there is no Ability that can be copied at that time, this Ability will activate as soon as an Ability can be copied. Abilities that cannot be copied are Flower Gift, Forecast, Illusion, Imposter, Multitype, Stance Change, Trace, and Zen Mode.",
shortDesc: "On switch-in, or when it can, this Pokemon copies a random adjacent foe's Ability.",
onUpdate: function (pokemon) {
var possibleTargets = [];
for (var i = 0; i < pokemon.side.foe.active.length; i++) {
if (pokemon.side.foe.active[i] && !pokemon.side.foe.active[i].fainted) possibleTargets.push(pokemon.side.foe.active[i]);
}
while (possibleTargets.length) {
var rand = 0;
if (possibleTargets.length > 1) rand = this.random(possibleTargets.length);
var target = possibleTargets[rand];
var ability = this.getAbility(target.ability);
var bannedAbilities = {flowergift:1, forecast:1, illusion:1, imposter:1, multitype:1, stancechange:1, trace:1, zenmode:1};
if (bannedAbilities[target.ability]) {
possibleTargets.splice(rand, 1);
continue;
}
this.add('-ability', pokemon, ability, '[from] ability: Trace', '[of] ' + target);
pokemon.setAbility(ability);
return;
}
},
id: "trace",
name: "Trace",
rating: 3,
num: 36
},
"truant": {
shortDesc: "This Pokemon skips every other turn instead of using a move.",
onBeforeMovePriority: 9,
onBeforeMove: function (pokemon, target, move) {
if (pokemon.removeVolatile('truant')) {
this.add('cant', pokemon, 'ability: Truant', move);
return false;
}
pokemon.addVolatile('truant');
},
effect: {
duration: 2
},
id: "truant",
name: "Truant",
rating: -2,
num: 54
},
"turboblaze": {
shortDesc: "This Pokemon's moves and their effects ignore the Abilities of other Pokemon.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Turboblaze');
},
stopAttackEvents: true,
id: "turboblaze",
name: "Turboblaze",
rating: 3.5,
num: 163
},
"unaware": {
desc: "This Pokemon ignores other Pokemon's Attack, Special Attack, and accuracy stat stages when taking damage, and ignores other Pokemon's Defense, Special Defense, and evasiveness stat stages when dealing damage.",
shortDesc: "This Pokemon ignores other Pokemon's stat stages when taking or doing damage.",
id: "unaware",
name: "Unaware",
onAnyModifyBoost: function (boosts, target) {
var source = this.effectData.target;
if (source === target) return;
if (source === this.activePokemon && target === this.activeTarget) {
boosts['def'] = 0;
boosts['spd'] = 0;
boosts['evasion'] = 0;
}
if (target === this.activePokemon && source === this.activeTarget) {
boosts['atk'] = 0;
boosts['spa'] = 0;
boosts['accuracy'] = 0;
}
},
rating: 3,
num: 109
},
"unburden": {
desc: "If this Pokemon loses its held item for any reason, its Speed is doubled. This boost is lost if it switches out or gains a new item or Ability.",
shortDesc: "Speed is doubled on held item loss; boost is lost if it switches, gets new item/Ability.",
onAfterUseItem: function (item, pokemon) {
if (pokemon !== this.effectData.target) return;
pokemon.addVolatile('unburden');
},
onTakeItem: function (item, pokemon) {
pokemon.addVolatile('unburden');
},
onEnd: function (pokemon) {
pokemon.removeVolatile('unburden');
},
effect: {
onModifySpe: function (speMod, pokemon) {
if (!pokemon.item) {
return this.chain(speMod, 2);
}
}
},
id: "unburden",
name: "Unburden",
rating: 3.5,
num: 84
},
"unnerve": {
shortDesc: "While this Pokemon is active, it prevents opposing Pokemon from using their Berries.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Unnerve', pokemon.side.foe);
},
onFoeEatItem: false,
id: "unnerve",
name: "Unnerve",
rating: 1.5,
num: 127
},
"victorystar": {
shortDesc: "This Pokemon and its allies' moves have their accuracy multiplied by 1.1.",
onAllyModifyMove: function (move) {
if (typeof move.accuracy === 'number') {
move.accuracy *= 1.1;
}
},
id: "victorystar",
name: "Victory Star",
rating: 2.5,
num: 162
},
"vitalspirit": {
shortDesc: "This Pokemon cannot fall asleep. Gaining this Ability while asleep cures it.",
onUpdate: function (pokemon) {
if (pokemon.status === 'slp') {
pokemon.cureStatus();
}
},
onImmunity: function (type) {
if (type === 'slp') return false;
},
id: "vitalspirit",
name: "Vital Spirit",
rating: 2,
num: 72
},
"voltabsorb": {
desc: "This Pokemon is immune to Electric-type moves and restores 1/4 of its maximum HP, rounded down, when hit by an Electric-type move.",
shortDesc: "This Pokemon heals 1/4 of its max HP when hit by Electric moves; Electric immunity.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Electric') {
if (!this.heal(target.maxhp / 4)) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
id: "voltabsorb",
name: "Volt Absorb",
rating: 3.5,
num: 10
},
"waterabsorb": {
desc: "This Pokemon is immune to Water-type moves and restores 1/4 of its maximum HP, rounded down, when hit by a Water-type move.",
shortDesc: "This Pokemon heals 1/4 of its max HP when hit by Water moves; Water immunity.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Water') {
if (!this.heal(target.maxhp / 4)) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
id: "waterabsorb",
name: "Water Absorb",
rating: 3.5,
num: 11
},
"waterveil": {
shortDesc: "This Pokemon cannot be burned. Gaining this Ability while burned cures it.",
onUpdate: function (pokemon) {
if (pokemon.status === 'brn') {
pokemon.cureStatus();
}
},
onImmunity: function (type, pokemon) {
if (type === 'brn') return false;
},
id: "waterveil",
name: "Water Veil",
rating: 2,
num: 41
},
"weakarmor": {
desc: "If a physical attack hits this Pokemon, its Defense is lowered by 1 stage and its Speed is raised by 1 stage.",
shortDesc: "If a physical attack hits this Pokemon, Defense is lowered by 1, Speed is raised by 1.",
onAfterDamage: function (damage, target, source, move) {
if (move.category === 'Physical') {
this.boost({spe:1, def:-1});
}
},
id: "weakarmor",
name: "Weak Armor",
rating: 0.5,
num: 133
},
"whitesmoke": {
shortDesc: "Prevents other Pokemon from lowering this Pokemon's stat stages.",
onBoost: function (boost, target, source, effect) {
if (source && target === source) return;
var showMsg = false;
for (var i in boost) {
if (boost[i] < 0) {
delete boost[i];
showMsg = true;
}
}
if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: White Smoke", "[of] " + target);
},
id: "whitesmoke",
name: "White Smoke",
rating: 2,
num: 73
},
"wonderguard": {
shortDesc: "This Pokemon can only be damaged by supereffective moves and indirect damage.",
onTryHit: function (target, source, move) {
if (target === source || move.category === 'Status' || move.type === '???' || move.id === 'struggle' || move.isFutureMove) return;
this.debug('Wonder Guard immunity: ' + move.id);
if (target.runEffectiveness(move) <= 0) {
this.add('-activate', target, 'ability: Wonder Guard');
return null;
}
},
id: "wonderguard",
name: "Wonder Guard",
rating: 5,
num: 25
},
"wonderskin": {
desc: "All non-damaging moves that check accuracy have their accuracy changed to 50% when used on this Pokemon. This change is done before any other accuracy modifying effects.",
shortDesc: "Status moves with accuracy checks are 50% accurate when used on this Pokemon.",
onModifyAccuracyPriority: 10,
onModifyAccuracy: function (accuracy, target, source, move) {
if (move.category === 'Status' && typeof move.accuracy === 'number') {
this.debug('Wonder Skin - setting accuracy to 50');
return 50;
}
},
id: "wonderskin",
name: "Wonder Skin",
rating: 2,
num: 147
},
"zenmode": {
desc: "If this Pokemon is a Darmanitan, it changes to Zen Mode if it has 1/2 or less of its maximum HP at the end of a turn. If Darmanitan's HP is above 1/2 of its maximum HP at the end of a turn, it changes back to Standard Mode. If Darmanitan loses this Ability while in Zen Mode it reverts to Standard Mode immediately.",
shortDesc: "If Darmanitan, at end of turn changes Mode to Standard if > 1/2 max HP, else Zen.",
onResidualOrder: 27,
onResidual: function (pokemon) {
if (pokemon.baseTemplate.species !== 'Darmanitan') {
return;
}
if (pokemon.hp <= pokemon.maxhp / 2 && pokemon.template.speciesid === 'darmanitan') {
pokemon.addVolatile('zenmode');
} else if (pokemon.hp > pokemon.maxhp / 2 && pokemon.template.speciesid === 'darmanitanzen') {
pokemon.removeVolatile('zenmode');
}
},
effect: {
onStart: function (pokemon) {
if (pokemon.formeChange('Darmanitan-Zen')) {
this.add('-formechange', pokemon, 'Darmanitan-Zen');
} else {
return false;
}
},
onEnd: function (pokemon) {
if (pokemon.formeChange('Darmanitan')) {
this.add('-formechange', pokemon, 'Darmanitan');
} else {
return false;
}
},
onUpdate: function (pokemon) {
if (!pokemon.hasAbility('zenmode')) {
pokemon.transformed = false;
pokemon.removeVolatile('zenmode');
}
}
},
id: "zenmode",
name: "Zen Mode",
rating: -1,
num: 161
},
// CAP
"mountaineer": {
shortDesc: "On switch-in, this Pokemon avoids all Rock-type attacks and Stealth Rock.",
onDamage: function (damage, target, source, effect) {
if (effect && effect.id === 'stealthrock') {
return false;
}
},
onImmunity: function (type, target) {
if (type === 'Rock' && !target.activeTurns) {
return false;
}
},
id: "mountaineer",
isNonstandard: true,
name: "Mountaineer",
rating: 3.5,
num: -2
},
"rebound": {
desc: "On switch-in, this Pokemon blocks certain status moves and instead uses the move against the original user.",
shortDesc: "On switch-in, blocks certain status moves and bounces them back to the user.",
id: "rebound",
isNonstandard: true,
name: "Rebound",
onTryHitPriority: 1,
onTryHit: function (target, source, move) {
if (this.effectData.target.activeTurns) return;
if (target === source || move.hasBounced || !move.flags['reflectable']) {
return;
}
var newMove = this.getMoveCopy(move.id);
newMove.hasBounced = true;
this.useMove(newMove, target, source);
return null;
},
onAllyTryHitSide: function (target, source, move) {
if (this.effectData.target.activeTurns) return;
if (target.side === source.side || move.hasBounced || !move.flags['reflectable']) {
return;
}
var newMove = this.getMoveCopy(move.id);
newMove.hasBounced = true;
this.useMove(newMove, target, source);
return null;
},
effect: {
duration: 1
},
rating: 3.5,
num: -3
},
"persistent": {
shortDesc: "The duration of certain field effects is increased by 2 turns if used by this Pokemon.",
id: "persistent",
isNonstandard: true,
name: "Persistent",
// implemented in the corresponding move
rating: 3.5,
num: -4
}
};
|
/* @flow */
import _ from 'lodash/fp';
/* ARRAY */
/**
* _.chunk
*/
(_.chunk(2, ['a', 'b', 'c', 'd']): Array<Array<string>>);
(_.chunk(2)(['a', 'b', 'c', 'd']): Array<Array<string>>);
(_.chunk(2, null): Array<Array<any>>);
// $ExpectError
(_.chunk(2, ['a', 'b', 'c', 'd']): Array<Array<void>>);
// $ExpectError
(_.chunk(2)(['a', 'b', 'c', 'd']): Array<Array<void>>);
// $ExpectError
(_.chunk(2, null): Object);
/**
* _.compact
*/
(_.compact((['a', 'b', null]: Array<?string>)): Array<string>);
(_.compact((['a', 'b', null, false]: Array<?string | false>)): Array<string>);
// $ExpectError
(_.compact((['a', 'b', null]: Array<?string>)): Array<void>);
// $ExpectError
(_.compact((['a', 'b', null, false]: Array<?string | false>)): Array<void>);
/**
* _.concat
*/
(_.concat(['a', 'b', 'c'], 'd'): Array<string>);
(_.concat(['a', 'b', 'c'])('d'): Array<string>);
(_.concat(['a', 'b', 'c'], ['d']): Array<string>);
(_.concat(null, 'd'): Array<?string>);
(_.concat(['a', 'b', 'c'], null): Array<?string>);
(_.concat(null, null): Array<any>);
// $ExpectError
(_.concat(['a', 'b', 'c'], 'd'): Array<void>);
// $ExpectError
(_.concat(['a', 'b', 'c'])('d'): Array<void>);
// $ExpectError
(_.concat(['a', 'b', 'c'], ['d']): Array<void>);
// $ExpectError
(_.concat(null, 'd'): Array<void>);
// $ExpectError
(_.concat(['a', 'b', 'c'], null): Array<void>);
// $ExpectError
(_.concat(null, null): Object);
/**
* _.drop
*/
(_.drop(['a', 'b', 'c']): Array<string>);
(_.drop(null): Array<any>);
// $ExpectError
(_.drop(['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.drop(null): Object);
/**
* _.dropRight
*/
(_.dropRight(1, ['a', 'b', 'c']): Array<string>);
(_.dropRight(1)(['a', 'b', 'c']): Array<string>);
(_.dropRight(1, null): Array<any>);
// $ExpectError
(_.dropRight(1, ['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.dropRight(1)(['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.dropRight(1, null): Object);
/**
* _.findIndex
*/
(_.findIndex(el => el.val === 'a', [{val: 'a'}, {val: 'b'}]): number);
(_.findIndex(el => el.val === 'a')([{val: 'a'}, {val: 'b'}]): number);
(_.findIndex({val: 'a'}, [{val: 'a'}, {val: 'b'}]): number);
(_.findIndex(['val', 'a'], [{val: 'a'}, {val: 'b'}]): number);
(_.findIndex('val', [{val: 'a'}, {val: 'b'}]): number);
// $ExpectError
(_.findIndex(el => el.val === 'a', [{val: 'a'}, {val: 'b'}]): void);
// $ExpectError
(_.findIndex(el => el.val === 'a')([{val: 'a'}, {val: 'b'}]): void);
// $ExpectError
(_.findIndex(el => el.notval === 'a', [{val: 'a'}, {val: 'b'}]): number);
/**
* _.flatten
*/
(_.flatten([['a', 'b'], ['c', 'd']]): Array<string>);
(_.flatten(null): Array<any>);
// $ExpectError
(_.flatten([['a', 'b'], ['c', 'd']]): Array<void>);
// $ExpectError
(_.flatten([['a', 'b'], ['c', ['d']]]): Array<string>);
// $ExpectError
(_.flatten(null): Object);
/**
* _.fromPairs
*/
(_.fromPairs([['val', 'a'], ['val', 'b']]): {+[key: string]: string});
(_.fromPairs([['val', 'a'], ['val', 'b']]): {+[key: 'val']: string});
(_.fromPairs(null): {+[key: any]: any});
// $ExpectError
(_.fromPairs([['val', 'a'], ['val', 'b']]): {+[key: string]: void});
// $ExpectError
(_.fromPairs([['val', 'a'], ['val', 'b']]): {+[key: void]: string});
// $ExpectError
(_.fromPairs(null): Array<any>);
/**
* _.head
*/
(_.head(['a', 'b', 'c']): ?string);
// $ExpectError
(_.head(['a', 'b', 'c']): string);
// $ExpectError
(_.head(['a', 'b', 'c']): void);
/**
* _.intersection
*/
(_.intersection(['a', 'b'], ['c', 'd']): Array<string>);
(_.intersection(['a', 'b'])(['c', 'd']): Array<string>);
(_.intersection(['a', 'b'], null): Array<string>);
(_.intersection(null, ['c', 'd']): Array<string>);
(_.intersection(null, null): Array<any>);
// $ExpectError
(_.intersection(['a', 'b'], ['c', 'd']): Array<void>);
// $ExpectError
(_.intersection(['a', 'b'])(['c', 'd']): Array<void>);
// $ExpectError
(_.intersection(['a', 'b'], null): Array<void>);
// $ExpectError
(_.intersection(null, ['c', 'd']): Array<void>);
// $ExpectError
(_.intersection(null, null): Object);
/**
* _.join
*/
(_.join(',', ['a', 'b', 'c']): string);
(_.join(',')(['a', 'b', 'c']): string);
// $ExpectError
(_.join(',', ['a', 'b', 'c']): void);
// $ExpectError
(_.join(',')(['a', 'b', 'c']): void);
/**
* _.pull
*/
(_.pull('a', ['a', 'b', 'c']): Array<string>);
(_.pull('a')(['a', 'b', 'c']): Array<string>);
(_.pull('a', null): Array<string>);
// $ExpectError
(_.pull('a', ['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.pull('a')(['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.pull('a', null): Array<void>);
/**
* _.pullAll
*/
(_.pullAll(['a'], ['a', 'b', 'c']): Array<string>);
(_.pullAll(['a'])(['a', 'b', 'c']): Array<string>);
(_.pullAll(['a'], null): Array<string>);
// $ExpectError
(_.pullAll(['a'], ['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.pullAll(['a'])(['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.pullAll(['a'], null): Array<void>);
/**
* _.pullAt
*/
(_.pullAt([0], ['a', 'b', 'c']): Array<string>);
(_.pullAt([0])(['a', 'b', 'c']): Array<string>);
(_.pullAt([0], null): Array<any>);
// $ExpectError
(_.pullAt([0], ['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.pullAt([0])(['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.pullAt([0], null): Object);
/**
* _.slice
*/
(_.slice(0, 1, ['a', 'b', 'c']): Array<string>);
(_.slice(0, 1)(['a', 'b', 'c']): Array<string>);
(_.slice(0)(1)(['a', 'b', 'c']): Array<string>);
(_.slice(0, 1, null): Array<any>);
// $ExpectError
(_.slice(0, 1, ['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.slice(0, 1)(['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.slice(0)(1)(['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.slice(0, 1, null): Object);
/**
* _.tail
*/
(_.tail(['a', 'b', 'c']): Array<string>);
// $ExpectError
(_.tail(['a', 'b', 'c']): Array<void>);
/**
* _.last
*/
(_.last(['a', 'b', 'c']): string);
// $ExpectError
(_.last(['a', 'b', 'c']): void);
/**
* _.uniq
*/
(_.uniq(['a', 'b', 'c']): Array<string>);
(_.uniq(null): Array<any>);
// $ExpectError
(_.uniq(['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.uniq(null): Object);
/**
* _.uniqBy
*/
(_.uniqBy(el => el.val, [{val: 'a'}, {val: 'b'}]): Array<Object>);
(_.uniqBy(el => el.val)([{val: 'a'}, {val: 'b'}]): Array<Object>);
(_.uniqBy('val', [{val: 'a'}, {val: 'b'}]): Array<Object>);
// $ExpectError
(_.uniqBy(el => el.val, [{val: 'a'}, {val: 'b'}]): Object);
// $ExpectError
(_.uniqBy(el => el.val)([{val: 'a'}, {val: 'b'}]): Object);
// $ExpectError
(_.uniqBy(el => el.notval, [{val: 'a'}, {val: 'b'}]): Array<Object>);
/**
* _.uniqWith
*/
(_.uniqWith((a, b) => a === b, [{val: 'a'}, {val: 'b'}]): Array<Object>);
(_.uniqWith((a, b) => a === b)([{val: 'a'}, {val: 'b'}]): Array<Object>);
// $ExpectError
(_.uniqWith((a, b) => a === b, [{val: 'a'}, {val: 'b'}]): Object);
// $ExpectError
(_.uniqWith((a, b) => a === b)([{val: 'a'}, {val: 'b'}]): Object);
// $ExpectError
(_.uniqWith((a, b) => a.notval, [{val: 'a'}, {val: 'b'}]): Array<Object>);
/* COLLECTION */
/**
* _.every
*/
(_.every(el => el.val === 'a', [{val: 'a'}, {val: 'b'}]): boolean);
(_.every(el => el.val === 'a')([{val: 'a'}, {val: 'b'}]): boolean);
(_.every({val: 'a'}, [{val: 'a'}, {val: 'b'}]): boolean);
(_.every(['val', 'a'], [{val: 'a'}, {val: 'b'}]): boolean);
(_.every('val', [{val: 'a'}, {val: 'b'}]): boolean);
(_.every('val', null): boolean);
// $ExpectError
(_.every(el => el.val === 'a', [{val: 'a'}, {val: 'b'}]): void);
// $ExpectError
(_.every(el => el.val === 'a')([{val: 'a'}, {val: 'b'}]): void);
// $ExpectError
(_.every('val', null): void);
// $ExpectError
(_.every(el => el.notval === 'a', [{val: 'a'}, {val: 'b'}]): boolean);
/**
* _.filter
*/
(_.filter(el => el.val === 'a', [{val: 'a'}, {val: 'b'}]): Array<Object>);
(_.filter(el => el.val === 'a')([{val: 'a'}, {val: 'b'}]): Array<Object>);
(_.filter({val: 'a'}, [{val: 'a'}, {val: 'b'}]): Array<Object>);
(_.filter(['val', 'a'], [{val: 'a'}, {val: 'b'}]): Array<Object>);
(_.filter('val', [{val: 'a'}, {val: 'b'}]): Array<Object>);
// $ExpectError
(_.filter(el => el.val === 'a', [{val: 'a'}, {val: 'b'}]): Object);
// $ExpectError
(_.filter(el => el.val === 'a')([{val: 'a'}, {val: 'b'}]): Object);
// $ExpectError
(_.filter(el => el.notval === 'a', [{val: 'a'}, {val: 'b'}]): Array<Object>);
/**
* _.find
*/
(_.find(el => el.val === 'a', [{val: 'a'}, {val: 'b'}]): ?Object);
(_.find(el => el.val === 'a')([{val: 'a'}, {val: 'b'}]): ?Object);
(_.find({val: 'a'}, [{val: 'a'}, {val: 'b'}]): ?Object);
(_.find(['val', 'a'], [{val: 'a'}, {val: 'b'}]): ?Object);
(_.find('val', [{val: 'a'}, {val: 'b'}]): ?Object);
(_.find('val', null): void);
// $ExpectError
(_.find(el => el.val === 'a', [{val: 'a'}, {val: 'b'}]): Array<any>);
// $ExpectError
(_.find(el => el.val === 'a')([{val: 'a'}, {val: 'b'}]): Array<any>);
// $ExpectError
(_.find(el => el.notval === 'a', [{val: 'a'}, {val: 'b'}]): ?Object);
/**
* _.flatMap
*/
(_.flatMap(el => [el, el], ['a', 'b', 'c']): Array<string>);
(_.flatMap(el => [el, el])(['a', 'b', 'c']): Array<string>);
(_.flatMap(el => el, ['a', 'b', 'c']): Array<string>);
(_.flatMap(el => [el, el], null): Array<any>);
// $ExpectError
(_.flatMap(el => [el, el], ['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.flatMap(el => [el, el])(['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.flatMap(el => el, ['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.flatMap(el => [el, el], null): Object);
/**
* _.groupBy
*/
(_.groupBy('val', [{val: 'a'}, {val: 'b'}, {val: 'c'}]): {
+[key: string]: Array<{val: string}>,
});
(_.groupBy('val')([{val: 'a'}, {val: 'b'}, {val: 'c'}]): {
+[key: string]: Array<{val: string}>,
});
(_.groupBy('val', null): {+[key: any]: Array<any>});
// $ExpectError
(_.groupBy('val', [{val: 'a'}, {val: 'b'}, {val: 'c'}]): {
+[key: string]: Array<void>,
});
// $ExpectError
(_.groupBy('val')([{val: 'a'}, {val: 'b'}, {val: 'c'}]): {
+[key: string]: Array<void>,
});
// $ExpectError
(_.groupBy('val', null): Array<any>);
/**
* _.includes
*/
(_.includes('a', ['a', 'b', 'c']): boolean);
(_.includes('a')(['a', 'b', 'c']): boolean);
(_.includes('a', 'abc'): boolean);
(_.includes('a', null): boolean);
// $ExpectError
(_.includes('a', ['a', 'b', 'c']): void);
// $ExpectError
(_.includes('a')(['a', 'b', 'c']): void);
// $ExpectError
(_.includes('a', 'abc'): void);
// $ExpectError
(_.includes('a', null): void);
/**
* _.map
*/
(_.map(el => el.val, [{val: 'a'}, {val: 'b'}]): Array<string>);
(_.map(el => el.val)([{val: 'a'}, {val: 'b'}]): Array<string>);
(_.map('val', [{val: 'a'}, {val: 'b'}]): Array<string>);
(_.map('val', {a: 'a', b: 'b'}): Array<any>);
(_.map(el => el.val, null): Array<any>);
// $ExpectError
(_.map(el => el.val, [{val: 'a'}, {val: 'b'}]): Array<void>);
// $ExpectError
(_.map(el => el.val)([{val: 'a'}, {val: 'b'}]): Array<void>);
// $ExpectError
(_.map('val', [{val: 'a'}, {val: 'b'}]): Object);
// $ExpectError
(_.map('val', {a: 'a', b: 'b'}): Object);
// $ExpectError
(_.map(el => el.val, null): Object);
/**
* _.reduce
*/
(_.reduce((acc, val) => acc + val, 0, [1, 2, 3]): number);
(_.reduce((acc, val) => acc + val, 0)([1, 2, 3]): number);
(_.reduce((acc, val) => acc + val)(0)([1, 2, 3]): number);
(_.reduce((acc, val) => acc + val, 0, null): number);
// $ExpectError
(_.reduce((acc, val) => acc + val, 0, [1, 2, 3]): void);
// $ExpectError
(_.reduce((acc, val) => acc + val, 0)([1, 2, 3]): void);
// $ExpectError
(_.reduce((acc, val) => acc + val)(0)([1, 2, 3]): void);
// $ExpectError
(_.reduce((acc, val) => acc + val, 0, null): void);
/**
* _.reject
*/
(_.reject(el => el.val === 'a', [{val: 'a'}, {val: 'b'}]): Array<Object>);
(_.reject(el => el.val === 'a')([{val: 'a'}, {val: 'b'}]): Array<Object>);
(_.reject({val: 'a'}, [{val: 'a'}, {val: 'b'}]): Array<Object>);
(_.reject(['val', 'a'], [{val: 'a'}, {val: 'b'}]): Array<Object>);
(_.reject('val', [{val: 'a'}, {val: 'b'}]): Array<Object>);
// $ExpectError
(_.reject(el => el.val === 'a', [{val: 'a'}, {val: 'b'}]): Object);
// $ExpectError
(_.reject(el => el.val === 'a')([{val: 'a'}, {val: 'b'}]): Object);
// $ExpectError
(_.reject(el => el.notval === 'a', [{val: 'a'}, {val: 'b'}]): Array<Object>);
/**
* _.shuffle
*/
(_.shuffle(['a', 'b', 'c']): Array<string>);
(_.shuffle({a: 'a', b: 'b', c: 'c'}): {+[key: string]: string});
// $ExpectError
(_.shuffle(['a', 'b', 'c']): Array<void>);
// $ExpectError
(_.shuffle({a: 'a', b: 'b', c: 'c'}): {+[key: string]: void});
/**
* _.size
*/
(_.size(['a', 'b', 'c']): number);
(_.size({a: 'a', b: 'b', c: 'c'}): number);
(_.size('abc'): number);
// $ExpectError
(_.size(['a', 'b', 'c']): void);
// $ExpectError
(_.size({a: 'a', b: 'b', c: 'c'}): void);
// $ExpectError
(_.size('abc'): void);
/**
* _.some
*/
(_.some(el => el.val === 'a', [{val: 'a'}, {val: 'b'}]): boolean);
(_.some(el => el.val === 'a')([{val: 'a'}, {val: 'b'}]): boolean);
(_.some({val: 'a'}, [{val: 'a'}, {val: 'b'}]): boolean);
(_.some(['val', 'a'], [{val: 'a'}, {val: 'b'}]): boolean);
(_.some('val', [{val: 'a'}, {val: 'b'}]): boolean);
(_.some('val', null): boolean);
// $ExpectError
(_.some(el => el.val === 'a', [{val: 'a'}, {val: 'b'}]): void);
// $ExpectError
(_.some(el => el.val === 'a')([{val: 'a'}, {val: 'b'}]): void);
// $ExpectError
(_.some('val', null): void);
// $ExpectError
(_.some(el => el.notval === 'a', [{val: 'a'}, {val: 'b'}]): boolean);
/**
* _.sortBy
*/
(_.sortBy(el => el.val, [{val: 'a'}, {val: 'b'}]): Array<Object>);
(_.sortBy(el => el.val)([{val: 'a'}, {val: 'b'}]): Array<Object>);
(_.sortBy('val', [{val: 'a'}, {val: 'b'}]): Array<Object>);
(_.sortBy([el => el.val, el => el.val], [{val: 'a'}, {val: 'b'}]): Array<
Object,
>);
// $ExpectError
(_.sortBy(el => el.val, [{val: 'a'}, {val: 'b'}]): Object);
// $ExpectError
(_.sortBy(el => el.val)([{val: 'a'}, {val: 'b'}]): Object);
// $ExpectError
(_.sortBy(el => el.notval, [{val: 'a'}, {val: 'b'}]): Array<Object>);
// $ExpectError
(_.sortBy([el => el.notval, el => el.val], [{val: 'a'}, {val: 'b'}]): Array<
Object,
>);
/* FUNCTION */
/**
* _.debounce
*/
(_.debounce(1000, () => 'a'): () => string);
(_.debounce(1000)(() => 'a'): () => string);
// $ExpectError
(_.debounce(1000, () => 'a'): () => void);
// $ExpectError
(_.debounce(1000)(() => 'a'): () => void);
/**
* _.negate
*/
(_.negate(() => true): () => boolean);
// $ExpectError
(_.negate(() => true): () => void);
/**
* _.debounce
*/
(_.throttle(1000, () => 'a'): () => string);
(_.throttle(1000)(() => 'a'): () => string);
// $ExpectError
(_.throttle(1000, () => 'a'): () => void);
// $ExpectError
(_.throttle(1000)(() => 'a'): () => void);
/* LANG */
/**
* _.eq
*/
(_.eq('a', 'b'): boolean);
(_.eq('a')('b'): boolean);
// $ExpectError
(_.eq('a', 'b'): void);
// $ExpectError
(_.eq('a')('b'): void);
/**
* _.isArray
*/
(_.isArray([]): boolean);
// $ExpectError
(_.isArray([]): void);
/**
* _.isEqual
*/
(_.isEqual({a: 'a'}, {b: 'b'}): boolean);
(_.isEqual({a: 'a'})({b: 'b'}): boolean);
// $ExpectError
(_.isEqual({a: 'a'}, {b: 'b'}): void);
// $ExpectError
(_.isEqual({a: 'a'})({b: 'b'}): void);
/**
* _.isEmpty
*/
(_.isEmpty('a'): boolean);
// $ExpectError
(_.isEmpty('a'): void);
/**
* _.isNaN
*/
(_.isNaN('a'): boolean);
// $ExpectError
(_.isNaN('a'): void);
/**
* _.isNil
*/
(_.isNil('a'): boolean);
// $ExpectError
(_.isNil('a'): void);
/**
* _.isPlainObject
*/
(_.isPlainObject({}): boolean);
// $ExpectError
(_.isPlainObject({}): void);
/* MATH */
/**
* _.sum
*/
(_.sum([1, 2, 3]): number);
(_.sum(null): number);
// $ExpectError
(_.sum(['a', 'b', 'c']): number);
// $ExpectError
(_.sum([1, 2, 3]): void);
// $ExpectError
(_.sum(null): void);
/* NUMBER */
/**
* _.random
*/
(_.random(1, 2): number);
// $ExpectError
(_.random('a', 'b'): number);
// $ExpectError
(_.random(1, 2): void);
/* OBJECT */
/**
* _.assign
*/
(_.assign({a: 'a'}, {b: 'b'}): {a: 'a', b: 'b'});
(_.assign({a: 'a'})({b: 'b'}): {a: 'a', b: 'b'});
(_.assign({a: 'a'}, {a: 'b', b: 'b'}): {a: 'b', b: 'b'});
// $ExpectError
(_.assign({a: 'a'}, {b: 'b'}): {a: 'b', b: 'b'});
// $ExpectError
(_.assign({a: 'a'})({b: 'b'}): {a: 'b', b: 'b'});
// $ExpectError
(_.assign({a: 'a'}, {a: 'b', b: 'b'}): {a: 'a', b: 'b'});
/**
* _.assignAll
*/
(_.assignAll([{a: 'a'}, {b: 'b'}]): {+[key: string]: string});
/**
* _.get
*/
_.get('a', {a: 'a'});
_.get('a')({a: 'a'});
// $ExpectError
_.get(null, {a: 'a'});
// $ExpectError
_.get('a', []);
/**
* _.getOr
*/
_.getOr('a', 'a', {a: 'a'});
_.getOr('a', 'a')({a: 'a'});
_.getOr('a')('a')({a: 'a'});
// $ExpectError
_.getOr('a', null, {a: 'a'});
// $ExpectError
_.getOr('a', 'a', []);
/**
* _.invert
*/
(_.invert({a: 1, b: 2, c: 3}): {+[key: number]: string});
(_.invert(null): {+[key: any]: any});
// $ExpectError
(_.invert({a: 1, b: 2, c: 3}): {+[key: number]: number});
// $ExpectError
(_.invert({a: 1, b: 2, c: 3}): {+[key: string]: string});
// $ExpectError
(_.invert(null): Array<any>);
/**
* _.keys
*/
(_.keys({a: 'a', b: 'b', c: 'c'}): Array<'a' | 'b' | 'c'>);
// $ExpectError
(_.keys({a: 'a', b: 'b', c: 'c'}): Array<'a' | 'b' | 'c' | 'd'>);
// $ExpectError
(_.keys({a: 'a', b: 'b', c: 'c'}): Array<void>);
// $ExpectError
(_.keys(null): Array<void>);
/**
* _.mapKeys
*/
(_.mapKeys(key => 'a', {a: 'a', b: 'b'}): {+[key: 'a']: string});
(_.mapKeys(key => 'a')({a: 'a', b: 'b'}): {+[key: 'a']: string});
(_.mapKeys(key => 'a', null): {+[key: 'a']: any});
// $ExpectError
(_.mapKeys(key => 'a', {a: 'a', b: 'b'}): {+[key: 'b']: string});
// $ExpectError
(_.mapKeys(key => 'a')({a: 'a', b: 'b'}): {+[key: 'b']: string});
// $ExpectError
(_.mapKeys(key => key.key, {a: 'a', b: 'b'}): {+[key: 'a']: string});
// $ExpectError
(_.mapKeys(key => 'a', null): {+[key: 'b']: any});
// $ExpectError
(_.mapKeys(key => 'a', {a: 'a', b: 'b'}): {+[key: 'a']: number});
/**
* _.mapValues
*/
(_.mapValues(val => 'a', {a: 'a', b: 'b'}): {+[key: 'a' | 'b']: 'a'});
(_.mapValues(val => 'a')({a: 'a', b: 'b'}): {+[key: 'a' | 'b']: 'a'});
(_.mapValues(val => 'a', null): {+[key: string]: 'a'});
// $ExpectError
(_.mapValues(val => 'a', {a: 'a', b: 'b'}): {+[key: 'a' | 'c']: 'a'});
// $ExpectError
(_.mapValues(val => 'a')({a: 'a', b: 'b'}): {+[key: 'a' | 'c']: 'a'});
// $ExpectError
(_.mapValues(val => 'a', {a: 'a', b: 'b'}): {+[key: 'a' | 'b']: 'c'});
// $ExpectError
(_.mapValues(val => 'a', null): {+[key: string]: 'c'});
(_.mapValues(val => 'a', null): {+[key: Object]: 'a'});
/**
* _.merge
*/
(_.merge({a: 'a'}, {b: 'b'}): {a: 'a', b: 'b'});
(_.merge({a: 'a'})({b: 'b'}): {a: 'a', b: 'b'});
(_.merge({a: 'a'}, {a: 'b', b: 'b'}): {a: 'b', b: 'b'});
// $ExpectError
(_.merge({a: 'a'}, {b: 'b'}): {a: 'b', b: 'b'});
// $ExpectError
(_.merge({a: 'a'})({b: 'b'}): {a: 'b', b: 'b'});
// $ExpectError
(_.merge({a: 'a'}, {a: 'b', b: 'b'}): {a: 'a', b: 'b'});
/**
* _.mergeAll
*/
(_.mergeAll([{a: 'a'}, {b: 'b'}]): {+[key: 'a' | 'b' | 'c']: string});
/**
* _.omit
*/
(_.omit(['a'], {a: 'a', b: 'b', c: 'c'}): Object);
(_.omit(['a'])({a: 'a', b: 'b', c: 'c'}): Object);
(_.omit(['a'], null): Object);
// $ExpectError
(_.omit(['a'], {a: 'a', b: 'b', c: 'c'}): Array<any>);
// $ExpectError
(_.omit(['a'])({a: 'a', b: 'b', c: 'c'}): Array<any>);
// $ExpectError
(_.omit(['a'], null): Array<any>);
// $ExpectError
(_.omit(['d'], {a: 'a', b: 'b', c: 'c'}): Object);
// $ExpectError
(_.omit([1], {a: 'a', b: 'b', c: 'c'}): Object);
// $ExpectError
(_.omit(['a'], {a: 'a', b: 'b', c: 'c'}): Array<any>);
/**
* _.omitBy
*/
(_.omitBy(val => val === 'a', {a: 'a', b: 'b', c: 'c'}): Object);
(_.omitBy(val => val === 'a')({a: 'a', b: 'b', c: 'c'}): Object);
(_.omitBy(val => val === 'a', null): Object);
// $ExpectError
(_.omitBy(val => val === 'a', {a: 'a', b: 'b', c: 'c'}): Array<any>);
// $ExpectError
(_.omitBy(val => val === 'a')({a: 'a', b: 'b', c: 'c'}): Array<any>);
// $ExpectError
(_.omitBy(val => val === 'a', null): Array<any>);
// $ExpectError
(_.omitBy(val => val, {a: 'a', b: 'b', c: 'c'}): Object);
// $ExpectError
(_.omitBy((val: number) => val === 'a', {a: 'a', b: 'b', c: 'c'}): Object);
/**
* _.pick
*/
(_.pick(['a'], {a: 'a', b: 'b', c: 'c'}): Object);
(_.pick(['a'])({a: 'a', b: 'b', c: 'c'}): Object);
(_.pick(['a'], null): Object);
// $ExpectError
(_.pick(['a'], {a: 'a', b: 'b', c: 'c'}): Array<any>);
// $ExpectError
(_.pick(['a'])({a: 'a', b: 'b', c: 'c'}): Array<any>);
// $ExpectError
(_.pick(['a'], null): Array<any>);
// $ExpectError
(_.pick(['d'], {a: 'a', b: 'b', c: 'c'}): Object);
// $ExpectError
(_.pick([1], {a: 'a', b: 'b', c: 'c'}): Object);
// $ExpectError
(_.pick(['a'], {a: 'a', b: 'b', c: 'c'}): Array<any>);
/**
* _.pickBy
*/
(_.pickBy(val => val === 'a', {a: 'a', b: 'b', c: 'c'}): Object);
(_.pickBy(val => val === 'a')({a: 'a', b: 'b', c: 'c'}): Object);
(_.pickBy(val => val === 'a', null): Object);
// $ExpectError
(_.pickBy(val => val === 'a', {a: 'a', b: 'b', c: 'c'}): Array<any>);
// $ExpectError
(_.pickBy(val => val === 'a')({a: 'a', b: 'b', c: 'c'}): Array<any>);
// $ExpectError
(_.pickBy(val => val === 'a', null): Array<any>);
// $ExpectError
(_.pickBy(val => val, {a: 'a', b: 'b', c: 'c'}): Object);
// $ExpectError
(_.pickBy((val: number) => val === 'a', {a: 'a', b: 'b', c: 'c'}): Object);
/**
* _.update
*/
(_.update('a', el => el, {a: 'a', b: 'b', c: 'c'}): Object);
(_.update('a', el => el)({a: 'a', b: 'b', c: 'c'}): Object);
(_.update('a')(el => el)({a: 'a', b: 'b', c: 'c'}): Object);
(_.update('a', el => el, null): Object);
// $ExpectError
(_.update('a', el => el, {a: 'a', b: 'b', c: 'c'}): Array<any>);
// $ExpectError
(_.update('a', el => el)({a: 'a', b: 'b', c: 'c'}): Array<any>);
// $ExpectError
(_.update('a')(el => el)({a: 'a', b: 'b', c: 'c'}): Array<any>);
/**
* _.values
*/
(_.values({a: 'a', b: 'b', c: 'c'}): Array<string>);
(_.values(null): Array<any>);
// $ExpectError
(_.values({a: 'a', b: 'b', c: 'c'}): Array<void>);
// $ExpectError
(_.values(null): Object);
/**
* _.toPairs
*/
(_.toPairs({a: 'a', b: 'b', c: 'c'}): Array<['a' | 'b' | 'c', string]>);
(_.toPairs(null): Array<[any, any]>);
// $ExpectError
(_.toPairs({a: 'a', b: 'b', c: 'c'}): Object);
// $ExpectError
(_.toPairs({a: 'a', b: 'b', c: 'c'}): Array<['a' | 'b' | 'c' | 'd', string]>);
// $ExpectError
(_.toPairs(null): Object);
/**
* _.has
*/
(_.has('a', {a: 'a', b: 'b', c: 'c'}): boolean);
(_.has('a')({a: 'a', b: 'b', c: 'c'}): boolean);
(_.has('a', null): boolean);
// $ExpectError
(_.has('a', {a: 'a', b: 'b', c: 'c'}): void);
// $ExpectError
(_.has('a')({a: 'a', b: 'b', c: 'c'}): void);
// $ExpectError
(_.has('a', null): void);
/* STRING */
/**
* _.camelCase
*/
(_.camelCase('a'): string);
(_.camelCase(null): string);
// $ExpectError
(_.camelCase('a'): void);
// $ExpectError
(_.camelCase(null): void);
/**
* _.capitalize
*/
(_.capitalize('a'): string);
(_.capitalize(null): string);
// $ExpectError
(_.capitalize('a'): void);
// $ExpectError
(_.capitalize(null): void);
/**
* _.padCharsStart
*/
(_.padCharsStart('a', 5, 'a'): string);
(_.padCharsStart('a', 5)('a'): string);
(_.padCharsStart('a')(5)('a'): string);
(_.padCharsStart('a', 5, null): string);
// $ExpectError
(_.padCharsStart('a', 5, 'a'): void);
// $ExpectError
(_.padCharsStart('a', 5)('a'): void);
// $ExpectError
(_.padCharsStart('a')(5)('a'): void);
// $ExpectError
(_.padCharsStart('a', 5, null): void);
// $ExpectError
(_.padCharsStart(null, 5, 'a'): string);
// $ExpectError
(_.padCharsStart('a', null, 'a'): string);
/**
* _.replace
*/
(_.replace('a', 'A', 'abc'): string);
(_.replace('a', 'A')('abc'): string);
(_.replace('a')('A')('abc'): string);
(_.replace(/a/, 'A', 'abc'): string);
(_.replace('a', 'A', null): string);
// $ExpectError
(_.replace('a', 'A', 'abc'): void);
// $ExpectError
(_.replace('a', 'A')('abc'): void);
// $ExpectError
(_.replace('a')('A')('abc'): void);
// $ExpectError
(_.replace(/a/, 'A', 'abc'): void);
// $ExpectError
(_.replace('a', 'A', null): void);
// $ExpectError
(_.replace(null, 'A', 'abc'): string);
// $ExpectError
(_.replace('a', null, 'abc'): string);
/**
* _.snakeCase
*/
(_.snakeCase('a'): string);
(_.snakeCase(null): string);
// $ExpectError
(_.snakeCase('a'): void);
// $ExpectError
(_.snakeCase(null): void);
/**
* _.split
*/
(_.split(' ', 'a b c'): Array<string>);
(_.split(' ')('a b c'): Array<string>);
(_.split(' ', null): Array<string>);
// $ExpectError
(_.split(' ', 'a b c'): Object);
// $ExpectError
(_.split(' ')('a b c'): Object);
// $ExpectError
(_.split(' ', null): Object);
// $ExpectError
(_.split(null, 'a b c'): Array<string>);
/**
* _.toString
*/
(_.toString(1): string);
(_.toString(true): string);
(_.toString(null): string);
/**
* _.toUpper
*/
(_.toUpper('a'): string);
(_.toUpper(null): string);
// $ExpectError
(_.toUpper('a'): void);
/**
* _.trim
*/
(_.trim('a'): string);
(_.trim(null): string);
// $ExpectError
(_.trim('a'): void);
/**
* _.truncate
*/
(_.truncate({}, 'a'): string);
(_.truncate({})('a'): string);
(_.truncate({}, null): string);
// $ExpectError
(_.truncate({}, 'a'): void);
// $ExpectError
(_.truncate({})('a'): void);
// $ExpectError
(_.truncate({}, null): void);
/**
* _.startsWith
*/
(_.startsWith('a', 'a'): boolean);
(_.startsWith('a')('a'): boolean);
(_.startsWith('a', null): boolean);
// $ExpectError
(_.startsWith('a', 'a'): void);
// $ExpectError
(_.startsWith('a')('a'): void);
// $ExpectError
(_.startsWith('a', null): void);
/* UTIL */
/**
* _.compose
*/
(_.compose(
() => 'f',
() => 'e',
() => 'd',
() => 'c',
() => 'b',
() => 'a',
): () => 'f');
(_.compose(() => 'e', () => 'd', () => 'c', () => 'b', () => 'a'): () => 'e');
(_.compose(() => 'd', () => 'c', () => 'b', () => 'a'): () => 'd');
(_.compose(() => 'c', () => 'b', () => 'a'): () => 'c');
(_.compose(() => 'b', () => 'a'): () => 'b');
(_.compose(() => 'a'): () => 'a');
(_.compose(
// $ExpectError
() => 'f',
() => 'e',
() => 'd',
() => 'c',
() => 'b',
() => 'a',
): () => 'g');
// $ExpectError
(_.compose(() => 'e', () => 'd', () => 'c', () => 'b', () => 'a'): () => 'f');
// $ExpectError
(_.compose(() => 'd', () => 'c', () => 'b', () => 'a'): () => 'e');
// $ExpectError
(_.compose(() => 'c', () => 'b', () => 'a'): () => 'd');
// $ExpectError
(_.compose(() => 'b', () => 'a'): () => 'c');
// $ExpectError
(_.compose(() => 'a'): () => 'b');
/**
* _.cond
*/
(_.cond([[(a: 'a') => a === 'a', (a: 'a') => 'b']]): (a: 'a') => 'b');
// $ExpectError
(_.cond([[(a: 'a') => a === 'a', (a: 'a') => 'b']]): (a: 'b') => 'b');
// $ExpectError
(_.cond([[(a: 'a') => a === 'a', (a: 'a') => 'b']]): (a: 'a') => 'c');
/**
* _.constant
*/
(_.constant('a'): () => 'a');
(_.constant(true): () => true);
// $ExpectError
(_.constant('a'): () => 'b');
// $ExpectError
(_.constant(true): () => false);
/**
* _.flow
*/
(_.flow(
() => 'a',
() => 'b',
() => 'c',
() => 'd',
() => 'e',
() => 'f',
): () => 'f');
(_.flow(() => 'a', () => 'b', () => 'c', () => 'd', () => 'e'): () => 'e');
(_.flow(() => 'a', () => 'b', () => 'c', () => 'd'): () => 'd');
(_.flow(() => 'a', () => 'b', () => 'c'): () => 'c');
(_.flow(() => 'a', () => 'b'): () => 'b');
(_.flow(() => 'a'): () => 'a');
(_.flow(
() => 'a',
() => 'b',
() => 'c',
() => 'd',
() => 'e',
// $ExpectError
() => 'f',
): () => 'g');
// $ExpectError
(_.flow(() => 'a', () => 'b', () => 'c', () => 'd', () => 'e'): () => 'f');
// $ExpectError
(_.flow(() => 'a', () => 'b', () => 'c', () => 'd'): () => 'e');
// $ExpectError
(_.flow(() => 'a', () => 'b', () => 'c'): () => 'd');
// $ExpectError
(_.flow(() => 'a', () => 'b'): () => 'c');
// $ExpectError
(_.flow(() => 'a'): () => 'b');
/**
* _.identity
*/
(_.identity('a'): 'a');
(_.identity(true): true);
// $ExpectError
(_.identity('a'): 'b');
// $ExpectError
(_.identity(true): false);
/**
* _.matches
*/
_.matches({a: 'a', b: 'b', c: 'c'});
// $ExpectError
_.matches('a');
// $ExpectError
_.matches([]);
/**
* _.noop
*/
(_.noop(): void);
/**
* _.stubTrue
*/
(_.stubTrue(): true);
// $ExpectError
(_.stubTrue(): false);
/**
* _.overEvery
*/
(_.overEvery([(a: 'a') => true]): (a: 'a') => boolean);
// $ExpectError
(_.overEvery([(a: 'a') => a]): (a: 'a') => boolean);
// $ExpectError
(_.overEvery([(a: 'a') => true]): (a: 'b') => boolean);
// $ExpectError
(_.overEvery([(a: 'a') => true]): (a: 'a') => 'a');
/**
* _.overSome
*/
(_.overSome([(a: 'a') => true]): (a: 'a') => boolean);
// $ExpectError
(_.overSome([(a: 'a') => a]): (a: 'a') => boolean);
// $ExpectError
(_.overSome([(a: 'a') => true]): (a: 'b') => boolean);
// $ExpectError
(_.overSome([(a: 'a') => true]): (a: 'a') => 'a');
/**
* _.range
*/
(_.range(0, 1): Array<number>);
(_.range(0)(1): Array<number>);
// $ExpectError
(_.range(0, 1): Array<void>);
// $ExpectError
(_.range(0)(1): Array<void>);
/**
* _.times
*/
(_.times(() => 'a', 1): Array<'a'>);
(_.times(() => 'a')(1): Array<'a'>);
// $ExpectError
(_.times(() => 'a', 1): Array<'b'>);
// $ExpectError
(_.times(() => 'a')(1): Array<'b'>);
|
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* This file was added automatically by CKEditor builder.
* You may re-use it at any time to build CKEditor again.
*
* If you would like to build CKEditor online again
* (for example to upgrade), visit one the following links:
*
* (1) http://ckeditor.com/builder
* Visit online builder to build CKEditor from scratch.
*
* (2) http://ckeditor.com/builder/13b5e7ae483a2ac02f22db181d10e412
* Visit online builder to build CKEditor, starting with the same setup as before.
*
* (3) http://ckeditor.com/builder/download/13b5e7ae483a2ac02f22db181d10e412
* Straight download link to the latest version of CKEditor (Optimized) with the same setup as before.
*
* NOTE:
* This file is not used by CKEditor, you may remove it.
* Changing this file will not change your CKEditor configuration.
*/
var CKBUILDER_CONFIG = {
skin: 'moono-lisa',
preset: 'basic',
ignore: [
'.bender',
'bender.js',
'bender-err.log',
'bender-out.log',
'dev',
'.DS_Store',
'.editorconfig',
'.gitattributes',
'.gitignore',
'gruntfile.js',
'.idea',
'.jscsrc',
'.jshintignore',
'.jshintrc',
'less',
'.mailmap',
'node_modules',
'package.json',
'README.md',
'tests'
],
plugins : {
'about' : 1,
'basicstyles' : 1,
'clipboard' : 1,
'enterkey' : 1,
'entities' : 1,
'floatingspace' : 1,
'indentlist' : 1,
'link' : 1,
'list' : 1,
'scayt' : 1,
'toolbar' : 1,
'undo' : 1,
'wysiwygarea' : 1
},
languages : {
'en' : 1
}
};
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';
class ArtistEdit extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentWillMount() {
this.props.findArtist(this.props.params.id);
}
componentWillReceiveProps({ artist }) {
if (artist) {
const { name, age, yearsActive, genre } = artist;
this.setState({ name, age, yearsActive, genre });
}
}
componentWillUpdate(nextProps) {
if (nextProps.params.id !== this.props.params.id) {
this.props.findArtist(nextProps.params.id);
}
}
componentWillUnmount() {
this.props.clearError();
}
onSubmit(event) {
event.preventDefault();
event.stopPropagation();
this.props.editArtist(this.props.params.id, this.state);
}
render() {
return (
<form onSubmit={this.onSubmit.bind(this)}>
<div className="input-field">
<input
value={this.state.name}
onChange={e => this.setState({ name: e.target.value })}
placeholder="Name"
/>
</div>
<div className="input-field">
<input
value={this.state.age}
onChange={e => this.setState({ age: e.target.value })}
placeholder="Age"
/>
</div>
<div className="input-field">
<input
value={this.state.yearsActive}
onChange={e => this.setState({ yearsActive: e.target.value })}
placeholder="Years Active"
/>
</div>
<div className="input-field">
<input
value={this.state.genre}
onChange={e => this.setState({ genre: e.target.value })}
placeholder="Genre"
/>
</div>
<div className="has-error">
{this.props.errorMessage}
</div>
<button className="btn">Submit</button>
</form>
);
}
}
const mapStateToProps = (state) => {
return {
artist: state.artists.artist,
errorMessage: state.errors
};
};
export default connect(mapStateToProps, actions)(ArtistEdit);
|
export const PI2 = 2.0 * Math.PI
export const HALF_PI = Math.PI * 0.5
export const DEG2RAD = Math.PI / 180.0
export const RAD2DEG = 180.0 / Math.PI
export const EPS = 10e-6
// Constants
/*
* Lineary interpolates between a->b, using n as a weight
*/
export const mix = (n, a, b) => a * (1 - n) + b * n
/*
* Linearly maps n from a->b to x->y
*/
export const map = (n, a, b, x, y) => x + (n - a) * (y - x) / (b - a)
/*
* Linearly maps n from a->b to 0-1
*/
export const normalize = (n, a, b) => map(n, a, b, 0, 1)
/*
* Clamp n within range a->b
*/
export const clamp = (n, a, b) => ((n < a) ? a : ((n > b) ? b : n))
/*
* Returns a pseudo-random floating point number within the range a->b, if b is not supplied it
* returns within the range 0-a
*/
export const random = (a, b) => ((b === undefined) ? Math.random() * a : Math.random() * (b - a) + a)
// export default {
// mix, map, normalize, clamp, random,
// PI2, HALF_PI, DEG2RAD, RAD2DEG, EPS }
|
import { SET_IS_CREATING_LINE_SPOT } from '../actions';
export default function IsCreatingLineSpot(state = false, action) {
switch (action.type) {
case SET_IS_CREATING_LINE_SPOT:
return action.payload;
default:
return state;
}
}
|
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { resolve } = require('path');
// Which files should be excluded from the compilation?
const exclude = /node_modules/;
const include = [];
// Loaders respond differently depending on the NODE_ENV environment variable
const p = process.env.NODE_ENV === 'production';
const fonts = {
test: /(\.svg|\.woff|\.woff2|\.[ot]tf|\.eot)$/,
loader: 'file-loader?name=[name].[ext]'
};
const css = {
loader: 'css-loader',
options: {
// Enable CSS Modules
modules: true,
importLoaders: 1,
// Mangle CSS class names
localIdentName: p ? '[hash:base64:5]' : '[name]__[local].[ext]', //'[name]__[local]__[hash:base64:5]',
// Minimize CSS for faster loading
minimize: p,
// Enable source maps if in production mode
sourceMap: p
}
};
const non_inliner = {
test: /\.(png|jpg|gif)$/,
include,
use: [{
loader: 'url-loader',
options: {
limit: 1,
/*1024 ,embed if the resource is 1kb or less*/
fallback: 'file-loader',
name: '[name].[ext]'
}
}]
};
const pic_inliner = {
test: /\.(png|jpg|gif)$/,
include,
use: [{
loader: 'url-loader',
options: {
limit: 1024, // embed if the resource is 1kb or less*/
name: p ? '[hash].[ext]' : '[name].[ext]'
}
}]
};
const postcss = {
loader: 'postcss-loader',
options: {
plugins: loader => [
require('postcss-cssnext')() // Autoprefixer
],
sourceMap: p // Enable source maps if in production
}
};
const sql = {
test: /\.sql/,
exclude,
include,
use: 'raw-loader'
}
const xml = {
test: /\.(anim|sheet)/,
exclude,
include,
use: 'xml-loader'
}
const scss = {
loader: 'sass-loader',
options: {
sourceMap: p // Enable scss source maps if in production,
}
};
const style = {
loader: 'style-loader',
options: {
sourceMap: p // Enable style source maps if in production
}
};
const styles = {
test: /\.(s[ca]|c)ss$/,
exclude,
include: [],
use: p ? // If we're in production, extract css, if not, inline css
ExtractTextPlugin.extract({
fallback: style,
use: [css, postcss, scss]
}) : [style, css, postcss, scss]
};
const ts = {
test: /\.tsx?$/,
exclude,
include: [],
use: {
loader: 'awesome-typescript-loader',
options: {
// Babel configuration
babelOptions: {
presets: [
["env", { loose: true, modules: false }],
"stage-0",
"react"
]
},
// Tells ATL to use Babel
useBabel: true,
// Cache output for quicker compilation
useCache: true
}
}
};
const tslint = {
enforce: 'pre',
test: /\.tsx?$/,
exclude,
include: [],
use: [{
loader: 'tslint-loader',
options: {
configFile: resolve('tslint.json'),
emitErrors: false,
failOnHint: false,
typeCheck: false,
fix: false,
tsConfigFile: resolve('tsconfig.json')
}
}]
};
module.exports = { sql, styles, ts, tslint, non_inliner, pic_inliner, xml, fonts };
|
require('../example-utils').listModuleAndTests(__dirname + '/foo.js', __filename);
var proxyquire = require('../../proxyquire')
, assert = require('assert')
, foo
;
// no overrides yet, so path.extname behaves normally
foo = proxyquire('./foo', __dirname, {});
assert.equal(foo.extnameAllCaps('file.txt'), '.TXT');
// override path.extname
foo = proxyquire('./foo', __dirname, {
path: { extname: function (file) { return 'Exterminate, exterminate the ' + file; } }
});
// path.extname now behaves as we told it to
assert.equal(foo.extnameAllCaps('file.txt'), 'EXTERMINATE, EXTERMINATE THE FILE.TXT');
// path.basename on the other hand still functions as before
assert.equal(foo.basenameAllCaps('/a/b/file.txt'), 'FILE.TXT');
console.log('*** All asserts passed ***');
|
(function(JsSIP) {
var Exceptions;
/**
* @namespace Exceptions
* @memberOf JsSIP
*/
Exceptions= {
/**
* Exception thrown when a valid parameter is given to the JsSIP.UA constructor.
* @class ConfigurationError
* @memberOf JsSIP.Exceptions
*/
ConfigurationError: (function(){
var exception = function(parameter, value) {
this.code = 1;
this.name = 'CONFIGURATION_ERROR';
this.parameter = parameter;
this.value = value;
this.message = (!this.value)? 'Missing parameter: '+ this.parameter : 'Invalid value '+ window.JSON.stringify(this.value) +' for parameter "'+ this.parameter +'"';
};
exception.prototype = new Error();
return exception;
}()),
InvalidStateError: (function(){
var exception = function(status) {
this.code = 2;
this.name = 'INVALID_STATE_ERROR';
this.status = status;
this.message = 'Invalid status: '+ status;
};
exception.prototype = new Error();
return exception;
}()),
NotSupportedError: (function(){
var exception = function(message) {
this.code = 3;
this.name = 'NOT_SUPPORTED_ERROR';
this.message = message;
};
exception.prototype = new Error();
return exception;
}()),
NotReadyError: (function(){
var exception = function(message) {
this.code = 4;
this.name = 'NOT_READY_ERROR';
this.message = message;
};
exception.prototype = new Error();
return exception;
}())
};
JsSIP.Exceptions = Exceptions;
}(JsSIP));
|
// http://jsbin.com/ozebIvu/2/edit
//////////////////////////////////
//ClipsJS
//////////////////////////////////
/**!
* MagnumJS - ClipsJS Template Factory v0.1
* https://github.com/magnumjs
*
* @description Fast simple Html template to javascript function cache
* Includes Staples.js
* https://github.com/magnumjs/staples.js/clips.js
* http://jsbin.com/ozebIvu/4/edit
* Copyright (c) 2013 Michael GLazer
* Released under the MIT license
* https://github.com/magnumjs/mag.js/blob/master/LICENSE
*
* Date: 2013-08-19T13:48Z
*/
'use strict';
(function ($, namespace, undefined) {
mag.clips = {};
})(jQuery, window.mag = window.mag || {});
(function ($) {
mag.clips.parse = function (id, data) {
this.cache = this.cache || {};
this.run = function (id, data) {
var $id = $('#' + id),
html, fun, ret;
$id.hide();
if (this.cache[id]) {
html = this.cache[id]['phtml'];
fun = this.cache[id]['fun'];
} else {
html = $id.html();
fun = this.tmpl(html);
this.cache[id] = {};
this.cache[id]['fun'] = fun;
this.cache[id]['ohtml'] = html;
}
this.fun = fun;
ret = this.loop(data);
if (ret == '') {
ret = this.fun(data);
ret = this.finder(ret, data);
}
this.cache[id]['phtml'] = ret;
$id.html(ret);
$id.show();
}
this.finder = function (out, data) {
for (var k in data) {
var p = 'class\=\"' + k + '\"\>';
var patt = new RegExp(p, 'gm');
out = out.replace(patt, p + data[k]);
}
return out;
}
this.loop = function (sdata) {
var ret = '';
var newobj = sdata;
for (var k in sdata) {
// array, string, function
if (Object.prototype.toString.call(sdata[k]) === '[object Array]') { // array
var newk = k.substring(0, k.length - 1);
for (var i in sdata[k]) {
var loopval = sdata[k][i];
newobj['index'] = i;
newobj[newk] = loopval;
var out = this.fun(newobj);
ret += this.finder(out, data);
}
delete sdata[newk];
delete sdata['index'];
} else {
}
}
return ret;
}
this.tmpl = function (str, /* optional to execute against or just returns a fun str */ data) {
var fn = new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
"with(obj){p.push('" +
str
.replace(/[\r\t\n]/g, " ")
.split("[[").join("\tp.push(")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("]]").join(");p.push('")
.split("\r").join("\\'") + "');}return p.join('');");
return data ? fn(data) : fn;
};
this.run(id, data);
};
/**
* @name Working example below
*
* @description
*/
// var data = {
// test: 'Yo!',
// users: [{
// name: 'm'
// }, {
// name: 'g'
// }],
// isOld: function () {
// return true;
// },
// other: {
// more: 'hmm'
// }
// };
// mag.clips.parse('map', data);
})(jQuery);
|
import React from 'react';
export default class ImgFigure extends React.Component {
// 构造函数
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
// 单击处理函数
handleClick(e) {
// 判断是否居中;居中就执行翻转操作;否则执行居中操作
if (this.props.arrange.isCenter) {
this.props.inverse();
}
else {
this.props.center();
}
e.preventDefault();
e.stopPropagation();
}
// 单个图片组件
render() {
var ImgFigureClassName = 'img-figure';
ImgFigureClassName += this.props.arrange.isInverse ? ' inverse' : '';
return (
<figure className={ImgFigureClassName} style={this.props.arrange.pos} onClick={this.handleClick}>
<img src={this.props.data.imageUrl} alt={this.props.data.title} />
<figcaption>
<h2 className="img-title">{this.props.data.title}</h2>
<div className="img-back">
<p>
{this.props.data.desc}
</p>
</div>
</figcaption>
</figure>
);
}
}
ImgFigure.defaultProps = {
};
|
//=============================================================================
// feature detection
//=============================================================================
ua = function() {
var ua = navigator.userAgent.toLowerCase(); // should avoid user agent sniffing... but sometimes you just gotta do what you gotta do
var key = ((ua.indexOf("opera") > -1) ? "opera" : null);
key = key || ((ua.indexOf("firefox") > -1) ? "firefox" : null);
key = key || ((ua.indexOf("chrome") > -1) ? "chrome" : null);
key = key || ((ua.indexOf("safari") > -1) ? "safari" : null);
key = key || ((ua.indexOf("msie") > -1) ? "ie" : null);
try {
var re = (key == "ie") ? "msie ([\\d\\.]*)" : key + "\\/([\\d\\.]*)"
var matches = ua.match(new RegExp(re, "i"));
var version = matches ? matches[1] : null;
} catch (e) {}
return {
full: ua,
name: key + (version ? " " + version : ""),
version: version,
major: version ? parseInt(version) : null,
is: {
firefox: (key == "firefox"),
chrome: (key == "chrome"),
safari: (key == "safari"),
opera: (key == "opera"),
ie: (key == "ie")
},
has: {
audio: AudioFX && AudioFX.enabled,
canvas: (document.createElement('canvas').getContext),
touch: ('ontouchstart' in window)
}
}
}();
//=============================================================================
// type detection
//=============================================================================
is = {
'string': function(obj) { return (typeof obj === 'string'); },
'number': function(obj) { return (typeof obj === 'number'); },
'bool': function(obj) { return (typeof obj === 'boolean'); },
'array': function(obj) { return (obj instanceof Array); },
'undefined': function(obj) { return (typeof obj === 'undefined'); },
'func': function(obj) { return (typeof obj === 'function'); },
'null': function(obj) { return (obj === null); },
'notNull': function(obj) { return (obj !== null); },
'invalid': function(obj) { return ( is['null'](obj) || is.undefined(obj)); },
'valid': function(obj) { return (!is['null'](obj) && !is.undefined(obj)); },
'emptyString': function(obj) { return (is.string(obj) && (obj.length == 0)); },
'nonEmptyString': function(obj) { return (is.string(obj) && (obj.length > 0)); },
'emptyArray': function(obj) { return (is.array(obj) && (obj.length == 0)); },
'nonEmptyArray': function(obj) { return (is.array(obj) && (obj.length > 0)); },
'document': function(obj) { return (obj === document); },
'window': function(obj) { return (obj === window); },
'element': function(obj) { return (obj instanceof HTMLElement); },
'event': function(obj) { return (obj instanceof Event); },
'link': function(obj) { return (is.element(obj) && (obj.tagName == 'A')); }
}
//=============================================================================
// type coersion
//=============================================================================
to = {
'bool': function(obj, def) { if (is.valid(obj)) return ((obj == 1) || (obj == true) || (obj == "1") || (obj == "y") || (obj == "Y") || (obj.toString().toLowerCase() == "true") || (obj.toString().toLowerCase() == 'yes')); else return (is.bool(def) ? def : false); },
'number': function(obj, def) { if (is.valid(obj)) { var x = parseFloat(obj); if (!isNaN(x)) return x; } return (is.number(def) ? def : 0); },
'string': function(obj, def) { if (is.valid(obj)) return obj.toString(); return (is.string(def) ? def : ''); }
}
//=============================================================================
//
// Compatibility for older browsers (compatibility: http://kangax.github.com/es5-compat-table/)
//
// Function.bind: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
// Object.create: http://javascript.crockford.com/prototypal.html
// Object.extend: (defacto standard like jquery $.extend or prototype's Object.extend)
// Class.create: create a simple javascript 'class' (a constructor function with a prototype and optional class methods)
//
//=============================================================================
if (!Function.prototype.bind) {
Function.prototype.bind = function(obj) {
var slice = [].slice,
args = slice.call(arguments, 1),
self = this,
nop = function () {},
bound = function () {
return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments)));
};
nop.prototype = self.prototype;
bound.prototype = new nop();
return bound;
};
}
if (!Object.create) {
Object.create = function(base) {
function F() {};
F.prototype = base;
return new F();
}
}
if (!Object.extend) {
Object.extend = function(destination, source) {
for (var property in source) {
if (source.hasOwnProperty(property))
destination[property] = source[property];
}
return destination;
};
}
var Class = {
create: function(prototype, extensions) {
var ctor = function() { if (this.initialize) return this.initialize.apply(this, arguments); }
ctor.prototype = prototype || {}; // instance methods
Object.extend(ctor, extensions || {}); // class methods
return ctor;
}
}
if (!window.requestAnimationFrame) {// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimationFrame = window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element) {
window.setTimeout(callback, 1000 / 60);
}
}
Game = {
run: function(gameFactory, cfg) {
document.addEventListener('DOMContentLoaded', function() {
window.game = gameFactory();
window.runner = new Game.Runner(window.game, cfg);
}, false);
},
//===========================================================================
// GAME RUNNER
//===========================================================================
Runner: Class.create({
initialize: function(game, cfg) {
this.game = game;
this.timer = null;
this.cfg = (cfg = Object.extend(cfg || {}, (game.cfg && game.cfg.runner) || {}));
this.fps = cfg.fps || 30;
this.dstep = 1.0 / cfg.fps;
this.frame = 0;
this.canvas = $(cfg.id || 'canvas');
this.bounds = this.canvas.getBoundingClientRect();
this.width = cfg.width || this.canvas.offsetWidth;
this.height = cfg.height || this.canvas.offsetHeight;
this.canvas = this.canvas;
this.canvas.width = this.width;
this.canvas.height = this.height;
this.ctx = this.canvas.getContext('2d');
this.infos = {update:0, draw:0, heapSize:0};
game.run(this);
if (to.bool(this.cfg.start))
this.start();
return this.game;
},
timestamp: function() { return new Date().getTime();
// return Date.now();//
},
start: function() {
// this.addEvents();
// this.resetStats();
if (this.cfg.manual)
return this.draw();
var timestamp = this.timestamp,
start, middle, end, last = timestamp(),
dt = 0.0, // time elapsed (seconds)
stopping = false, // flag for stopping game loop
self = this; // closure over this
var step = function() {
start = timestamp(); dt = self.update(dt + Math.min(1, (start - last)/1000.0)); // send dt as seconds, MAX of 1s (to avoid huge delta's when requestAnimationFrame put us in the background)
middle = timestamp(); self.draw();
end = timestamp();
self.updateStats(middle - start, end - middle);
last = start;
if (!stopping)
requestAnimationFrame(step);
//if (stopping)clearInterval(this.timer);
}
this.stop = function() {
stopping = true;
// clearInterval(this.timer);
}
step();
//this.timer = setInterval(step, 1000/this.fps );
},
update: function(dt) {
while (dt >= this.dstep) {
this.game.update(this.frame);
this.frame ++; //= this.frame + 1;
dt = dt - this.dstep;
}
return dt;
},
manual: function() {
if (this.cfg.manual) {
var start = this.timestamp(); this.update(this.dstep);
var middle = this.timestamp(); this.draw();
var end = this.timestamp();
this.updateStats(middle - start, end - middle);
}
},
draw: function() {
this.game.draw3D(this.frame);
/* this.ctx.save();
this.game.draw(this.ctx, this.frame);
this.ctx.restore();*/
// this.drawStats();
},
/* resetStats: function() {
if (this.cfg.stats) {
this.stats = new Stats();
this.stats.extra = { update: 0, draw: 0 };
this.stats.domElement.id = 'stats';
this.canvas.parentNode.appendChild(this.stats.domElement);
this.stats.domElement.appendChild($({
tag: 'div',
'class': 'extra',
'style': 'font-size: 8pt; position: absolute; top: -50px;',
html: "<span class='update'></span><br><span class='draw'></span>"
}));
this.stats.updateCounter = $(this.stats.domElement).down('div.extra span.update');
this.stats.drawCounter = $(this.stats.domElement).down('div.extra span.draw');
}
},*/
updateStats: function(update, draw) {
this.infos.update = update ? Math.max(1, update) : this.infos.update;
this.infos.draw = draw ? Math.max(1, draw) : this.infos.draw;
game.cfg.infos.update = Math.round( this.infos.update);
game.cfg.infos.draw = Math.round(this.infos.draw);
if(ua.is.chrome)
this.infos.heapSize = window.performance.memory.usedJSHeapSize * 9.54E-7;
game.cfg.infos.heapSize = Math.round(this.infos.heapSize);
/* if (this.cfg.stats) {
this.stats.update();
this.stats.extra.update = update ? Math.max(1, update) : this.stats.extra.update;
this.stats.extra.draw = draw ? Math.max(1, draw) : this.stats.extra.draw;
}*/
},
/* drawStats: function() {
if (this.cfg.stats) {
game.cfg.infos.update = Math.round(this.stats.extra.update);
game.cfg.infos.draw = Math.round(this.stats.extra.draw);
// this.stats.updateCounter.update("update: " + Math.round(this.stats.extra.update) + "ms");
// this.stats.drawCounter.update( "draw: " + Math.round(this.stats.extra.draw) + "ms");
}
},*/
/* getStat:function(){
if (this.cfg.stats){
var st ="game update: " + Math.round(this.stats.extra.update) + "ms" + "<br>game draw: " + Math.round(this.stats.extra.draw) + "ms";
return st
}
},*/
/*addEvents: function() {
var game = this.game;
if (game.onfocus) {
document.body.tabIndex = to.number(document.body.tabIndex, 0); // body needs tabIndex to recieve focus
$(document.body).on('focus', function(ev) { game.onfocus(ev); });
}
if (game.onclick) {
this.canvas.on('click', function(ev) { game.onclick(ev); });
}
if (game.onwheel) {
this.canvas.on(ua.is.firefox ? "DOMMouseScroll" : "mousewheel", function(ev) { game.onwheel(Game.Event.mouseWheelDelta(ev), ev); });
}
},*/
setSize: function(width, height) {
this.width = this.canvas.width = width;
this.height = this.canvas.height = height;
}
}),
//===========================================================================
// UTILS
//===========================================================================
qsValue: function(name, format) {
var pattern = name + "=(" + (format || "\\w+") + ")",
re = new RegExp(pattern),
match = re.exec(location.search);
return match ? match[1] : null;
},
qsNumber: function(name, def) {
var value = this.qsValue(name);
return value ? to.number(value, def) : null;
},
qsBool: function(name, def) {
return to.bool(this.qsValue(name), def);
},
storage: function() {
try {
return this.localStorage = this.localStorage || window.localStorage || {};
}
catch(e) { // IE localStorage throws exceptions when using non-standard port (e.g. during development)
return this.localStorage = {};
}
},
createCanvas: function(width, height) {
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas;
},
renderToCanvas: function(width, height, render, canvas) { // http://kaioa.com/node/103
canvas = canvas || this.createCanvas(width, height, canvas);
render(canvas.getContext('2d'));
return canvas;
},
parseImage: function(image, callback) {
var tx, ty, index, pixel,
tw = image.width,
th = image.height,
canvas = Game.renderToCanvas(tw, th, function(ctx) { ctx.drawImage(image, 0, 0); }),
ctx = canvas.getContext('2d'),
data = ctx.getImageData(0, 0, tw, th).data,
helpers = {
valid: function(tx,ty) { return (tx >= 0) && (tx < tw) && (ty >= 0) && (ty < th); },
index: function(tx,ty) { return (tx + (ty*tw)) * 4; },
pixel: function(tx,ty) { var i = this.index(tx,ty); return this.valid(tx,ty) ? (data[i]<<16)+(data[i+1]<<8)+(data[i+2]) : null; }
}
for(ty = 0 ; ty < th ; ty++)
for(tx = 0 ; tx < tw ; tx++)
callback(tx, ty, helpers.pixel(tx,ty), helpers);
},
createImage: function(url, options) {
options = options || {};
var image = $({tag: 'img'});
if (options.onload)
image.on('load', options.onload);
image.src = url;
return image;
},
loadResources: function(images, sounds, callback) { /* load multiple images and sounds and callback when ALL have finished loading */
images = images || [];
sounds = sounds || [];
var count = images.length + sounds.length;
var resources = { images: {}, sounds: {} };
if (count == 0) {
callback(resources);
}
else {
var done = false;
var loaded = function() {
if (!done) {
done = true; // ensure only called once, either by onload, or by setTimeout
callback(resources);
}
}
var onload = function() {
if (--count == 0)
loaded();
};
for(var n = 0 ; n < images.length ; n++) {
var image = images[n];
image = is.string(image) ? { id: image, url: image } : image;
resources.images[image.id] = Game.createImage(image.url, { onload: onload });
}
for(var n = 0 ; n < sounds.length ; n++) {
var sound = sounds[n];
sound = is.string(sound) ? { id: sound, name: sound } : sound;
resources.sounds[sound.id] = AudioFX(sound.name, sound, onload);
}
setTimeout(loaded, 15000); // need a timeout because HTML5 audio canplay event is VERY VERY FLAKEY (especially on slow connections)
}
}
};
Game.PubSub = {
enable: function(cfg, on) {
var n, max;
on.subscribe = function(event, callback) {
this.subscribers = this.subscribers || {};
this.subscribers[event] = this.subscribers[event] || [];
this.subscribers[event].push(callback);
},
on.publish = function(event) {
if (this.subscribers && this.subscribers[event]) {
var subs = this.subscribers[event],
args = [].slice.call(arguments, 1),
n, max;
for(n = 0, max = subs.length ; n < max ; n++)
subs[n].apply(on, args);
}
}
if (cfg) {
for(n = 0, max = cfg.length ; n < max ; n++)
on.subscribe(cfg[n].event, cfg[n].action);
}
}
}
//=============================================================================
// Minimal DOM Library ($)
//=============================================================================
Game.Element = function() {
var query = function(selector, context) {
if (is.array(context))
return Sizzle.matches(selector, context);
else
return Sizzle(selector, context);
};
var extend = function(obj) {
if (is.array(obj)) {
for(var n = 0, l = obj.length ; n < l ; n++)
obj[n] = extend(obj[n]);
}
else if (!obj._extended) {
Object.extend(obj, Game.Element.instanceMethods);
}
return obj;
};
var on = function(ele, type, fn, capture) { ele.addEventListener(type, fn, capture); };
var un = function(ele, type, fn, capture) { ele.removeEventListener(type, fn, capture); };
var create = function(attributes) {
var ele = document.createElement(attributes.tag);
for (var name in attributes) {
if (attributes.hasOwnProperty(name) && is.valid(attributes[name])) {
switch(name) {
case 'tag' : break;
case 'html' : ele.innerHTML = attributes[name]; break;
case 'text' : ele.appendChild(document.createTextNode(attributes[name])); break;
case 'dom' :
attributes[name] = is.array(attributes[name]) ? attributes[name] : [attributes[name]];
for (var n = 0 ; n < attributes[name].length ; n++)
ele.appendChild(attributes[name][n]);
break;
case 'class':
case 'klass':
case 'className':
ele.className = attributes[name];
break;
case 'on':
for(var ename in attributes[name])
on(ele, ename, attributes[name][ename]);
break;
default:
ele.setAttribute(name, attributes[name]);
break;
}
}
}
return ele;
};
return {
all: function(selector, context) {
return extend(query(selector, context));
},
get: function(obj, context) {
if (is.string(obj))
return extend(query("#" + obj, context)[0]);
else if (is.element(obj) || is.window(obj) || is.document(obj))
return extend(obj);
else if (is.event(obj))
return extend(obj.target || obj.srcElement);
else if ((typeof obj == 'object') && obj.tag)
return extend(create(obj));
else
throw "not an appropriate type for DOM wrapping: " + ele;
},
instanceMethods: {
_extended: true,
on: function(type, fn, capture) { on(this, type, fn, capture); return this; },
un: function(type, fn, capture) { un(this, type, fn, capture); return this; },
showIf: function(on) { if (on) this.show(); else this.hide(); },
show: function() { this.style.display = '' },
hide: function() { this.style.display = 'none'; },
visible: function() { return (this.style.display != 'none') && !this.fading; },
fade: function(amount) { this.style.opacity = amount; },
relations: function(property, includeSelf) {
var result = includeSelf ? [this] : [], ele = this;
while(ele = ele[property])
if (ele.nodeType == 1)
result.push(ele);
return extend(result);
},
parent: function() { return extend(this.parentNode); },
ancestors: function(includeSelf) { return this.relations('parentNode', includeSelf); },
previousSiblings: function() { return this.relations('previousSibling'); },
nextSiblings: function() { return this.relations('nextSibling'); },
select: function(selector) { return Game.Element.all(selector, this); },
down: function(selector) { return Game.Element.all(selector, this)[0]; },
up: function(selector, includeSelf) { return Game.Element.all(selector, this.ancestors(includeSelf))[0]; },
prev: function(selector) { return Game.Element.all(selector, this.previousSiblings())[0]; },
next: function(selector) { return Game.Element.all(selector, this.nextSiblings())[0]; },
remove: function() {
if (this.parentNode)
this.parentNode.removeChild(this);
return this;
},
removeChildren: function() { // NOTE: can't use :clear because its in DOM level-1 and IE bitches if we try to provide our own
while (this.childNodes.length > 0)
this.removeChild(this.childNodes[0]);
return this;
},
update: function(content) {
this.innerHTML = "";
this.append(content);
return this;
},
append: function(content) {
if (is.string(content))
this.innerHTML += content;
else if (is.array(content))
for(var n = 0 ; n < content.length ; n++)
this.append(content[n]);
else
this.appendChild(Game.Element.get(content));
},
setClassName: function(name) { this.className = name; },
hasClassName: function(name) { return (new RegExp("(^|\s*)" + name + "(\s*|$)")).test(this.className) },
addClassName: function(name) { this.toggleClassName(name, true); },
removeClassName: function(name) { this.toggleClassName(name, false); },
toggleClassName: function(name, on) {
var classes = this.className.split(' ');
var n = classes.indexOf(name);
on = (typeof on == 'undefined') ? (n < 0) : on;
if (on && (n < 0))
classes.push(name);
else if (!on && (n >= 0))
classes.splice(n, 1);
this.className = classes.join(' ');
},
fadeout: function(options) {
options = options || {};
this.cancelFade();
this.fading = Animator.apply(this, 'opacity: 0', { duration: options.duration, onComplete: function() {
this.hide();
this.fading = null;
this.style.opacity = is.ie ? 1 : null; /* clear opacity after hiding, but IE doesn't allow clear so set to 1.0 for IE */
if (options.onComplete)
options.onComplete();
}.bind(this) });
this.fading.play();
},
fadein: function(options) {
options = options || {};
this.cancelFade();
this.style.opacity = 0;
this.show();
this.fading = Animator.apply(this, 'opacity: 1', { duration: options.duration, onComplete: function() {
this.fading = null;
this.style.opacity = is.ie ? 1 : null; /* clear opacity after hiding, but IE doesn't allow clear so set to 1.0 for IE */
if (options.onComplete)
options.onComplete();
}.bind(this) });
this.fading.play();
},
cancelFade: function() {
if (this.fading) {
this.fading.stop();
delete this.fading;
}
}
}
};
}();
$ = Game.Element.get;
$$ = Game.Element.all;
Game.Event = {
stop: function(ev) {
ev.preventDefault();
ev.cancelBubble = true;
//ev.returnValue = false;
//ev.preventDefault();
return false;
}//,
/*canvasPos: function(ev, canvas) {
var bbox = canvas.getBoundingClientRect(),
x = (ev.clientX - bbox.left) * (canvas.width / bbox.width),
y = (ev.clientY - bbox.top) * (canvas.height / bbox.height);
return { x: x, y: y };
},
mouseWheelDelta: function(ev) {
if (is.valid(ev.wheelDelta))
return ev.wheelDelta/120;
else if (is.valid(ev.detail))
return -ev.detail/3;
else
return 0;
}*/
}
Game.Key = {
BACKSPACE: 8,
TAB: 9,
RETURN: 13,
ESC: 27,
SPACE: 32,
END: 35,
HOME: 36,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
PAGEUP: 33,
PAGEDOWN: 34,
INSERT: 45,
DELETE: 46,
ZERO: 48, ONE: 49, TWO: 50, THREE: 51, FOUR: 52, FIVE: 53, SIX: 54, SEVEN: 55, EIGHT: 56, NINE: 57,
A: 65, B: 66, C: 67, D: 68, E: 69, F: 70, G: 71, H: 72, I: 73, J: 74, K: 75, L: 76, M: 77, N: 78, O: 79, P: 80, Q: 81, R: 82, S: 83, T: 84, U: 85, V: 86, W: 87, X: 88, Y: 89, Z: 90,
TILDA: 192,
map: function(map, context, cfg) {
cfg = cfg || {};
var ele = $(cfg.ele || document);
var onkey = function(ev, keyCode, mode) {
var n, k, i;
if ((ele === document) || ele.visible()) {
for(n = 0 ; n < map.length ; ++n) {
k = map[n];
k.mode = k.mode || 'up';
if (Game.Key.match(k, keyCode, mode, context)) {
k.action.call(context, keyCode, ev.shiftKey);
return Game.Event.stop(ev);
}
}
}
};
ele.on('keydown', function(ev) { return onkey(ev, ev.keyCode, 'down'); });
ele.on('keyup', function(ev) { return onkey(ev, ev.keyCode, 'up'); });
},
match: function(map, keyCode, mode, context) {
if (map.mode === mode) {
if (!map.state || !context || (map.state === context.current) || (is.array(map.state) && map.state.indexOf(context.current) >= 0)) {
if ((map.key === keyCode) || (map.keys && (map.keys.indexOf(keyCode) >= 0))) {
return true;
}
}
}
return false;
}
};
Game.Math = {
minmax: function(x, min, max) {
return Math.max(min, Math.min(max, x));
},
random: function(min, max) {
return (min + (Math.random() * (max - min)));
},
randomInt: function(min, max) {
return Math.round(Game.Math.random(min, max));
},
randomChoice: function(choices) {
return choices[Math.round(Game.Math.random(0, choices.length-1))];
},
randomBool: function() {
return Game.randomChoice([true, false]);
},
between: function(x, from, to) {
return (is.valid(x) && (from <= x) && (x <= to));
},
overlap: function(x1, y1, w1, h1, x2, y2, w2, h2) {
return !(((x1 + w1 - 1) < x2) ||
((x2 + w2 - 1) < x1) ||
((y1 + h1 - 1) < y2) ||
((y2 + h2 - 1) < y1))
}
}
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import Main from './app/components/Main';
class T13 extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<Main />
);
}
};
AppRegistry.registerComponent('t13', () => T13);
|
module.exports = function ( grunt ) {
/**
* Load required Grunt tasks. These are installed based on the versions listed
* in `package.json` when you do `npm install` in this directory.
*/
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-open');
grunt.loadNpmTasks('grunt-conventional-changelog');
grunt.loadNpmTasks('grunt-bump');
grunt.loadNpmTasks('grunt-ng-annotate');
grunt.loadNpmTasks('grunt-html2js');
/**
* Load in our build configuration file.
*/
var userConfig = require( './build.config.js' );
/**
* This is the configuration object Grunt uses to give each plugin its
* instructions.
*/
var taskConfig = {
/**
* We read in our `package.json` file so we can access the package name and
* version. It's already there, so we don't repeat ourselves here.
*/
pkg: grunt.file.readJSON("package.json"),
/**
* The banner is the comment that is placed at the top of our compiled
* source files. It is first processed as a Grunt template, where the `<%=`
* pairs are evaluated based on this very configuration object.
*/
meta: {
banner:
'/**\n' +
' * <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>\n' +
' * <%= pkg.homepage %>\n' +
' *\n' +
' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' +
' * Licensed <%= pkg.licenses.type %> <<%= pkg.licenses.url %>>\n' +
' */\n'
},
/**
* Creates a changelog on a new version.
*/
changelog: {
options: {
dest: 'CHANGELOG.md',
template: 'changelog.tpl'
}
},
/**
* Increments the version number, etc.
*/
bump: {
options: {
files: [
"package.json",
"bower.json"
],
commit: false,
commitMessage: 'chore(release): v%VERSION%',
commitFiles: [
"package.json",
"client/bower.json"
],
createTag: false,
tagName: 'v%VERSION%',
tagMessage: 'Version %VERSION%',
push: false,
pushTo: 'origin'
}
},
/**
* The directories to delete when `grunt clean` is executed.
*/
clean: [
'<%= build_dir %>',
'<%= compile_dir %>'
],
/**
* The `copy` task just copies files from A to B. We use it here to copy
* our project assets (images, fonts, etc.) and javascripts into
* `build_dir`, and then to copy the assets to `compile_dir`.
*/
copy: {
build_app_assets: {
files: [
{
src: [ '**' ],
dest: '<%= build_dir %>/assets/',
cwd: 'src/assets',
expand: true
}
]
},
build_vendor_assets: {
files: [
{
src: [ '<%= vendor_files.assets %>' ],
dest: '<%= build_dir %>/assets/',
cwd: '.',
expand: true,
flatten: true
}
]
},
build_appjs: {
files: [
{
src: [ '<%= app_files.js %>' ],
dest: '<%= build_dir %>/',
cwd: '.',
expand: true
}
]
},
build_vendorjs: {
files: [
{
src: [ '<%= vendor_files.js %>' ],
dest: '<%= build_dir %>/',
cwd: '.',
expand: true
}
]
},
build_vendorcss: {
files: [
{
src: [ '<%= vendor_files.css %>' ],
dest: '<%= build_dir %>/',
cwd: '.',
expand: true
}
]
},
compile_assets: {
files: [
{
src: [ '**' ],
dest: '<%= compile_dir %>/assets',
cwd: '<%= build_dir %>/assets',
expand: true
},
{
src: [ '<%= vendor_files.css %>' ],
dest: '<%= compile_dir %>/',
cwd: '.',
expand: true
}
]
}
},
/**
* `grunt concat` concatenates multiple source files into a single file.
*/
concat: {
/**
* The `build_css` target concatenates compiled CSS and vendor CSS
* together.
*/
build_css: {
src: [
'<%= vendor_files.css %>',
'<%= build_dir %>/assets/<%= pkg.name %>-<%= pkg.version %>.css'
],
dest: '<%= build_dir %>/assets/<%= pkg.name %>-<%= pkg.version %>.css'
},
/**
* The `compile_js` target is the concatenation of our application source
* code and all specified vendor source code into a single file.
*/
compile_js: {
options: {
banner: '<%= meta.banner %>'
},
src: [
'<%= vendor_files.js %>',
'module.prefix',
'<%= build_dir %>/src/**/*.js',
'<%= html2js.app.dest %>',
'<%= html2js.common.dest %>',
'module.suffix'
],
dest: '<%= compile_dir %>/assets/<%= pkg.name %>-<%= pkg.version %>.js'
}
},
/**
* `ngAnnotate` annotates the sources before minifying. That is, it allows us
* to code without the array syntax.
*/
ngAnnotate: {
compile: {
files: [
{
src: [ '<%= app_files.js %>' ],
cwd: '<%= build_dir %>',
dest: '<%= build_dir %>',
expand: true
}
]
}
},
/**
* Minify the sources!
*/
uglify: {
compile: {
options: {
banner: '<%= meta.banner %>'
},
files: {
'<%= concat.compile_js.dest %>': '<%= concat.compile_js.dest %>'
}
}
},
/**
* `grunt-contrib-less` handles our LESS compilation and uglification automatically.
* Only our `main.less` file is included in compilation; all other files
* must be imported from this file.
*/
less: {
build: {
files: {
'<%= build_dir %>/assets/<%= pkg.name %>-<%= pkg.version %>.css': '<%= app_files.less %>'
}
},
compile: {
files: {
'<%= build_dir %>/assets/<%= pkg.name %>-<%= pkg.version %>.css': '<%= app_files.less %>'
},
options: {
cleancss: true,
compress: true
}
}
},
/**
* `jshint` defines the rules of our linter as well as which files we
* should check. This file, all javascript sources, and all our unit tests
* are linted based on the policies listed in `options`. But we can also
* specify exclusionary patterns by prefixing them with an exclamation
* point (!); this is useful when code comes from a third party but is
* nonetheless inside `src/`.
*/
jshint: {
src: [
'<%= app_files.js %>'
],
test: [
'<%= app_files.jsunit %>'
],
gruntfile: [
'Gruntfile.js'
],
options: {
curly: true,
immed: true,
newcap: true,
noarg: true,
sub: true,
boss: true,
eqnull: true
},
globals: {}
},
/**
* HTML2JS is a Grunt plugin that takes all of your template files and
* places them into JavaScript files as strings that are added to
* AngularJS's template cache. This means that the templates too become
* part of the initial payload as one JavaScript file. Neat!
*/
html2js: {
/**
* These are the templates from `src/app`.
*/
app: {
options: {
base: 'src/app'
},
src: [ '<%= app_files.atpl %>' ],
dest: '<%= build_dir %>/templates-app.js'
},
/**
* These are the templates from `src/common`.
*/
common: {
options: {
base: 'src/common'
},
src: [ '<%= app_files.ctpl %>' ],
dest: '<%= build_dir %>/templates-common.js'
}
},
/**
* The `index` task compiles the `index.html` file as a Grunt template. CSS
* and JS files co-exist here but they get split apart later.
*/
index: {
/**
* During development, we don't want to have wait for compilation,
* concatenation, minification, etc. So to avoid these steps, we simply
* add all script files directly to the `<head>` of `index.html`. The
* `src` property contains the list of included files.
*/
build: {
dir: '<%= build_dir %>',
src: [
'<%= vendor_files.js %>',
'<%= build_dir %>/src/**/*.js',
'<%= html2js.common.dest %>',
'<%= html2js.app.dest %>',
'<%= vendor_files.css %>',
'<%= build_dir %>/assets/<%= pkg.name %>-<%= pkg.version %>.css'
]
},
/**
* When it is time to have a completely compiled application, we can
* alter the above to include only a single JavaScript and a single CSS
* file. Now we're back!
*/
compile: {
dir: '<%= compile_dir %>',
src: [
'<%= concat.compile_js.dest %>',
'<%= vendor_files.css %>',
'<%= build_dir %>/assets/<%= pkg.name %>-<%= pkg.version %>.css'
]
}
},
/**
* And for rapid development, we have a watch set up that checks to see if
* any of the files listed below change, and then to execute the listed
* tasks when they do. This just saves us from having to type "grunt" into
* the command-line every time we want to see what we're working on; we can
* instead just leave "grunt watch" running in a background terminal. Set it
* and forget it, as Ron Popeil used to tell us.
*
* But we don't need the same thing to happen for all the files.
*/
delta: {
/**
* By default, we want the Live Reload to work for all tasks; this is
* overridden in some tasks (like this file) where browser resources are
* unaffected. It runs by default on port 35729, which your browser
* plugin should auto-detect.
*/
options: {
livereload: true
},
/**
* When the Gruntfile changes, we just want to lint it. In fact, when
* your Gruntfile changes, it will automatically be reloaded!
*/
gruntfile: {
files: 'Gruntfile.js',
tasks: [ 'jshint:gruntfile' ],
options: {
livereload: false
}
},
/**
* When our JavaScript source files change, we want to run lint them and
* run our unit tests.
*/
jssrc: {
files: [
'<%= app_files.js %>'
],
tasks: [ 'jshint:src', 'copy:build_appjs' ]
},
/**
* When assets are changed, copy them. Note that this will *not* copy new
* files, so this is probably not very useful.
*/
assets: {
files: [
'src/assets/**/*'
],
tasks: [ 'copy:build_app_assets', 'copy:build_vendor_assets' ]
},
/**
* When index.html changes, we need to compile it.
*/
html: {
files: [ '<%= app_files.html %>' ],
tasks: [ 'index:build' ]
},
/**
* When our templates change, we only rewrite the template cache.
*/
tpls: {
files: [
'<%= app_files.atpl %>',
'<%= app_files.ctpl %>'
],
tasks: [ 'html2js' ]
},
/**
* When the CSS files change, we need to compile and minify them.
*/
less: {
files: [ 'src/**/*.less' ],
tasks: [ 'less:build' ]
},
/**
* When a JavaScript unit test file changes, we only want to lint it and
* run the unit tests. We don't want to do any live reloading.
*/
jsunit: {
files: [
'<%= app_files.jsunit %>'
],
tasks: [ 'jshint:test' ],
options: {
livereload: false
}
}
},
connect: {
server: {
options: {
port: 8888,
base: 'build'
}
}
},
open: {
dev: {
path: 'http://localhost:8888'
}
}
};
grunt.initConfig( grunt.util._.extend( taskConfig, userConfig ) );
/**
* In order to make it safe to just compile or copy *only* what was changed,
* we need to ensure we are starting from a clean, fresh build. So we rename
* the `watch` task to `delta` (that's why the configuration var above is
* `delta`) and then add a new task called `watch` that does a clean build
* before watching for changes.
*/
grunt.renameTask( 'watch', 'delta' );
grunt.registerTask( 'watch', [ 'build', 'connect', 'open:dev', 'delta' ] );
/**
* The default task is to build and compile.
*/
grunt.registerTask( 'default', [ 'build', 'compile' ] );
/**
* The `build` task gets your app ready to run for development and testing.
*/
grunt.registerTask( 'build', [
'clean', 'html2js', 'jshint', 'less:build',
'concat:build_css', 'copy:build_app_assets', 'copy:build_vendor_assets',
'copy:build_appjs', 'copy:build_vendorjs', 'copy:build_vendorcss', 'index:build' ]);
/**
* The `compile` task gets your app ready for deployment by concatenating and
* minifying your code.
*/
grunt.registerTask( 'compile', [
'less:compile', 'copy:compile_assets', 'ngAnnotate', 'concat:compile_js', 'uglify', 'index:compile'
]);
/**
* A utility function to get all app JavaScript sources.
*/
function filterForJS ( files ) {
return files.filter( function ( file ) {
return file.match( /\.js$/ );
});
}
/**
* A utility function to get all app CSS sources.
*/
function filterForCSS ( files ) {
return files.filter( function ( file ) {
return file.match( /\.css$/ );
});
}
/**
* The index.html template includes the stylesheet and javascript sources
* based on dynamic names calculated in this Gruntfile. This task assembles
* the list into variables for the template to use and then runs the
* compilation.
*/
grunt.registerMultiTask( 'index', 'Process index.html template', function () {
var dirRE = new RegExp( '^('+grunt.config('build_dir')+'|'+grunt.config('compile_dir')+')\/', 'g' );
var jsFiles = filterForJS( this.filesSrc ).map( function ( file ) {
return file.replace( dirRE, '' );
});
var cssFiles = filterForCSS( this.filesSrc ).map( function ( file ) {
return file.replace( dirRE, '' );
});
grunt.file.copy('src/index.html', this.data.dir + '/index.html', {
process: function ( contents, path ) {
return grunt.template.process( contents, {
data: {
scripts: jsFiles,
styles: cssFiles,
version: grunt.config( 'pkg.version' )
}
});
}
});
});
};
|
(function() {
/*************************************************************************************/
var ASTHelper = Firecrow.ASTHelper;
var Command = Firecrow.N_Interpreter.Command;
var ValueTypeHelper = Firecrow.ValueTypeHelper;
var CommandGenerator = Firecrow.N_Interpreter.CommandGenerator =
{
generateCommands: function(program)
{
var executionCommands = [];
var declarationCommands = [];
ASTHelper.traverseDirectSourceElements
(
program,
function(sourceElement)
{
ValueTypeHelper.pushAll(declarationCommands, CommandGenerator.generateDeclarationCommands(sourceElement));
},
true
);
ASTHelper.traverseDirectSourceElements
(
program,
function(sourceElement)
{
ValueTypeHelper.pushAll(executionCommands, CommandGenerator.generateExecutionCommands(sourceElement, null));
},
false
);
return ValueTypeHelper.concatArray(declarationCommands, executionCommands);
},
generateEvalCommands: function(callExpression, programAST)
{
var startEvalCommand = new Command(callExpression, Command.COMMAND_TYPE.StartEval, null);
var evalCommands = [startEvalCommand];
ValueTypeHelper.pushAll(evalCommands, this.generateCommands(programAST));
var finishEvalCommand = new Command(callExpression, Command.COMMAND_TYPE.FinishEval, null);
evalCommands.push(finishEvalCommand);
finishEvalCommand.startCommand = startEvalCommand;
return evalCommands;
},
generateDeclarationCommands: function(sourceElement, parentFunctionCommand)
{
var declarationCommands = [];
var CommandType = Command.COMMAND_TYPE;
if(ASTHelper.isVariableDeclaration(sourceElement))
{
sourceElement.declarations.forEach(function(variableDeclarator)
{
declarationCommands.push(new Command(variableDeclarator, CommandType.DeclareVariable, parentFunctionCommand));
});
}
else if (ASTHelper.isFunctionDeclaration(sourceElement))
{
declarationCommands.push(new Command(sourceElement, CommandType.DeclareFunction, parentFunctionCommand));
}
else if (ASTHelper.isForStatement(sourceElement))
{
if(ASTHelper.isVariableDeclaration(sourceElement.init))
{
sourceElement.init.declarations.forEach(function(variableDeclarator)
{
declarationCommands.push(new Command(variableDeclarator, CommandType.DeclareVariable, parentFunctionCommand));
});
}
}
else if(ASTHelper.isForInStatement(sourceElement))
{
if(ASTHelper.isVariableDeclaration(sourceElement.left))
{
sourceElement.left.declarations.forEach(function(variableDeclarator)
{
declarationCommands.push(new Command(variableDeclarator, CommandType.DeclareVariable, parentFunctionCommand));
});
}
}
return declarationCommands;
},
generateExecutionCommands: function(sourceElement, parentFunctionCommand)
{
if (ASTHelper.isExpressionStatement(sourceElement)) { return this.generateExpressionStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isBlockStatement(sourceElement)) { return this.generateBlockStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isVariableDeclaration(sourceElement)) { return this.generateVariableDeclarationExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isWhileStatement(sourceElement)) { return this.generateWhileStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isDoWhileStatement(sourceElement)) { return this.generateDoWhileStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isForStatement(sourceElement)) { return this.generateForStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isForInStatement(sourceElement)) { return this.generateForInStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isIfStatement(sourceElement)) { return this.generateIfStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isReturnStatement(sourceElement)) { return this.generateReturnStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isWithStatement(sourceElement)) { return this.generateWithStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isSwitchStatement(sourceElement)) { return this.generateSwitchStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isBreakStatement(sourceElement)) { return this.generateBreakStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isContinueStatement(sourceElement)) { return this.generateContinueStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isTryStatement(sourceElement)) { return this.generateTryStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isThrowStatement(sourceElement)) { return this.generateThrowStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isLetStatement(sourceElement)) { return this.generateLetStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isLabeledStatement(sourceElement)) { return this.generateLabeledStatementExecutionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isFunctionDeclaration(sourceElement)) { return []; }
else if (ASTHelper.isEmptyStatement(sourceElement)) { return []; }
else { this.notifyError("Unhandled source element when generating execution command: " + sourceElement.type); return []; }
},
generateExpressionStatementExecutionCommands: function (sourceElement, parentFunctionCommand)
{
return this.generateExpressionCommands(sourceElement.expression, parentFunctionCommand);
},
generateBlockStatementExecutionCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
var body = sourceElement.body;
for(var i = 0, length = body.length; i < length; i++)
{
ValueTypeHelper.pushAll(commands, this.generateExecutionCommands(body[i], parentFunctionCommand))
}
return commands;
},
generateVariableDeclarationExecutionCommands: function (sourceElement, parentFunctionCommand)
{
var commands = [];
var declarations = sourceElement.declarations;
for(var i = 0; i < declarations.length; i++)
{
var variableDeclarator = declarations[i];
if(variableDeclarator.init != null)
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(variableDeclarator.init, parentFunctionCommand));
commands.push(Command.createAssignmentCommand(variableDeclarator, parentFunctionCommand));
}
}
return commands;
},
generateWhileStatementExecutionCommands: function (sourceElement, parentFunctionCommand)
{
var commands = [];
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.test, parentFunctionCommand));
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.WhileStatement, parentFunctionCommand));
return commands;
},
generateDoWhileStatementExecutionCommands: function (sourceElement, parentFunctionCommand)
{
var commands = [];
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.StartDoWhileStatement, parentFunctionCommand))
ValueTypeHelper.pushAll(commands, this.generateExecutionCommands(sourceElement.body, parentFunctionCommand));
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.test, parentFunctionCommand));
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.DoWhileStatement, parentFunctionCommand));
return commands;
},
generateForStatementExecutionCommands: function (sourceElement, parentFunctionCommand)
{
var commands = [];
if(sourceElement.init != null)
{
if(ASTHelper.isVariableDeclaration(sourceElement.init))
{
ValueTypeHelper.pushAll(commands, this.generateVariableDeclarationExecutionCommands(sourceElement.init, parentFunctionCommand));
}
else if (ASTHelper.isExpression(sourceElement.init))
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.init, parentFunctionCommand));
}
}
if(sourceElement.test != null)
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.test, parentFunctionCommand));
}
var forStatementCommand = new Command(sourceElement, Command.COMMAND_TYPE.ForStatement, parentFunctionCommand);
forStatementCommand.isFirstLoopExecution = true;
commands.push(forStatementCommand);
return commands;
},
generateForInStatementExecutionCommands: function (sourceElement, parentFunctionCommand)
{
var commands = [];
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.right, parentFunctionCommand));
commands.push(Command.createForInWhereCommand(sourceElement, undefined, parentFunctionCommand));
return commands;
},
generateIfStatementExecutionCommands: function (sourceElement, parentFunctionCommand)
{
var commands = [];
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.test, parentFunctionCommand));
var ifStatementCommand = new Command(sourceElement, Command.COMMAND_TYPE.IfStatement, parentFunctionCommand);
var endIfCommand = new Command(ifStatementCommand.codeConstruct, Command.COMMAND_TYPE.EndIf, parentFunctionCommand);
endIfCommand.startCommand = ifStatementCommand;
commands.push(ifStatementCommand);
commands.push(endIfCommand);
return commands;
},
generateReturnStatementExecutionCommands: function (sourceElement, parentFunctionCommand)
{
var commands = [];
if(sourceElement.argument != null)
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.argument, parentFunctionCommand));
}
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.EvalReturnExpression, parentFunctionCommand));
return commands;
},
generateBreakStatementExecutionCommands: function (sourceElement, parentFunctionCommand)
{
var commands = [];
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.EvalBreak, parentFunctionCommand));
return commands;
},
generateContinueStatementExecutionCommands: function (sourceElement, parentFunctionCommand)
{
var commands = [];
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.EvalContinue, parentFunctionCommand));
return commands;
},
generateTryStatementExecutionCommands: function (sourceElement, parentFunctionCommand)
{
var commands = [];
var startTryCommand = new Command(sourceElement, Command.COMMAND_TYPE.StartTryStatement, parentFunctionCommand);
commands.push(startTryCommand);
ASTHelper.traverseDirectSourceElements
(
sourceElement.block,
function(sourceElement)
{
ValueTypeHelper.pushAll(commands, CommandGenerator.generateExecutionCommands(sourceElement, parentFunctionCommand));
},
false
);
var endTryCommand = new Command(sourceElement, Command.COMMAND_TYPE.EndTryStatement, parentFunctionCommand);
endTryCommand.startCommand = startTryCommand;
commands.push(endTryCommand);
return commands;
},
generateThrowStatementExecutionCommands: function (sourceElement, parentFunctionCommand)
{
var commands = [];
if(sourceElement.argument != null)
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.argument, parentFunctionCommand));
}
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.EvalThrowExpression, parentFunctionCommand));
return commands;
},
generateWithStatementExecutionCommands: function (sourceElement, parentFunctionCommand)
{
var commands = [];
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.object, parentFunctionCommand));
var startWithCommand = new Command(sourceElement, Command.COMMAND_TYPE.StartWithStatement, parentFunctionCommand);
commands.push(startWithCommand);
ASTHelper.traverseDirectSourceElements
(
sourceElement.body,
function(sourceElement)
{
ValueTypeHelper.pushAll(commands, CommandGenerator.generateExecutionCommands(sourceElement, parentFunctionCommand));
},
false
);
var endWithCommand = new Command(sourceElement, Command.COMMAND_TYPE.EndWithStatement, parentFunctionCommand);
commands.push(endWithCommand);
endWithCommand.startCommand = startWithCommand;
return commands;
},
generateSwitchStatementExecutionCommands: function (sourceElement, parentFunctionCommand)
{
var commands = [];
var startSwitchCommand = new Command(sourceElement, Command.COMMAND_TYPE.StartSwitchStatement, parentFunctionCommand);
startSwitchCommand.caseCommands = [];
startSwitchCommand.hasBeenMatched = false;
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.discriminant, parentFunctionCommand));
commands.push(startSwitchCommand);
sourceElement.cases.forEach(function(caseElement)
{
if(caseElement.test != null)
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(caseElement.test, parentFunctionCommand));
}
var caseCommand = new Command(caseElement, Command.COMMAND_TYPE.Case, parentFunctionCommand);
caseCommand.parent = startSwitchCommand;
startSwitchCommand.caseCommands.push(caseCommand);
commands.push(caseCommand);
}, this);
var endSwitchCommand = new Command(sourceElement, Command.COMMAND_TYPE.EndSwitchStatement, parentFunctionCommand);
endSwitchCommand.startCommand = startSwitchCommand;
commands.push(endSwitchCommand);
return commands;
},
generateLetStatementExecutionCommands: function (sourceElement, parentFunctionCommand)
{
this.notifyError("Let statement not yet handled");
return [];
},
generateLabeledStatementExecutionCommands: function (labelElement, parentFunctionCommand)
{
return [new Command(labelElement, Command.COMMAND_TYPE.Label, parentFunctionCommand)];
},
generateFunctionExecutionCommands: function(callExpressionCommand, functionObject, thisObject)
{
var commands = [];
if(functionObject == null) { this.notifyError("function object can not be null when generating commands for function execution!"); return commands; }
if(functionObject.isInternalFunction && !callExpressionCommand.isCall && !callExpressionCommand.isApply)
{
return this._generateInternalFunctionExecutionCommands(callExpressionCommand, functionObject, thisObject);
}
else if(functionObject.isInternalFunction && (callExpressionCommand.isCall || callExpressionCommand.isApply))
{
return this._generateInternalFunctionExecutionCallApplyCommands(callExpressionCommand, functionObject, thisObject);
}
var enterFunctionContextCommand = Command.createEnterFunctionContextCommand(functionObject, thisObject, callExpressionCommand);
var exitFunctionContextCommand = Command.createExitFunctionContextCommand(functionObject, callExpressionCommand);
commands.push(enterFunctionContextCommand);
callExpressionCommand.exitFunctionContextCommand = exitFunctionContextCommand;
exitFunctionContextCommand.callExpressionCommand = callExpressionCommand;
var functionConstruct = functionObject.codeConstruct;
ASTHelper.traverseDirectSourceElements
(
functionConstruct.body,
function(sourceElement)
{
ValueTypeHelper.pushAll
(
commands,
CommandGenerator.generateDeclarationCommands(sourceElement, callExpressionCommand)
);
},
true
);
ASTHelper.traverseDirectSourceElements
(
functionConstruct.body,
function(sourceElement)
{
ValueTypeHelper.pushAll
(
commands,
CommandGenerator.generateExecutionCommands(sourceElement, callExpressionCommand)
);
},
false
);
commands.push(exitFunctionContextCommand);
return commands;
},
_generateInternalFunctionExecutionCommands: function(callExpressionCommand, functionObject, thisObject)
{
var commands = [];
if(functionObject == null) { this.notifyError("function object can not be null when generating commands for internal function execution!"); return commands; }
if(!functionObject.isInternalFunction) { this.notifyError("function must be an internal function"); return commands; }
var command = null;
if (callExpressionCommand.isEvalNewExpressionCommand())
{
command = Command.createCallInternalConstructorCommand
(
callExpressionCommand.codeConstruct,
functionObject,
callExpressionCommand.parentFunctionCommand
);
}
else
{
command = Command.createCallInternalFunctionCommand
(
callExpressionCommand.codeConstruct,
functionObject,
thisObject,
callExpressionCommand.parentFunctionCommand,
callExpressionCommand
);
}
commands.push(command);
return commands;
},
_generateInternalFunctionExecutionCallApplyCommands: function(callExpressionCommand, functionObject, thisObject)
{
var command = Command.createCallInternalFunctionCommand
(
callExpressionCommand.codeConstruct,
functionObject,
thisObject,
callExpressionCommand.parentFunctionCommand
);
command.isCall = callExpressionCommand.isCall;
command.isApply = callExpressionCommand.isApply;
return [command];
},
generateCallbackFunctionExecutionCommands: function(callbackCommand)
{
var commands = [];
var argumentGroups = callbackCommand.callbackArgumentGroups;
if(argumentGroups == null) { return commands; }
callbackCommand.intermediateResults = [];
callbackCommand.childCommands = [];
for(var i = 0, length = argumentGroups.length; i < length; i++)
{
var executeCallbackCommand = Command.createExecuteCallbackCommand(callbackCommand, argumentGroups[i], i);
executeCallbackCommand.parentInitCallbackCommand = callbackCommand;
callbackCommand.childCommands.push(executeCallbackCommand);
commands.push(executeCallbackCommand);
ValueTypeHelper.pushAll(commands, this.generateFunctionExecutionCommands(executeCallbackCommand, callbackCommand.callbackFunction, callbackCommand.thisObject));
var evalCallbackCommand = new Command
(
callbackCommand.callbackFunction.codeConstruct,
Command.COMMAND_TYPE.EvalCallbackFunction,
callbackCommand
);
evalCallbackCommand.parentInitCallbackCommand = callbackCommand;
evalCallbackCommand.thisObject = executeCallbackCommand.thisObject;
evalCallbackCommand.originatingObject = executeCallbackCommand.originatingObject;
evalCallbackCommand.targetObject = executeCallbackCommand.targetObject;
evalCallbackCommand.executeCallbackCommand = executeCallbackCommand;
commands.push(evalCallbackCommand);
}
if(commands.length != 0)
{
var lastEvalCallbackCommand = commands[commands.length - 1];
lastEvalCallbackCommand.isLastCallbackCommand = true;
lastEvalCallbackCommand.executeCallbackCommand.isLastCallbackCommand = true;
callbackCommand.lastCallbackCommand = lastEvalCallbackCommand;
}
return commands;
},
generateIfStatementBodyCommands: function(ifStatementCommand, conditionEvaluationResult, parentFunctionCommand)
{
var commands = [];
if(conditionEvaluationResult)
{
ASTHelper.traverseDirectSourceElements
(
ifStatementCommand.codeConstruct.consequent,
function(sourceElement)
{
ValueTypeHelper.pushAll(commands, CommandGenerator.generateExecutionCommands(sourceElement, parentFunctionCommand));
},
false
);
}
else
{
if(ifStatementCommand.codeConstruct.alternate != null)
{
ASTHelper.traverseDirectSourceElements
(
ifStatementCommand.codeConstruct.alternate,
function(sourceElement)
{
ValueTypeHelper.pushAll(commands, CommandGenerator.generateExecutionCommands(sourceElement, parentFunctionCommand));
},
false
);
}
}
return commands;
},
generateCaseExecutionCommands: function(caseCommand)
{
var commands = [];
ASTHelper.traverseArrayOfDirectStatements
(
caseCommand.codeConstruct.consequent,
caseCommand.codeConstruct,
function(sourceElement)
{
ValueTypeHelper.pushAll(commands, CommandGenerator.generateExecutionCommands(sourceElement, caseCommand.parentFunctionCommand));
},
false
);
return commands;
},
generateCatchStatementExecutionCommands: function(tryCommand, exceptionArgument, throwingCommand)
{
var commands = [];
var tryStatement = tryCommand.codeConstruct;
var handlers = tryStatement.handlers || (ValueTypeHelper.isArray(tryStatement.handler) ? tryStatement.handler : [tryStatement.handler]);
if(handlers.length > 1) { this.notifyError("Not handling more than 1 catch"); return commands; }
var catchElement = handlers[0];
var startCatchCommand = new Command(catchElement, Command.COMMAND_TYPE.StartCatchStatement, tryCommand.parentFunctionCommand);
startCatchCommand.throwingCommand = throwingCommand;
commands.push(startCatchCommand);
commands[0].exceptionArgument = exceptionArgument;
ASTHelper.traverseDirectSourceElements
(
catchElement.body,
function(sourceElement)
{
ValueTypeHelper.pushAll(commands, CommandGenerator.generateExecutionCommands
(
sourceElement,
tryCommand.parentFunctionCommand
));
},
false
);
var endCatchCommand = new Command(catchElement, Command.COMMAND_TYPE.EndCatchStatement, tryCommand.parentFunctionCommand);
endCatchCommand.startCommand = startCatchCommand;
commands.push(endCatchCommand);
return commands;
},
generateLoopExecutionCommands: function(loopStatementCommand, evaldCondition)
{
if (loopStatementCommand.isForStatementCommand()) { return this.generateForBodyExecutionCommands(loopStatementCommand, evaldCondition); }
else if (loopStatementCommand.isDoWhileStatementCommand()) { return this.generateDoWhileBodyExecutionCommands(loopStatementCommand, evaldCondition); }
else if (loopStatementCommand.isWhileStatementCommand()) { return this.generateWhileBodyExecutionCommands(loopStatementCommand, evaldCondition); }
else if (loopStatementCommand.isEvalForInWhereCommand()) { return this.generateForInBodyExecutionCommands(loopStatementCommand, evaldCondition); }
else { this.notifyError("Unknown loop statement!"); }
},
generateWhileBodyExecutionCommands: function(whileStatementCommand, evaldCondition)
{
var commands = [];
var endWhileCommand = new Command(whileStatementCommand.codeConstruct, Command.COMMAND_TYPE.EndLoopStatement, whileStatementCommand.parentFunctionCommand);
endWhileCommand.startCommand = whileStatementCommand;
if(evaldCondition)
{
ASTHelper.traverseDirectSourceElements
(
whileStatementCommand.codeConstruct.body,
function(sourceElement)
{
ValueTypeHelper.pushAll(commands, CommandGenerator.generateExecutionCommands(sourceElement, whileStatementCommand.parentFunctionCommand));
},
false
);
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(whileStatementCommand.codeConstruct.test, whileStatementCommand.parentFunctionCommand));
commands.push(endWhileCommand);
commands.push(new Command(whileStatementCommand.codeConstruct, Command.COMMAND_TYPE.WhileStatement, whileStatementCommand.parentFunctionCommand));
}
else
{
commands.push(endWhileCommand);
}
return commands;
},
generateDoWhileBodyExecutionCommands: function(doWhileStatementCommand, evaldCondition)
{
var commands = [];
var endDoWhileCommand = new Command(doWhileStatementCommand.codeConstruct, Command.COMMAND_TYPE.EndLoopStatement, doWhileStatementCommand.parentFunctionCommand);
endDoWhileCommand.startCommand = doWhileStatementCommand;
if(evaldCondition)
{
ASTHelper.traverseDirectSourceElements
(
doWhileStatementCommand.codeConstruct.body,
function(sourceElement)
{
ValueTypeHelper.pushAll(commands, CommandGenerator.generateExecutionCommands(sourceElement, doWhileStatementCommand.parentFunctionCommand));
},
false
);
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(doWhileStatementCommand.codeConstruct.test, doWhileStatementCommand.parentFunctionCommand));
commands.push(endDoWhileCommand);
commands.push(new Command(doWhileStatementCommand.codeConstruct, Command.COMMAND_TYPE.DoWhileStatement, doWhileStatementCommand.parentFunctionCommand));
}
else
{
commands.push(endDoWhileCommand);
}
return commands;
},
generateForBodyExecutionCommands: function(forStatementCommand, evaldCondition)
{
var commands = [];
var forConstruct = forStatementCommand.codeConstruct;
var endLoopCommand = new Command(forConstruct, Command.COMMAND_TYPE.EndLoopStatement, forStatementCommand.parentFunctionCommand);
endLoopCommand.startCommand = forStatementCommand;
if(evaldCondition)
{
ASTHelper.traverseDirectSourceElements
(
forConstruct.body,
function(sourceElement)
{
ValueTypeHelper.pushAll(commands, CommandGenerator.generateExecutionCommands(sourceElement, forStatementCommand.parentFunctionCommand));
},
false
);
commands.push(new Command(forConstruct, Command.COMMAND_TYPE.ForUpdateStatement, forStatementCommand.parentFunctionCommand));
if(forConstruct.update != null)
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(forConstruct.update, forStatementCommand.parentFunctionCommand));
}
if(forConstruct.test != null)
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(forConstruct.test, forStatementCommand.parentFunctionCommand));
}
commands.push(endLoopCommand);
commands.push(new Command(forConstruct, Command.COMMAND_TYPE.ForStatement, forStatementCommand.parentFunctionCommand));
}
else
{
commands.push(endLoopCommand);
}
return commands;
},
generateForInBodyExecutionCommands: function(forInCommand)
{
var commands = [];
var endLoopCommand = new Command(forInCommand.codeConstruct, Command.COMMAND_TYPE.EndLoopStatement, forInCommand.parentFunctionCommand);
endLoopCommand.startCommand = forInCommand;
if(forInCommand.willBodyBeExecuted)
{
ASTHelper.traverseDirectSourceElements
(
forInCommand.codeConstruct.body,
function(sourceElement)
{
ValueTypeHelper.pushAll(commands, CommandGenerator.generateExecutionCommands(sourceElement, forInCommand.parentFunctionCommand));
},
false
);
commands.push(endLoopCommand);
commands.push(Command.createForInWhereCommand(forInCommand.codeConstruct, forInCommand.propertyNames, forInCommand.parentFunctionCommand));
}
else
{
commands.push(endLoopCommand);
}
return commands;
},
generateExpressionCommands: function(sourceElement, parentFunctionCommand)
{
if (ASTHelper.isThisExpression(sourceElement)) { return this.generateThisCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isIdentifier(sourceElement)) { return this.generateIdentifierCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isLiteral(sourceElement)) { return this.generateLiteralCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isArrayExpression(sourceElement)) { return this.generateArrayExpressionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isObjectExpression(sourceElement)) { return this.generateObjectExpressionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isFunctionExpression(sourceElement)) { return this.generateFunctionExpressionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isSequenceExpression(sourceElement)) { return this.generateSequenceExpressionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isUnaryExpression(sourceElement)) { return this.generateUnaryExpressionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isBinaryExpression(sourceElement)) { return this.generateBinaryExpressionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isAssignmentExpression(sourceElement)) { return this.generateAssignmentExpressionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isUpdateExpression(sourceElement)) { return this.generateUpdateExpressionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isLogicalExpression(sourceElement)) { return this.generateLogicalExpressionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isConditionalExpression(sourceElement)) { return this.generateConditionalExpressionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isNewExpression(sourceElement)) { return this.generateNewExpressionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isCallExpression(sourceElement)) { return this.generateCallExpressionCommands(sourceElement, parentFunctionCommand);}
else if (ASTHelper.isMemberExpression(sourceElement)) { return this.generateMemberExpressionCommands(sourceElement, parentFunctionCommand); }
else if (ASTHelper.isYieldExpression(sourceElement)
|| ASTHelper.isComprehensionExpression(sourceElement)
|| ASTHelper.isGeneratorExpression(sourceElement)
|| ASTHelper.isLetExpression(sourceElement))
{
this.notifyError("Yield, Comprehension, Generator and Let not yet implemented!");
}
},
generateThisCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.ThisExpression, parentFunctionCommand));
return commands;
},
generateIdentifierCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.EvalIdentifier, parentFunctionCommand));
return commands;
},
generateLiteralCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
if(ValueTypeHelper.isObject(sourceElement.value))
{
var regExCommand = new Command(sourceElement, Command.COMMAND_TYPE.EvalRegExLiteral, parentFunctionCommand);
//If it is directly gotten from mdc parser
if(sourceElement.value.constructor != null && sourceElement.value.constructor.name === "RegExp")
{
regExCommand.regExLiteral = sourceElement.value;
}
else //over JSON conversion
{
regExCommand.regExLiteral = ValueTypeHelper.adjustForRegExBug(sourceElement.value, atob(sourceElement.value.RegExpBase64));
}
commands.push(regExCommand);
}
else
{
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.EvalLiteral, parentFunctionCommand));
}
return commands;
},
generateArrayExpressionCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
var arrayExpressionCommand = new Command(sourceElement, Command.COMMAND_TYPE.ArrayExpression, parentFunctionCommand);
commands.push(arrayExpressionCommand);
var elements = sourceElement.elements;
if(elements == null || elements.length == 0) { return commands; }
for(var i = 0, length = elements.length; i < length; i++)
{
var item = elements[i];
if(item != null)
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(item, parentFunctionCommand));
}
commands.push(Command.createArrayExpressionItemCommand(item, arrayExpressionCommand, parentFunctionCommand));
}
return commands;
},
generateObjectExpressionCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
var objectExpressionCommand = new Command(sourceElement, Command.COMMAND_TYPE.ObjectExpression, parentFunctionCommand);
commands.push(objectExpressionCommand);
var properties = sourceElement.properties;
if(properties == null || properties.length == 0) { return commands; }
for(var i = 0, length = properties.length; i < length; i++)
{
var property = properties[i];
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(property.value, parentFunctionCommand));
if(property.kind == "get" || property.kind == "set") { this.notifyError("Getters and setters not supported!"); }
commands.push(Command.createObjectPropertyCommand(property, objectExpressionCommand, parentFunctionCommand));
}
return commands;
},
generateFunctionExpressionCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.FunctionExpressionCreation, parentFunctionCommand));
return commands;
},
generateSequenceExpressionCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
var expressions = sourceElement.expressions;
for(var i = 0, length = expressions.length; i < length; i++)
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(expressions[i], parentFunctionCommand));
}
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.EvalSequenceExpression, parentFunctionCommand));
return commands;
},
generateUnaryExpressionCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.argument, parentFunctionCommand));
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.EvalUnaryExpression, parentFunctionCommand));
return commands;
},
generateBinaryExpressionCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.left, parentFunctionCommand));
commands.push(new Command(sourceElement.left, Command.COMMAND_TYPE.ConvertToPrimitive, parentFunctionCommand));
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.right, parentFunctionCommand));
commands.push(new Command(sourceElement.right, Command.COMMAND_TYPE.ConvertToPrimitive, parentFunctionCommand));
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.EvalBinaryExpression, parentFunctionCommand));
return commands;
},
generateAssignmentExpressionCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.right, parentFunctionCommand));
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.left, parentFunctionCommand));
commands.push(Command.createAssignmentCommand(sourceElement, parentFunctionCommand));
return commands;
},
generateUpdateExpressionCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.argument, parentFunctionCommand));
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.EvalUpdateExpression, parentFunctionCommand));
return commands;
},
generateLogicalExpressionCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
var startLogicalExpressionCommand = new Command(sourceElement, Command.COMMAND_TYPE.StartEvalLogicalExpression, parentFunctionCommand);
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.left, parentFunctionCommand));
var evalLeft = new Command(sourceElement.left, Command.COMMAND_TYPE.EvalLogicalExpressionItem, parentFunctionCommand);
evalLeft.parentLogicalExpressionCommand = startLogicalExpressionCommand;
commands.push(evalLeft);
startLogicalExpressionCommand.evalLeftCommand = evalLeft;
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.right, parentFunctionCommand));
var evalRight = new Command(sourceElement.right, Command.COMMAND_TYPE.EvalLogicalExpressionItem, parentFunctionCommand);
evalRight.parentLogicalExpressionCommand = startLogicalExpressionCommand;
commands.push(evalRight);
startLogicalExpressionCommand.evalRightCommand = evalRight;
var endLogicalExpressionCommand = new Command(sourceElement, Command.COMMAND_TYPE.EndEvalLogicalExpression, parentFunctionCommand);
evalLeft.parentEndLogicalExpressionCommand = endLogicalExpressionCommand;
evalRight.parentEndLogicalExpressionCommand = endLogicalExpressionCommand;
endLogicalExpressionCommand.startCommand = startLogicalExpressionCommand;
endLogicalExpressionCommand.executedLogicalItemExpressionCommands = [];
commands.push(endLogicalExpressionCommand);
return commands;
},
generateConditionalExpressionCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.test, parentFunctionCommand));
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.EvalConditionalExpressionBody, parentFunctionCommand));
return commands;
},
generateConditionalExpressionEvalBodyCommands: function(executeConditionalExpressionBodyCommand, willConsequentBeExecuted)
{
var commands = [];
var evalConditionalExpressionCommand = new Command(executeConditionalExpressionBodyCommand.codeConstruct, Command.COMMAND_TYPE.EvalConditionalExpression, executeConditionalExpressionBodyCommand.codeConstruct.parentFunctionCommand);
commands.push(evalConditionalExpressionCommand);
if(willConsequentBeExecuted)
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(executeConditionalExpressionBodyCommand.codeConstruct.consequent, executeConditionalExpressionBodyCommand.parentFunctionCommand));
evalConditionalExpressionCommand.body = executeConditionalExpressionBodyCommand.codeConstruct.consequent;
}
else
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(executeConditionalExpressionBodyCommand.codeConstruct.alternate, executeConditionalExpressionBodyCommand.parentFunctionCommand));
evalConditionalExpressionCommand.body = executeConditionalExpressionBodyCommand.codeConstruct.alternate;
}
var endConditionalExpressionCommand = new Command(executeConditionalExpressionBodyCommand.codeConstruct, Command.COMMAND_TYPE.EndEvalConditionalExpression, executeConditionalExpressionBodyCommand.codeConstruct.parentFunctionCommand);
endConditionalExpressionCommand.startCommand = evalConditionalExpressionCommand;
commands.push(endConditionalExpressionCommand);
return commands;
},
generateNewExpressionCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.callee, parentFunctionCommand));
if(sourceElement.arguments != null)
{
sourceElement.arguments.forEach(function(argument)
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(argument, parentFunctionCommand));
}, this);
}
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.EvalNewExpression, parentFunctionCommand));
return commands;
},
generateCallExpressionCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.callee, parentFunctionCommand));
if(sourceElement.arguments != null)
{
sourceElement.arguments.forEach(function(argument)
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(argument, parentFunctionCommand));
}, this);
}
commands.push(new Command(sourceElement, Command.COMMAND_TYPE.EvalCallExpression, parentFunctionCommand));
return commands;
},
generateMemberExpressionCommands: function(sourceElement, parentFunctionCommand)
{
var commands = [];
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.object, parentFunctionCommand));
if(sourceElement.computed)
{
ValueTypeHelper.pushAll(commands, this.generateExpressionCommands(sourceElement.property, parentFunctionCommand));
}
var evalMemberExpressionCommand = new Command(sourceElement, Command.COMMAND_TYPE.EvalMemberExpression, parentFunctionCommand);
var evalMemberPropertyExpressionCommand = new Command(sourceElement, Command.COMMAND_TYPE.EvalMemberExpressionProperty, parentFunctionCommand);
evalMemberPropertyExpressionCommand.parentMemberExpressionCommand = evalMemberExpressionCommand;
commands.push(evalMemberPropertyExpressionCommand);
commands.push(evalMemberExpressionCommand);
return commands;
},
toString: function(commands) { return commands.join("\n"); },
notifyError: function(message) { debugger; alert("CommandGenerator - " + message); }
};
/*************************************************************************************/
})();
|
var searchData=
[
['game_5fstate_5flose',['GAME_STATE_LOSE',['../merge_2tank_8cpp.html#a4cc39f049df62b331976f9a4482bd3eaa6a015920aa14873056d9e7b167259851',1,'GAME_STATE_LOSE(): tank.cpp'],['../tank_8cpp.html#a4cc39f049df62b331976f9a4482bd3eaa6a015920aa14873056d9e7b167259851',1,'GAME_STATE_LOSE(): tank.cpp']]],
['game_5fstate_5fmenu',['GAME_STATE_MENU',['../merge_2tank_8cpp.html#a4cc39f049df62b331976f9a4482bd3eaad55f850ac43776aa81cada955236d058',1,'tank.cpp']]],
['game_5fstate_5frun',['GAME_STATE_RUN',['../merge_2tank_8cpp.html#a4cc39f049df62b331976f9a4482bd3eaa681fca356588f51a1f22440a0f193582',1,'GAME_STATE_RUN(): tank.cpp'],['../tank_8cpp.html#a4cc39f049df62b331976f9a4482bd3eaa681fca356588f51a1f22440a0f193582',1,'GAME_STATE_RUN(): tank.cpp']]],
['game_5fstate_5ftitle',['GAME_STATE_TITLE',['../merge_2tank_8cpp.html#a4cc39f049df62b331976f9a4482bd3eaa6a28ed2a7dacc8b327a2b718be1b6088',1,'tank.cpp']]],
['game_5fstate_5ftuto',['GAME_STATE_TUTO',['../merge_2tank_8cpp.html#a4cc39f049df62b331976f9a4482bd3eaa21d086879fb2dffe551186a87c896cf0',1,'tank.cpp']]],
['game_5fstate_5fwin',['GAME_STATE_WIN',['../merge_2tank_8cpp.html#a4cc39f049df62b331976f9a4482bd3eaabdf2ca310ee249a9126f1694014e888a',1,'GAME_STATE_WIN(): tank.cpp'],['../tank_8cpp.html#a4cc39f049df62b331976f9a4482bd3eaabdf2ca310ee249a9126f1694014e888a',1,'GAME_STATE_WIN(): tank.cpp']]]
];
|
'use strict';
var _ = require('underscore');
var winston = require('winston');
module.exports = function(level) {
level = 5 - level;
var levels = {
trace: 0,
"debug": 1,
"info": 2,
"warn": 3,
"error": 4,
"silent": 5
};
if(level > 5) level = 5;
if(level < 1) level = 0;
var lookup = _.invert(levels);
var logger = new winston.Logger({
transports: [
new winston.transports.Console({
level: lookup[level],
stderrLevels: Object.keys(levels)
})
],
level: lookup[level],
levels: levels
});
return logger;
};
|
/*
* Set focus on element when the value of the show-focus attribute is true
*/
instaLurker.directive('showFocus', ['$timeout', function($timeout) {
return {
link:function(scope, element, attrs) {
scope.$watch(attrs.showFocus,
function (newValue) {
$timeout(function() {
if(newValue) {
element[0].focus();
element[0].select();
}
});
},true);
}
}
}]);
|
'use strict';
function UsuarioResource(CrudResourceFactory) {
return CrudResourceFactory('/api/usuario', 'Usuario');
}
angular.module('erpapp.usuario.services', ['grails'])
.factory('UsuarioResource', UsuarioResource);
|
angular.module('myApp.manage', ['ngRoute']).config([
'$routeProvider', function($routeProvider)
{
$routeProvider.when('/manage/:type/:route_key', {
templateUrl: 'sections/routes/manage/manage.html',
controller: 'manageCtrl'
});
}
]).controller('manageCtrl', function($scope, $routeParams, $mdDialog, $location)
{
$scope.route = {};
switch($routeParams.type)
{
case "route":
$scope.route.type = 2;
$scope.route.concession_route = {};
$scope.route.concession_route.polyline = "";
$scope.route.concession_route.stops = [];
break;
case "site":
$scope.route.type = 1;
$scope.route.site = {};
break;
case "private":
$scope.route.type = 3;
$scope.route.private_route = {};
break;
default:
$location.path('/route');
}
$scope.isNew = true;
if($routeParams.route_key != "new")
{
$scope.isNew = false;
$.post(webtransporte + '/admin/get/route',
{
public_key: localStorage.getItem('public_key'),
route_key: $routeParams.route_key
}, function(response)
{
if(response.response_code == 200)
{
$scope.route = response.route;
$scope.route.vehicle_antiquity = parseInt(response.route.vehicle_antiquity);
$scope.vehicleKey = $scope.route.vehicle_typeId + "-" + $scope.route.vehicle_classId;
$('#preview').attr('src', $scope.route.image);
$scope.$digest();
$scope.getLocalities(response.route.municipalityId);
}
}, 'json');
}
getSelectsContent();
/********************************
polyline modal
*********************************/
$scope.addPolyline = function()
{
$mdDialog.show({
controller: 'add_route_polylineCtrl',
templateUrl: 'sections/routes/manage/add_route_polyline/add_route_polyline.html',
parent: angular.element(document.body),
escapeToClose: false,
fullscreen: false,
locals: {
data: {
route: $scope.route.concession_route
}
}
}).then(function(data)
{
$scope.route.link = data.highResUrl;
$scope.route.concession_route.polyline = data.polyline;
$scope.route.concession_route.stops = data.stops;
toDataUrl(data.lowResUrl, function(result)
{
$scope.route.lowResMap = result;
});
toDataUrl(data.highResUrl, function(result)
{
$scope.route.highResMap = result;
});
});
};
$scope.addLoc = function()
{
$mdDialog.show({
controller: 'add_locCtrl',
templateUrl: 'sections/routes/manage/add_loc/add_loc.html',
parent: angular.element(document.body),
escapeToClose: false,
fullscreen: false
}).then(function(data)
{
$scope.route.link = data.highResUrl;
toDataUrl(data.lowResUrl, function(result)
{
$scope.route.lowResMap = result;
});
toDataUrl(data.highResUrl, function(result)
{
$scope.route.highResMap = result;
});
});
};
function toDataUrl(url, callback)
{
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function()
{
var reader = new FileReader();
reader.onloadend = function()
{
var image = new Image();
image.onload = function()
{
var canvas = document.createElement('canvas');
var width = image.width;
var height = image.height;
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
callback(canvas.toDataURL('image/jpeg'));
};
image.src = reader.result;
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
/********************************
top buttons
*********************************/
$scope.saveRoute = function()
{
if($routeParams.route_key == "new")
{
if($scope.route.type == 2)
$scope.route.concession_route.route_typeId = parseInt($scope.route.concession_route.route_typeId);
$mdDialog.show({
controller: 'loadingCtrl',
templateUrl: 'loading/loading.html',
locals:{title:"Guardando..."}
});
$.post(webtransporte + '/admin/new/route',
{
public_key: localStorage.getItem('public_key'),
route: JSON.stringify($scope.route)
}, function(response)
{
if(response.response_code == 200)
{
$scope.$apply(function()
{
$mdDialog.show(
$mdDialog.alert()
.clickOutsideToClose(true)
.title($scope.route.type == 2 ? 'Ruta Agregada' : $scope.route.type == 1 ? 'Sitio Agregado' : 'Privado Agregado')
.ariaLabel('Dialog route added')
.ok('Aceptar')
).then(function()
{
$location.path('/routes/' + $scope.route.type);
});
});
}
else if(response.response_code == 400)
{
$mdDialog.show(
$mdDialog.alert()
.clickOutsideToClose(true)
.title('Error al guardar')
.textContent($scope.getErrorMessage(response.response_message))
.ariaLabel('Alguno de los parámetros es inválido')
.ok('Aceptar')
);
}
else
{
$scope.$apply(function()
{
$mdDialog.show(
$mdDialog.alert()
.clickOutsideToClose(true)
.title('Error al guardar')
.ariaLabel('Alguno de los parámetros es inválido')
.textContent(response.response_message)
.ok('Aceptar')
);
});
}
}, 'json')
.fail(function()
{
$scope.$apply(function()
{
$mdDialog.show(
$mdDialog.alert()
.clickOutsideToClose(true)
.title('Error al guardar')
.ariaLabel('Alguno de los parámetros es inválido')
.textContent('Error en el servidor')
.ok('Aceptar')
);
});
});
}
else
{
$scope.route.type = $scope.getRouteType();
if($scope.route.type == 2)
$scope.route.concession_route.route_typeId = parseInt($scope.route.concession_route.route_typeId);
$mdDialog.show({
controller: 'loadingCtrl',
templateUrl: 'loading/loading.html',
locals:{title:"Guardando..."}
});
$.post(webtransporte + '/admin/update/route',
{
public_key: localStorage.getItem('public_key'),
route_key: $routeParams.route_key,
route: JSON.stringify($scope.route)
}, function(response)
{
if(response.response_code == 200)
{
$scope.$apply(function()
{
$mdDialog.show(
$mdDialog.alert()
.clickOutsideToClose(true)
.title($scope.route.type == 2 ? 'Ruta Guardada' : $scope.route.type == 1 ? 'Sitio Guardado' : 'Privado Guardado')
.ariaLabel('Dialog route added')
.ok('Aceptar')
).then(function()
{
$location.path('/routes/' + $scope.route.type);
});
});
}
else if(response.response_code == 400)
{
$mdDialog.show(
$mdDialog.alert()
.clickOutsideToClose(true)
.title('Error al guardar')
.textContent($scope.getErrorMessage(response.response_message))
.ariaLabel('Alguno de los parámetros es inválido')
.ok('Aceptar')
);
}
else
{
$scope.$apply(function()
{
$mdDialog.show(
$mdDialog.alert()
.clickOutsideToClose(true)
.title('Error al guardar')
.ariaLabel('Alguno de los parámetros es inválido')
.textContent(response.response_message)
.ok('Aceptar')
);
});
}
}, 'json')
.fail(function()
{
$scope.$apply(function()
{
$mdDialog.show(
$mdDialog.alert()
.clickOutsideToClose(true)
.title('Error al guardar')
.ariaLabel('Alguno de los parámetros es inválido')
.textContent('Error en el servidor')
.ok('Aceptar')
);
});
});
}
};
/********************************
route params
*********************************/
$scope.routeTypeEquals = function(type)
{
return $routeParams.type == type;
};
$scope.isNewRoute = function()
{
return $routeParams.route_key == "new"
};
$scope.getRouteType = function()
{
switch($routeParams.type)
{
case 'route':
return 2;
case 'site':
return 1;
case 'private':
return 3;
}
};
/********************************
image
*********************************/
$scope.selectFile = function()
{
$('#file').click();
$('#file').off('change');
$('#file').on('change', function()
{
if(this.files && this.files[0])
{
var reader = new FileReader();
reader.onload = function(e)
{
$('#preview').attr('src', e.target.result);
$scope.$digest();
resize(e.target.result,1280,720,function(img)
{
$scope.route.image = img;
});
resize(e.target.result,320,240,function(img)
{
$scope.route.imageLowRes = img;
});
};
reader.readAsDataURL(this.files[0]);
}
});
};
function resize(img,maxWidth,maxHeight,onResized)
{
var image = new Image();
image.onload = function()
{
var canvas = document.createElement('canvas');
var width = image.width;
var height = image.height;
if(width > maxWidth)
{
if(width > maxWidth)
{
height *= maxWidth / width;
width = maxWidth;
}
} else
{
if(height > maxHeight)
{
width *= maxHeight / height;
height = maxHeight;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
onResized(canvas.toDataURL('image/jpeg'));
};
image.src = img;
}
$scope.clearImg = function()
{
$scope.route.image = "";
$scope.route.imageLowRes = "";
$('#preview').attr('src', '');
};
/********************************
get selects content
*********************************/
function getSelectsContent()
{
$.post(webtransporte + '/admin/get/states', {
public_key: localStorage.getItem('public_key')
}, function(response)
{
if(response.response_code == 200)
{
$scope.$apply(function()
{
$scope.states = response.states;
});
}
});
$.post(webtransporte + '/admin/get/municipalities', {
public_key: localStorage.getItem('public_key')
}, function(response)
{
if(response.response_code == 200)
{
$scope.$apply(function()
{
$scope.municipalities = response.municipalities;
});
}
});
$.post(webtransporte + '/admin/get/vehicles', {
public_key: localStorage.getItem('public_key')
}, function(response)
{
if(response.response_code == 200)
{
$scope.$apply(function()
{
$scope.vehicles = {};
response.vehicles.forEach(function(vehicle)
{
$scope.vehicles[(vehicle.id + "-" + vehicle.class)] = vehicle;
});
});
}
});
}
$scope.getLocalities = function(municipalityId)
{
$.post(webtransporte + '/admin/get/localities', {
public_key: localStorage.getItem('public_key'),
municipalityId: municipalityId
}, function(response)
{
if(response.response_code == 200)
{
$scope.$apply(function()
{
$scope.localities = response.localities;
});
}
});
};
/********************************
service units
*********************************/
$scope.chipsChanged = function()
{
console.log($scope.route.private_route.service_units);
};
/********************************
form validation
*********************************/
$scope.isFormValid = function()
{
return $scope.routeForm.$valid
&& $scope.route.type == 2?($scope.route.concession_route.ground != undefined && $scope.route.concession_route.ground != "" && $scope.route.concession_route.road != undefined && $scope.route.concession_route.road != ""):true;
};
$scope.filterVehicles = function(vehicles, classId)
{
var result = {};
angular.forEach(vehicles, function(vehicle, key)
{
if(vehicle.class == classId)
{
result[key] = vehicle;
}
});
return result;
};
$scope.getErrorMessage = function(message)
{
if(message instanceof Object)
{
var key = Object.keys(message)[0];
return key in keys ? keys[key] : key;
}
else
{
return message;
}
};
var keys =
{
"route.key": "Error en el parámetro: Clave mnemotécnica",
"route.name": "Error en el parámetro: Nombre",
"route.itinerary": "Error en el parámetro: Itinerario",
"route.localityId": "Error en el parámetro: Localidad",
"route.municipalityId": "Error en el parámetro: Minicipio",
"route.link": "Error en el parámetro: Mapa",
"route.sizing": "Error en el parámetro: Dimensionamiento",
"route.notes": "Error en el parámetro: Observaciones",
"route.vehicle_classId": "Error en el parámetro: Clase de vehículo",
"route.vehicle_typeId": "Error en el parámetro: Tipo de vehículo",
"route.vehicle_antiquity": "Error en el parámetro: Antigüedad de vehículo",
"route.schedule_start": "Error en el parámetro: Inicio",
"route.schedule_end": "Error en el parámetro: Fin",
"route.concession_route.length": "Error en el parámetro: Longitud",
"route.concession_route.duration": "Error en el parámetro: Tiempo de recorrido",
"route.concession_route.frequency": "Error en el parámetro: Frecuencia",
"route.concession_route.min_rate": "Error en el parámetro: Tarifa mínima",
"route.concession_route.max_rate": "Error en el parámetro: Tarifa máxima",
"route.concession_route.polyline": "Error en el parámetro: Mapa de la ruta",
"route.concession_route.stops": "La ruta debe de tener al menos una parada",
"route.site.generator": "Error en el parámetro: Generador",
"route.site.atractor": "Error en el parámetro: Atractor",
"route.site.users_benefit": "Error en el parámetro: Usuarios Beneficiados",
"route.site.frequency": "Error en el parámetro: Frecuencia",
"route.site.min_rate": "Error en el parámetro: Tarifa mínima",
"route.site.max_rate": "Error en el parámetro: Tarifa máxima",
"route.private_route.generator": "Error en el parámetro: Generador",
"route.private_route.atractor": "Error en el parámetro: Atractor",
"route.private_route.users_benefit": "Error en el parámetro: Usuarios beneficiados",
"route.private_route.rate": "Error en el parámetro: Tarífa",
"route.private_route.concessions": "Error en el parámetro: Concesiones",
"route.private_route.service_units": "Error en el parámetro: Unidades óptimas para el servicio"
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.