code stringlengths 2 1.05M |
|---|
/*
* Kendo UI v2015.1.408 (http://www.telerik.com/kendo-ui)
* Copyright 2015 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["kl-GL"] = {
name: "kl-GL",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3,0],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3,0],
symbol: "%"
},
currency: {
pattern: ["$ -n","$ n"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3,0],
symbol: "kr."
}
},
calendars: {
standard: {
days: {
names: ["sapaat","ataasinngorneq","marlunngorneq","pingasunngorneq","sisamanngorneq","tallimanngorneq","arfininngorneq"],
namesAbbr: ["sap.","at.","marl.","ping.","sis.","tall.","arf."],
namesShort: ["sa","at","ma","pi","si","ta","ar"]
},
months: {
names: ["januaari","februaari","marsi","apriili","maaji","juuni","juuli","aggusti","septembari","oktobari","novembari","decembari"],
namesAbbr: ["jan","feb","mar","apr","mai","jun","jul","aug","sep","okt","nov","dec"]
},
AM: [""],
PM: [""],
patterns: {
d: "dd-MM-yyyy",
D: "MMMM d'.-at, 'yyyy",
F: "MMMM d'.-at, 'yyyy HH:mm:ss",
g: "dd-MM-yyyy HH:mm",
G: "dd-MM-yyyy HH:mm:ss",
m: "MMMM d'.-at'",
M: "MMMM d'.-at'",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "-",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); |
app.factory("dataService", function ($http, $q) {
var token = sessionStorage.getItem('accessToken');
var _sediEnergia = [];
var _sediEnergiaLoaded = false;
var _includiSedeVoltura = function (idVoltura, idSede, includi, idTabCFG_Azienda) {
var deferred = $q.defer();
$http({
url: QL.serviceUrl + "odata/Years",
method: "Get",
data: {
"idTabOPE_Contratti_Volture": idVoltura.toString(),
"idSede": idSede,
"includi": includi,
"idTabCFG_Azienda": idTabCFG_Azienda
},
headers: {
"Authorization": "Bearer " + token
}
}).then(function (result) {
deferred.resolve();
}, function () { // failure
deferred.reject("Errore durante la richiesta di elaborazione sede.");
});
return deferred.promise;
};
var _includiSedeVoltura = function (idVoltura, idSede, includi, idTabCFG_Azienda) {
var deferred = $q.defer();
$http({
url: QL.serviceUrl + "odata/Years",
method: "Get",
data: {
"idTabOPE_Contratti_Volture": idVoltura.toString(),
"idSede": idSede,
"includi": includi,
"idTabCFG_Azienda": idTabCFG_Azienda
},
headers: {
"Authorization": "Bearer " + token
}
}).then(function (result) {
deferred.resolve();
}, function () { // failure
deferred.reject("Errore durante la richiesta di elaborazione sede.");
});
return deferred.promise;
};
return {
LoadSediEnergia: _loadSediEnergia,
SediEnergia: _sediEnergia,
};
}); |
import React from 'react'
import styled from 'styled-components'
import ui from '../layouts/theme'
import GatsbyImage from 'gatsby-image'
import Journal from '../components/Journal'
const Title = styled.h1`
color: ${ui.color.background};
`
const BackgroundImage = styled(GatsbyImage)`
position: absolute;
top: 0;
right: 0;
bottom: 0;
width: 300%;
@media (min-width:768px) {
width: 100%;
}
`
const Content = styled.div`
z-index:1;
position: relative;
`
const LandingPage = styled.div`
position: relative;
padding: ${ui.size.s}
width: 100vw;
height: 100vh;
`
const IndexPage = ({ className, data }) => (
<div className={className}>
<BackgroundImage
sizes={data.imageSharp.sizes}
style={{ position: `absolute`, top: 0, right: 0, bottom: 0}}
/>
<Content>
<LandingPage></LandingPage>
<Journal posts={data.allMarkdownRemark.edges} />
</Content>
</div>
)
export default styled(IndexPage)`
height: 100%;
width: 100%;
flex: 1;
display: flex;
flex-direction: column;
position: relative;
padding-top: 30px;
`
export const queries = graphql`
query IndexAndBackgroundQueries {
allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) {
edges {
node {
excerpt(pruneLength: 250)
id
frontmatter {
title
date(formatString: "MMMM DD, YYYY")
path
}
}
}
}
imageSharp(id: { regex: "/dogs/" }) {
sizes(maxWidth: 1500) {
...GatsbyImageSharpSizes
}
}
}
`;
|
'use strict';
/**
* practice Node.js project
*
* @author Ryan <roninby@yeah.net>
*/
import path from 'path';
import express from 'express';
import serveStatic from 'serve-static';
import bodyParser from 'body-parser';
import multipart from 'connect-multiparty';
import session from 'express-session';
import _RedisStore from "connect-redis";
const RedisStore = _RedisStore(session);
module.exports = function (done) {
const debug = $.createDebug('init:express');
debug('Initing Express...');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(multipart());
app.use(session({
secret: $.config.get('web.session.secret'),
store: new RedisStore($.config.get('web.session.redis')),
}));
const router = express.Router();
const routerWrap = {};
['get', 'head', 'post', 'put', 'del', 'delete'].forEach(method => {
routerWrap[method] = function (path, ...fnList) {
fnList = fnList.map(fn => {
return function (req, res, next) {
const ret = fn(req, res, next);
if (ret && ret.catch) ret.catch(next);
};
});
router[method](path, ...fnList);
};
});
$.router = routerWrap;
app.use(function (req, res, next) {
res.apiSuccess = function (data) {
res.json({success: true, result: data});
};
next();
});
app.use(router);
app.use('/static', serveStatic(path.resolve(__dirname, '../../static')));
app.use('/api', function (err, req, res, next) {
debug('API error: %s', err && err.stack || err);
res.json({error: err.toString()});
});
app.listen($.config.get('web.port'), (err) => {
done(err);
});
};
|
'use strict';
// core modules
var http = require('http');
// external modules
var _ = require('lodash');
var assert = require('assert-plus');
// local globals
var INTERNAL_OPTS_KEYS = {
'code': true,
'restCode': true,
'statusCode': true,
'toJSON': true,
'toString': true
};
//------------------------------------------------------------------------------
// constructor arg parsers
//------------------------------------------------------------------------------
/**
* helper function for parsing all of the Error constructor variadic sigs.
* these signatures are all derived from VError.
* 1) new HttpError(sprintf_args...);
* 2) new HttpError(anotherErr, sprintf_args);
* 3) new HttpError({...}, sprintf_args);
* restify-errors' value is to add support for additional options using the
* signature #3. this function parses out the arguments specific to
* restify-errors so that they don't get passed on to VError.
* @public
* @param {Object} ctorArgs an 'arguments' object
* @function parseVErrorArgs
* @returns {Object}
*/
function parseVErrorArgs(ctorArgs) {
// to array the inner arguments so it's easier to determine which cases
// we are looking at
var args = _.toArray(ctorArgs);
var internalOpts = {};
var verrorOpts = {};
var verrorArgs;
if (_.isPlainObject(args[0])) {
// split restify-errors options from verror options
_.forOwn(args[0], function(val, key) {
if (Object.prototype.hasOwnProperty.call(INTERNAL_OPTS_KEYS, key)) {
internalOpts[key] = val;
} else {
verrorOpts[key] = val;
}
});
// reconstruct verror ctor options from the cleaned up options
verrorArgs = [ verrorOpts ].concat(_.tail(args));
} else {
verrorArgs = args;
}
return {
// raw arguments to pass to VError constructor
verrorArgs: verrorArgs,
// restify-errors specific options
internalOpts: internalOpts
};
}
//------------------------------------------------------------------------------
// helpers
//------------------------------------------------------------------------------
/**
* create an error name from a status code. looks up the description via
* http.STATUS_CODES, then calls createErrNameFromDesc().
* @private
* @function errNameFromCode
* @param {Number} code an http status code
* @returns {String}
*/
function errNameFromCode(code) {
assert.number(code, 'code');
// attempt to retrieve status code description, if not available,
// fallback on 500.
var errorDesc = http.STATUS_CODES[code] || http.STATUS_CODES[500];
return errNameFromDesc(errorDesc);
}
/**
* used to programatically create http error code names, using the underlying
* status codes names exposed via the http module.
* @private
* @function errNameFromDesc
* @param {String} desc a description of the error, e.g., 'Not Found'
* @returns {String}
*/
function errNameFromDesc(desc) {
assert.string(desc, 'desc');
// takes an error description, split on spaces, camel case it correctly,
// then append 'Error' at the end of it.
// e.g., the passed in description is 'Internal Server Error'
// the output is 'InternalServerError'
var pieces = desc.split(/\s+/);
var name = _.reduce(pieces, function(acc, piece) {
// lowercase all, then capitalize it.
var normalizedPiece = _.capitalize(piece.toLowerCase());
return acc + normalizedPiece;
}, '');
// strip all non word characters
name = name.replace(/\W+/g, '');
// append 'Error' at the end of it only if it doesn't already end with it.
if (!_.endsWith(name, 'Error')) {
name += 'Error';
}
return name;
}
module.exports = {
errNameFromCode: errNameFromCode,
errNameFromDesc: errNameFromDesc,
parseVErrorArgs: parseVErrorArgs
};
|
var vows = require('vows');
var optimizerContext = require('../test-helper').optimizerContext;
vows.describe('advanced optimizer')
.addBatch(
optimizerContext('all optimizations', {
'adjacent': [
'a{display:none}a{display:none;visibility:hidden}',
'a{display:none;visibility:hidden}'
]
}, { advanced: true })
)
.addBatch(
optimizerContext('advanced on & aggressive merging on', {
'repeated' : [
'a{color:red;color:red}',
'a{color:red}'
]
}, { advanced: true, aggressiveMerging: true })
)
.addBatch(
optimizerContext('advanced on & aggressive merging on - IE8 mode', {
'units': [
'.one{width:1px;width:1rem;display:block}.two{color:red}.one{width:2px;width:1.1rem}',
'.one{display:block;width:2px;width:1.1rem}.two{color:red}'
]
}, { advanced: true, aggressiveMerging: true, compatibility: 'ie8' })
)
.addBatch(
optimizerContext('advanced on & aggressive merging off', {
'repeated' : [
'a{color:red;color:red}',
'a{color:red}'
]
}, { advanced: true, aggressiveMerging: false })
)
.addBatch(
optimizerContext('advanced off', {
'repeated' : [
'a{color:red;color:red}',
'a{color:red;color:red}'
]
}, { advanced: false })
)
.addBatch(
optimizerContext('@media', {
'empty': [
'@media (min-width:980px){}',
''
],
'whitespace': [
' @media ( min-width: 980px ){}',
''
],
'body': [
'@media (min-width:980px){\na\n{color:red}}',
'@media (min-width:980px){a{color:red}}'
],
'multiple': [
'@media screen, print, (min-width:980px){a{color:red}}',
'@media screen,print,(min-width:980px){a{color:red}}'
],
'nested once': [
'@media screen { @media print { a{color:red} } }',
'@media screen{@media print{a{color:red}}}'
],
'nested twice': [
'@media screen { @media print { @media (min-width:980px) { a{color:red} } } }',
'@media screen{@media print{@media (min-width:980px){a{color:red}}}}'
]
})
)
.addBatch(
optimizerContext('@font-face', {
'rebuilding': [
'@font-face{font-family:PublicVintage;src:url(/PublicVintage.otf) format(\'opentype\')}',
'@font-face{font-family:PublicVintage;src:url(/PublicVintage.otf) format(\'opentype\')}'
]
})
)
.export(module);
|
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var User = new Schema({
first_name: {
type: String,
required:true
},
last_name: {
type: String,
required: true
},
email: {
type: String,
required: true,
lowercase: true
},
phone: {
type: Number,
required: true
},
dob: {
type: String,
required: true,
},
gender: {
type: String,
required: true
},
faculty: {
type: String,
required: true
},
department: {
type: String,
required: true
},
level: {
type: Number,
required: true
}
}, {
collection: 'users'
});
module.exports = mongoose.model("User", User); |
import React from "react";
import ReactDOM from "react-dom";
import {mount} from "enzyme";
import { Provider } from "react-redux";
import { createStore } from "redux";
import chai from "chai";
import chaiEnzyme from "chai-enzyme";
import { expect as chaiExpect } from "chai"
chai.use(chaiEnzyme());
import { mapValues } from "lodash";
import Form from "../../../../../src/components/forms/Form";
import FieldWrapper from "../../../../../src/components/forms/fields/wrappers/FieldWrapper";
import { fieldWrapperCssClasses as css } from "../../../../../src/components/forms/fields/wrappers/FieldWrapper";
import TextBox from "../../../../../src/components/forms/fields/TextBox";
import combinedReducers from "../../../../../src/reducers/combined";
const selectors = mapValues(css, (raw) => '.' + raw);
let mockWarn, store, wrapper;
beforeEach(() => {
mockWarn = console.warn = jest.fn(() => {});
store = createStore(combinedReducers);
});
afterEach(() => {
mockWarn.mockClear();
wrapper.unmount();
});
test("A fieldId should be generated if not provided", () => {
wrapper = mount(
<Provider store={store}>
<Form formId="FORM1">
<FieldWrapper>
<TextBox></TextBox>
</FieldWrapper>
</Form>
</Provider>
);
const state = store.getState();
expect(state).toHaveProperty("forms.FORM1.fieldsById");
expect(Object.keys(state.forms.FORM1.fieldsById)[0]).not.toEqual("undefined");
})
test("visibility should change on value", () => {
wrapper = mount(
<Provider store={store}>
<Form formId="FORM1">
<FieldWrapper fieldId="FIELD1"
visibleWhen={ [ { fieldId: "FIELD2", is: [ "show" ] }]}>
<TextBox ></TextBox>
</FieldWrapper>
<FieldWrapper fieldId="FIELD2">
<TextBox></TextBox>
</FieldWrapper>
</Form>
</Provider>
);
// Initially the first field should be hidden because the second field is not "show"
const wrappers = wrapper.find(selectors.base);
const inputs = wrapper.find("input");
expect(wrappers).toHaveLength(2);
chaiExpect(wrappers.first()).to.have.style("display", "none");
chaiExpect(wrappers.at(1)).to.have.style("display", "block");
// Change the second field to "show" to reveal the first field
inputs.at(1).node.value = "show";
inputs.at(1).simulate("change", inputs.at(1));
chaiExpect(wrappers.first()).to.have.style("display", "block");
// Change the second field to "shows" to hide the first child again
inputs.at(1).node.value = "shows";
inputs.at(1).simulate("change", inputs.at(1));
chaiExpect(wrappers.first()).to.have.style("display", "none");
})
test("label should be shown", () => {
wrapper = mount(
<Provider store={store}>
<Form formId="FORM1">
<FieldWrapper fieldId="FIELD1"
label="This is a label">
<TextBox></TextBox>
</FieldWrapper>
</Form>
</Provider>
);
chaiExpect(wrapper.find(selectors.label)).to.have.text("This is a label");
})
test("description should NOT be shown", () => {
wrapper = mount(
<Provider store={store}>
<Form formId="FORM1">
<FieldWrapper fieldId="FIELD1">
<TextBox></TextBox>
</FieldWrapper>
</Form>
</Provider>
);
expect(wrapper.find(selectors.description)).toHaveLength(0);
})
test("description should NOT be shown", () => {
wrapper = mount(
<Provider store={store}>
<Form formId="FORM1">
<FieldWrapper fieldId="FIELD1"
description="This is a description">
<TextBox></TextBox>
</FieldWrapper>
</Form>
</Provider>
);
chaiExpect(wrapper.find(selectors.description)).to.have.text("This is a description");
})
test("validation errors are displayed", () => {
wrapper = mount(
<Provider store={store}>
<Form formId="FORM1">
<FieldWrapper fieldId="FIELD1"
validWhen={{
lengthIsGreaterThan: {
length: 4,
message: "Error"
}
}}>
<TextBox value="bob"></TextBox>
</FieldWrapper>
</Form>
</Provider>
);
chaiExpect(wrapper.find(selectors.base)).to.have.style("display", "block");
chaiExpect(wrapper.find(selectors.errors)).to.have.text("Error");
expect(wrapper.find(selectors.invalid)).toHaveLength(1);
})
test("validation errors are NOT displayed", () => {
wrapper = mount(
<Provider store={store}>
<Form formId="FORM1">
<FieldWrapper fieldId="FIELD1"
validWhen={{
lengthIsGreaterThan: {
length: 4,
message: "Error"
}
}}>
<TextBox value="passes test"></TextBox>
</FieldWrapper>
</Form>
</Provider>
);
expect(wrapper.find(selectors.errors)).toHaveLength(0);
})
test("required class name is applied (rule)", () => {
wrapper = mount(
<Provider store={store}>
<Form formId="FORM1">
<FieldWrapper fieldId="REQUIRED_WHEN_1"
requiredWhen={ [ { fieldId: "FIELD2", is: [ "required" ] }]}>
<TextBox></TextBox>
</FieldWrapper>
<FieldWrapper fieldId="FIELD2">
<TextBox value="required"></TextBox>
</FieldWrapper>
</Form>
</Provider>
);
expect(wrapper.find(selectors.required)).toHaveLength(1);
})
test("required class name is applied (declaration)", () => {
wrapper = mount(
<Provider store={store}>
<Form formId="FORM1">
<FieldWrapper fieldId="REQUIRED_DECLARATION"
isRequired={true}>
<TextBox></TextBox>
</FieldWrapper>
</Form>
</Provider>
);
expect(wrapper.find(selectors.required)).toHaveLength(1);
})
test("required class name is NOT applied", () => {
wrapper = mount(
<Provider store={store}>
<Form formId="FORM1">
<FieldWrapper fieldId="FIELD1"
isRequired={false}>
<TextBox></TextBox>
</FieldWrapper>
</Form>
</Provider>
);
expect(wrapper.find(selectors.required)).toHaveLength(0);
})
test("disabled class is applied (rule)", () => {
wrapper = mount(
<Provider store={store}>
<Form formId="FORM1">
<FieldWrapper fieldId="FIELD1"
disabledWhen={ [ { fieldId: "FIELD2", is: [ "disable" ] }]}>
<TextBox></TextBox>
</FieldWrapper>
<FieldWrapper fieldId="FIELD2">
<TextBox value="disable"></TextBox>
</FieldWrapper>
</Form>
</Provider>
);
expect(wrapper.find(selectors.disabled)).toHaveLength(1);
})
test("disabled class is applied (declaration)", () => {
wrapper = mount(
<Provider store={store}>
<Form formId="FORM1">
<FieldWrapper fieldId="FIELD1"
isDisabled={true}>
<TextBox></TextBox>
</FieldWrapper>
</Form>
</Provider>
);
expect(wrapper.find(selectors.disabled)).toHaveLength(1);
})
test("multiple fields assigning updating one attribute", () => {
wrapper = mount(
<Provider store={store}>
<Form formId="FORM1">
<FieldWrapper fieldId="FIELD1"
name="data"
value="initial"
omitWhenValueIs={["custom"]}>
<TextBox/>
</FieldWrapper>
<FieldWrapper fieldId="FIELD2"
name="data"
omitWhenHidden={true}
value="test"
visibleWhen={ [{ fieldId: "FIELD1", is: [ "custom" ]}] }>
<TextBox/>
</FieldWrapper>
</Form>
</Provider>
);
const inputs = wrapper.find("input");
expect(inputs).toHaveLength(2);
chaiExpect(inputs.at(1)).to.have.style("display", "none");
expect(store.getState()).toHaveProperty("forms.FORM1.value", { data: "initial" });
inputs.at(0).node.value = "custom";
inputs.at(0).simulate("change", inputs.at(0));
chaiExpect(inputs.at(1)).to.have.style("display", "inline-block");
expect(store.getState()).toHaveProperty("forms.FORM1.value", { data: "test" });
}) |
/**
* @module lib/launcher
*/
define(function(require) {
'use strict';
var JSMESS = require('./loader');
// Features.
var gamePad = require('./features/gamepad');
var mute = require('./features/mute');
// Utils.
var getRequest = require('./utils/get_request');
var parseQueryString = require('./utils/parse_query_string');
// Parse the location.search QueryString for key/values.
var params = parseQueryString(location.search);
var games;
function getextrahtml(id, folder, file) {
var moduleinfo = document.getElementById(id);
if (!moduleinfo) {
return;
}
getRequest(folder + '/' + file + '.html', function(resp) {
moduleinfo.innerHTML = resp;
});
}
function getgamelist(moduleName) {
getRequest('json/' + moduleName + '-gamelist.json', function(resp) {
games = JSON.parse(resp).games;
ready(moduleName);
});
}
function emustart() {
var select = document.getElementById('selgame');
if (select) {
select.style.display = 'none';
}
}
function init() {
var moduleName = params.module || 'test';
getextrahtml('moduleinfo', 'html', moduleName);
if(!params.game) {
getgamelist(moduleName);
} else {
ready(moduleName);
}
}
function ready(moduleName) {
// Cache the resusable DOM nodes.
var dom = {
fullscreen: document.getElementById('gofullscreen'),
select: document.getElementById('selgame'),
mute: document.getElementById('mute'),
canvas: document.getElementById('canvas')
};
// Determine if JSMESS should default to muted or not.
var shouldMute = params.mute ? params.mute === "true" : true;
// Schedule the mute for when the loader is ready.
mute.toggle(shouldMute);
// Ensure the element exists before binding events to it.
if (dom.mute) {
dom.mute.checked = shouldMute;
dom.mute.addEventListener('click', mute.toggle);
}
var mess = new JSMESS(dom.canvas)
.setprecallback(emustart)
.setscale(params.scale ? parseFloat(params.scale) : 1)
.setmodule(moduleName);
var setgame = function(game, moduleName) {
game = (game == 'NONE') ? undefined : game;
if (game) {
getextrahtml('gameinfo', 'gamehtml', game);
} else {
document.getElementById('gameinfo').innerHTML = '';
}
mess.setgame(game ? 'roms/' + moduleName + '/' + game : undefined);
};
var isfullscreensupported = function() {
return !!(getfullscreenenabler());
};
var getfullscreenenabler = function() {
return dom.canvas.webkitRequestFullScreen || canvas.mozRequestFullScreen ||
canvas.requestFullScreen;
};
var gofullscreen = function() {
getfullscreenenabler().call(dom.canvas);
};
// If the fullscreen toggle exists and fullscreen is supported bind the
// toggle event listener.
if (dom.fullscreen && isfullscreensupported()) {
dom.fullscreen.addEventListener('click', gofullscreen);
}
// Otherwise if only the button exists, set it to a disabled state.
else if (dom.fullscreen) {
dom.fullscreen.disabled = true;
}
// Build up the games list if they exists.
if (dom.select && games) {
for(var i = 0; i < games.length; i++) {
var o = document.createElement('option');
o.textContent = games[i];
o.value = games[i];
dom.select.appendChild(o);
}
dom.select.addEventListener('change', function(e) {
setgame(e.target.value);
});
}
// Otherwise, hide the selection.
else if (dom.select) {
dom.select.style.display = 'none';
}
setgame(games ? games[0] : params.game, moduleName);
if (params.autostart) {
mess.start();
}
// Gamepad text
if (gamePad.isSupported) {
var gamepadDiv = document.getElementById('gamepadtext');
gamepadDiv.innerHTML = 'No gamepads detected. Press a button on a gamepad to use it.';
gamePad.pollForDevices(function(connected) {
if (connected.length === 1) {
gamepadDiv.innerHTML = '1 gamepad detected.';
}else {
gamepadDiv.innerHTML = connected.length + ' gamepads detected.';
}
if (mess.hasStarted) {
gamepadDiv.innerHTML += '<br />Restart MESS to use new gamepads.';
}
});
}
}
init();
});
|
/*
MIT License
Copyright (c) 2022 Looker Data Sciences, Inc.
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.
*/
import React from 'react'
import { ExtensionProvider2 } from '@looker/extension-sdk-react'
import { hot } from 'react-hot-loader/root'
import { Looker40SDK } from '@looker/sdk'
import { FileUpload } from './FileUpload'
export const App = hot(() => {
return (
<ExtensionProvider2 type={Looker40SDK}>
<FileUpload />
</ExtensionProvider2>
)
})
|
$(document).ready(function() {
$("#formSearch button").prop("disabled", true);
$("#formSearch button").css("transition", "0.5s all");
$("#player").keyup(function() {
if ($("#player").val().length <= 0) {
$("#tribe").prop("disabled", false);
}
else {
$("#tribe").prop("disabled", true);
}
checkSubmit();
});
$("#tribe").keyup(function() {
if ($("#tribe").val().length <= 0) {
$("#player").prop("disabled", false);
}
else {
$("#player").prop("disabled", true);
}
checkSubmit();
});
function checkSubmit()
{
if ($("#player").val().length > 0 || $("#tribe").val().length > 0) {
$("#formSearch button").prop("disabled", false);
}
else {
$("#formSearch button").prop("disabled", true);
}
}
$("#formSearch").submit(function( e ) {
e.preventDefault();
var player = $("#player").val(),
tribe = $("#tribe").val();
$("#formSearch button").removeClass("btn-primary").addClass("btn-warning");
$("#formSearch button").prop("disabled", true);
if (player.length > 0 && tribe.length > 0)
{
$("#player").val("");
$("#tribe").val("");
}
else if (player.length > 0)
{
location.href = "/Atelier%20801%20Experiments/search/p/" + encodeURIComponent(player) + "/";
}
else if (tribe.length > 0)
{
location.href = "/Atelier%20801%20Experiments/search/t/" + encodeURIComponent(tribe) + "/";
}
$("#formConnexion button").removeClass("btn-warning").addClass("btn-primary");
});
}); |
/**
*
* Marker
*
*/
import React, { PropTypes } from 'react';
import RaisedButton from 'material-ui/RaisedButton';
// import { FormattedMessage } from 'react-intl';
// import messages from './messages';
function Marker(props) {
return (
<span>
<RaisedButton label={props.text || 'test'} />
</span>
);
}
Marker.propTypes = {
text: PropTypes.string,
};
export default Marker;
|
import map from '../../../src/state/map/reducers';
import {GET_MAP_ID, SET_MAP_ID, GET_IS_EDITING, GET_OL3_MAP, SET_OL3_MAP, SAVE_MAP_SUCCESS, SAVE_MAP_ERROR, SET_USER_LOGGED_IN, SET_CHECK_LOGIN} from '../../../src/state/actiontypes';
describe('map', () => {
let defaultState;
beforeEach(function() {
defaultState = {
id: undefined,
userLoggedIn: false,
checkLogin: false,
save: {
success: false,
error: false,
errorMessage: undefined
}
}
});
it('has initial state', () => {
assert.deepEqual(map(undefined, {}), defaultState);
});
describe('GET_MAP_ID', () => {
it('is undefined in initial state', () => {
let action = { type: GET_MAP_ID};
assert.equal(map(undefined, action), undefined);
});
describe('map id is set', () => {
it('returns map id', () => {
let action = { type: GET_MAP_ID};
assert.equal(map({id: 1}, action), 1);
});
});
});
describe('SET_MAP_ID', () => {
it('sets the map ID in state', () => {
let action = { type: SET_MAP_ID, mapId: 1};
let state = Object.assign({}, defaultState, { id: 1});
assert.deepEqual(map(undefined, action), state);
});
});
describe('GET_IS_EDITING', () => {
it('is undefined in initial state', () => {
let action = { type: GET_IS_EDITING};
assert.equal(map(undefined, action), false);
});
describe('map id is set', () => {
it('returns map id', () => {
let action = { type: GET_IS_EDITING};
assert.equal(map({id: 1}, action), true);
});
});
});
describe('SAVE_MAP_SUCCESS', () => {
it('sets the new map id in state', () => {
let action = { type: SAVE_MAP_SUCCESS, result: {id: 1}};
let state = Object.assign({}, defaultState, { id: 1, save: { success: true, error: false}});
assert.deepEqual(map(undefined, action), state);
});
});
describe('SAVE_MAP_ERROR', () => {
it('sets the errorMessage and error', () => {
let action = { type: SAVE_MAP_ERROR, error: {text: 'Failure'}};
let state = Object.assign({}, defaultState, { save: { success: false, error: true, errorMessage: { text: 'Failure'}}});
assert.deepEqual(map(undefined, action), state);
});
});
describe('SET_USER_LOGGED_IN', () => {
it('sets if the user is logged in', () => {
let action = {type: SET_USER_LOGGED_IN, loggedIn: true};
let state = Object.assign({}, defaultState, { userLoggedIn: true});
assert.deepEqual(map(undefined, action), state);
});
});
describe('SET_CHECK_LOGIN', () => {
it('sets if the user is logged in', () => {
let action = {type: SET_CHECK_LOGIN, check: true};
let state = Object.assign({}, defaultState, { checkLogin: true});
assert.deepEqual(map(undefined, action), state);
});
});
});
|
import React from 'react';
const VideoListItem = ({video, onVideoSelect}) => {
const imageURL = video.snippet.thumbnails.default.url;
return (
<li onClick={ () => onVideoSelect(video) } className="list-group-item">
<div className="video-list media">
<div className="media-left">
<img className="media-object" src={imageURL} />
</div>
</div>
<div className="media-body">
<div className="media-heading">{video.snippet.title}</div>
</div>
</li>
);
};
export default VideoListItem;
|
/*
*handling post request
*/
parseForm = require('../modules/mortgageCalc');
weather = require('../modules/weather');
currency = require('../modules/currency');
var request = require('request');
var routes = require('../routes');
WE = require('../modules/parseJson');
var fs = require('fs');
exports.morData = function(req, res) {
parseForm.printRes(req);
var monthlyInst = parseForm.calculateMonthlyInst(req);
var biMonthlyInst = parseForm.calculateBiMonthlyInst(req);
console.log(' Monthly Inst = ' + monthlyInst);
console.log(' Bi Monthly Inst = ' + biMonthlyInst);
// res.send('mission', routes.mission);
res.render('resultmortgage', {
monthlyInst: monthlyInst,
biMonthlyInst: biMonthlyInst
});
};
exports.weatherData = function(req, res) {
parseForm.printRes(req);
var url = 'http://api.worldweatheronline.com/free/v2/weather.ashx?key=2699c2d06bc888d90e7064bc31eaa&q=' + req.body.city + '&num_of_days=1&format=json';
weather.getWeatherCity(url, function(result) {
var r_city = WE.getValueFromJson('query', result, function() {});
var r_weather = WE.getValueFromJson('temp_F', result, function() {});
var r_todayDate = WE.getValueFromJson('date', result, function() {});
var r_sunrise = WE.getValueFromJson('sunrise', result, function() {});
var r_sunset = WE.getValueFromJson('sunset', result, function() {});
var r_desc = WE.getValueFromJson('weatherDesc', result, function() {});
var r_srcurl = WE.getValueFromJson('weatherIconUrl', result, function() {});
res.render('resultweather', {
city: r_city,
weather: r_weather,
todayDate: r_todayDate,
sunrise: r_sunrise,
sunset: r_sunset,
desc: r_desc,
srcurl: r_srcurl
});
});
};
exports.carLoan = function(req, res) {
parseForm.printRes(req);
};
exports.getTodaysRate = function(req, res) {
// console.log("RESULT = req = " + req.query.currFrom);
// var ram1 = currency.getTodayRate(req, function() {});
// console.log("RAMMM ram1 = " + ram1);
// var ram = WE.getValueFromJson('rate', function() {});
// console.log("RAMMM = " + ram);
var rawUrl = "http://jsonrates.com/get/?";
var key = "&apiKey=jr-45bd80322cf6cbe3c6bfaede65f4e998";
var currF = req.query.currFrom;
var currT = req.query.currTo;
console.log(' currF == ' + currF);
console.log(' currT == ' + currT);
var rate;
var finalUrl = rawUrl + "from=" + currF + "&to=" + currT + key;
request(finalUrl, function(err, resp, body) {
var result;
if (err) console.log(' ****** ERROR FROM SERVICE ****** ');
else{
console.log(' BODY == ' + body);
rate = WE.getValueFromJson('rate', body, function() {});
}
res.send(rate);
});
};
|
const sendJson = require('../../../../packages/api-pls-express-router/util/send-json');
describe('sendJson', function() {
beforeEach(() => {
this.res = {
send: stub()
};
});
describe('when passing in nothing', () => {
it('should call `res.send` with the right arguments', () => {
sendJson(this.res);
assert(this.res.send.calledOnce, 'res.send was not called');
const arg = new Buffer(JSON.stringify({}));
assert.deepEqual(arg, this.res.send.getCall(0).args[0]);
});
});
describe('when passing in an object', () => {
it('should call `res.send` with the right arguments', () => {
const someObj = {
name: 'sandwiches'
};
sendJson(this.res, someObj);
assert(this.res.send.calledOnce, 'res.send was not called');
const arg = new Buffer(JSON.stringify(someObj));
assert.deepEqual(arg, this.res.send.getCall(0).args[0]);
});
});
});
|
/**
* Controllers
*/
var start = 0;
var totalScore = 0 ;
var scanInterval;
var truckInterval;
var RATING_RETURN;
var allImageArray=[1001,
1002,
1003,
1004,
1005,
1006,
1007,
1008,
1009,
100,
1010,
1011,
1012,
1013,
1014,
1015,
1016,
1017,
1018,
1019,
101,
1020,
1021,
1022,
1023,
1024,
1025,
1026,
1027,
1028,
1029,
102,
1030,
1031,
1032,
1033,
1034,
1035,
1036,
1037,
1038,
1039,
103,
1040,
1041,
1042,
1043,
1044,
1045,
1046,
1047,
1048,
1049,
104,
1050,
1051,
1052,
1053,
1054,
1055,
1056,
1057,
1058,
1059,
105,
1060,
1061,
1062,
1063,
1064,
1065,
1066,
1067,
1068,
1069,
106,
1070,
1071,
1072,
1073,
1074,
1075,
1076,
1077,
1078,
1079,
107,
1080,
1081,
1082,
1083,
1084,
1085,
1086,
1087,
1088,
1089,
108,
1090,
1091,
1092,
1093,
1094,
1095,
1096,
1097,
1098,
1099,
109,
10,
1100,
1101,
1102,
1103,
1104,
1105,
1106,
1107,
1108,
1109,
110,
1110,
1111,
1112,
1113,
1114,
1115,
1116,
1117,
1118,
1119,
111,
1120,
1121,
1122,
1123,
1124,
1125,
1126,
1127,
1128,
1129,
112,
1130,
1131,
1132,
1133,
1134,
1135,
1136,
1137,
1138,
1139,
113,
1140,
1141,
1142,
1143,
1144,
1145,
1146,
1147,
1148,
1149,
114,
1150,
1151,
1152,
1153,
1154,
1155,
1156,
1157,
1158,
1159,
115,
1160,
1161,
1162,
1163,
1164,
1165,
1166,
1167,
1168,
1169,
116,
1170,
1171,
1172,
1173,
1174,
1175,
1176,
1177,
1178,
1179,
117,
1180,
1181,
1182,
1183,
1184,
1185,
1186,
1187,
1188,
1189,
118,
1190,
1191,
1192,
1193,
1194,
1195,
1196,
1197,
1198,
1199,
119,
11,
1200,
1201,
1202,
1203,
1204,
1205,
1206,
1207,
1208,
1209,
120,
1210,
1211,
1212,
1213,
1214,
1215,
1216,
1217,
1218,
1219,
121,
1220,
1221,
1222,
1223,
1224,
1225,
1226,
1227,
1228,
1229,
122,
1230,
1231,
1232,
1233,
1234,
1235,
1236,
1237,
1238,
1239,
123,
1240,
1241,
1242,
1243,
1244,
1245,
1246,
1247,
1248,
1249,
124,
1250,
1251,
1252,
1253,
1254,
1255,
1256,
1257,
1258,
1259,
125,
1260,
1261,
1262,
1263,
1264,
1265,
1266,
1267,
1268,
1269,
126,
1270,
1271,
1272,
1273,
1274,
1275,
1276,
1277,
1278,
1279,
127,
1280,
1281,
1282,
1283,
1284,
1285,
1286,
1287,
1288,
1289,
128,
1290,
1291,
1292,
1293,
1294,
1295,
129,
12,
130,
131,
132,
133,
134,
135,
136,
137,
138,
139,
13,
140,
141,
142,
143,
144,
145,
146,
147,
148,
149,
14,
150,
151,
152,
153,
154,
155,
156,
157,
158,
159,
15,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
16,
170,
171,
172,
173,
174,
175,
176,
177,
178,
179,
17,
180,
181,
182,
183,
184,
185,
186,
187,
188,
189,
18,
190,
191,
192,
193,
194,
195,
196,
197,
198,
199,
19,
1,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
20,
210,
211,
212,
213,
214,
215,
216,
217,
218,
219,
21,
220,
221,
222,
223,
224,
225,
226,
227,
228,
229,
22,
230,
231,
232,
233,
234,
235,
236,
237,
238,
239,
23,
240,
241,
242,
243,
244,
245,
246,
247,
248,
249,
24,
250,
251,
252,
253,
254,
255,
256,
257,
258,
259,
25,
260,
261,
262,
263,
264,
265,
266,
267,
268,
269,
26,
270,
271,
272,
273,
274,
275,
276,
277,
278,
279,
27,
280,
281,
282,
283,
284,
285,
286,
287,
288,
289,
28,
290,
291,
292,
293,
294,
295,
296,
297,
298,
299,
29,
2,
300,
301,
302,
303,
304,
305,
306,
307,
308,
309,
30,
310,
311,
312,
313,
314,
315,
316,
317,
318,
319,
31,
320,
321,
322,
323,
324,
325,
326,
327,
328,
329,
32,
330,
331,
332,
333,
334,
335,
336,
337,
338,
339,
33,
340,
341,
342,
343,
344,
345,
346,
347,
348,
349,
34,
350,
351,
352,
353,
354,
355,
356,
357,
358,
359,
35,
360,
361,
362,
363,
364,
365,
366,
367,
368,
369,
36,
370,
371,
372,
373,
374,
375,
376,
377,
378,
379,
37,
380,
381,
382,
383,
384,
385,
386,
387,
388,
389,
38,
390,
391,
392,
393,
394,
395,
39,
3,
401,
402,
403,
404,
405,
406,
407,
408,
409,
40,
410,
411,
412,
413,
414,
415,
41,
42,
43,
44,
45,
46,
47,
48,
49,
4,
501,
502,
503,
504,
505,
506,
507,
508,
509,
50,
510,
511,
512,
513,
514,
515,
516,
517,
518,
519,
51,
520,
521,
522,
523,
524,
525,
526,
527,
528,
529,
52,
530,
531,
532,
533,
534,
535,
536,
537,
538,
539,
53,
540,
541,
542,
543,
544,
545,
546,
547,
548,
549,
54,
550,
551,
552,
553,
554,
555,
556,
557,
558,
559,
55,
560,
561,
562,
563,
564,
565,
566,
567,
568,
569,
56,
570,
571,
572,
573,
574,
575,
576,
577,
578,
579,
57,
580,
581,
582,
583,
584,
585,
586,
587,
588,
589,
58,
590,
591,
592,
593,
594,
59,
5,
601,
602,
603,
604,
605,
606,
607,
608,
609,
60,
610,
611,
612,
613,
614,
615,
616,
617,
618,
619,
61,
620,
621,
622,
623,
624,
625,
626,
627,
628,
629,
62,
630,
631,
632,
633,
634,
635,
636,
637,
638,
639,
63,
640,
641,
642,
643,
644,
645,
646,
647,
648,
649,
64,
650,
651,
652,
653,
654,
655,
656,
657,
658,
659,
65,
660,
661,
662,
663,
664,
665,
666,
667,
668,
669,
66,
670,
671,
672,
673,
674,
675,
676,
677,
678,
679,
67,
680,
681,
682,
683,
684,
685,
686,
687,
688,
689,
68,
690,
691,
692,
693,
694,
695,
696,
697,
698,
699,
69,
6,
700,
701,
702,
703,
704,
705,
706,
707,
708,
709,
70,
710,
711,
712,
713,
714,
715,
716,
717,
718,
719,
71,
720,
721,
722,
723,
724,
72,
73,
74,
75,
76,
77,
78,
79,
7,
801,
802,
803,
804,
805,
806,
807,
808,
809,
80,
810,
811,
812,
813,
814,
815,
816,
817,
818,
819,
81,
820,
821,
822,
823,
824,
825,
826,
827,
828,
829,
82,
830,
831,
832,
833,
834,
835,
836,
837,
838,
839,
83,
840,
841,
842,
843,
844,
845,
846,
847,
848,
84,
85,
86,
87,
88,
89,
8,
90,
91,
92,
93,
94,
95,
96,
97,
98,
99,
9];
var MAX_VALUE_RATING = 9;
var MIN_VALUE_RATING = 1;
const NUMBER_OF_QUESTION = PAIR_IMAGE_SHOWING ;
angular.module('myApp.controller', ['ui.bootstrap'])
.service('scoreService', function(){
var result = {
score: 0,
round : 5
};
return {
getScore: function () {
return result.score;
},
setScore: function(value) {
result.score = value;
},
getRound : function () {
return result.round;
},
setRound : function (value) {
result.round = value;
}
};
})
.controller("ShowController", function($scope, $state){
var imageArray = All_Image_Show_Array;
var currentIndex = 0 ;
$scope.finishShowing = false;
$scope.first = "bg/1a";
console.log("length before start: " + imageArray.length);
var imageInterval = setInterval(function(){
showOnePairImage();
}, 2 * 1000);
function showOnePairImage(){
var imageNumber = imageArray[currentIndex++];
console.log("Image: " + imageNumber +" index: " + currentIndex);
$scope.first = "bg/" + imageNumber;
$scope.$apply();
checkFinishShowing();
}
function checkFinishShowing(){
if( currentIndex === imageArray.length ){
clearInterval(imageInterval);
console.log("Clear interval here");
$scope.$apply(function(){
$scope.finishShowing = true;
});
}
}
function getRandomImage( max){
return Math.floor((Math.random() * max) );
}
function getImagePosition(){
return ( Math.floor((Math.random() * 100) + 1) % 2) ;
}
function generateImageArray() {
var imageArray = [] ;
for( var i = 0; i < 150; i++){
var randomIndex = getRandomImage(allImageArray.length);
imageArray.push(allImageArray[randomIndex]);
}
return imageArray;
}
})
.controller("TestController", function($scope, $state, $timeout,
$modal, $log, scoreService) {
var LEFT_CLICKED, LEFT_TRUE;
var QuestionNumber = 0, AI_SUGGEST, TOTAL_SCORE = 0 ;
var INITIAL_DELAY_TIMEOUT;
var imagePairs = WX_target;
var AI_choice = AI_suggestion;
var resultArray = Y_target;
$scope.animationsEnabled = true;
$scope.first = "bg/1a";
$scope.second = "bg/1b";
$scope.showAnswer = false;
$scope.open = function (size) {
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: 'myModalContent.html',
controller: 'RatingModalController',
size: size,
resolve: {
result: function () {
return $scope.result;
}
}
});
modalInstance.result.then(function (selectedItem) {
console.log("Return rating value: " + selectedItem);
if( selectedItem >= MIN_VALUE_RATING && selectedItem <= MAX_VALUE_RATING){
console.log("User select to close the dialog");
if( QuestionNumber < NUMBER_OF_QUESTION){
setTimeout(function(){
resetToStartNewRound();
showOnePairImage();
}, 1000);
}else{
scoreService.setRound(QuestionNumber);
scoreService.setScore(TOTAL_SCORE);
$state.go('summary');
}
}
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
INITIAL_DELAY_TIMEOUT = setTimeout(function(){
showOnePairImage();
}, 3 * 1000);
function resetToStartNewRound(){
$scope.selectImage = "";
$scope.suggestImage = "";
$scope.showAnswer = false;
}
function showOnePairImage(){
QuestionNumber++;
AI_SUGGEST = AI_choice[QuestionNumber];
if( resultArray[QuestionNumber]){
LEFT_TRUE = true;
}else{
LEFT_TRUE = false;
}
console.log("Image Left: " + imagePairs[QuestionNumber].left
+" Image Right " + imagePairs[QuestionNumber].right + " current question: " + QuestionNumber);
setImage(imagePairs[QuestionNumber].left, imagePairs[QuestionNumber].right);
checkFinishShowing();
}
$scope.clickImage = function (leftClick) {
$scope.showAnswer = true;
LEFT_CLICKED = leftClick;
if( LEFT_CLICKED){
$scope.selectImage = "LEFT";
}else{
$scope.selectImage = "RIGHT";
}
if( AI_SUGGEST ){
$scope.suggestImage = "LEFT";
}else{
$scope.suggestImage = "RIGHT";
}
};
$scope.clickFinalAnswer = function(leftClick){
LEFT_CLICKED = leftClick;
checkResult();
$scope.open('lg');
};
function checkResult(){
if( (LEFT_CLICKED && LEFT_TRUE) || (!LEFT_CLICKED && !LEFT_TRUE) ){
$scope.result = true;
TOTAL_SCORE++;
}else{
$scope.result = false;
}
}
function setImage(leftImage,rightImage ){
$scope.first = "bg/" + leftImage;
$scope.second = "bg/" + rightImage;
$scope.$apply();
}
function checkFinishShowing(){
if( QuestionNumber === PAIR_IMAGE_SHOWING){
console.log("Finish the test here");
}
}
})
.controller('RatingModalController', function ($scope, $modalInstance, result) {
if( result){
$scope.finalResult = "CORRECT";
}else{
$scope.finalResult = "WRONG";
}
$scope.rate = {
value : 5
};
$scope.max = MAX_VALUE_RATING;
$scope.isReadonly = false;
$scope.next = function () {
$modalInstance.close($scope.rate.value);
};
$scope.hoveringOver = function (value) {
$scope.overStar = value;
$scope.percent = value;
};
$scope.ratingStates = [
{stateOn: 'glyphicon-ok-sign', stateOff: 'glyphicon-ok-circle'},
{stateOn: 'glyphicon-star', stateOff: 'glyphicon-star-empty'},
{stateOn: 'glyphicon-heart', stateOff: 'glyphicon-ban-circle'},
{stateOn: 'glyphicon-heart'},
{stateOff: 'glyphicon-off'}
];
})
.controller('SummaryController', function($scope, scoreService){
$scope.rate = {
value : 5
};
$scope.max = MAX_VALUE_RATING;
$scope.isReadonly = false;
$scope.showScore = false;
$scope.hoveringOver = function (value) {
$scope.overStar = value;
$scope.percent = value;
};
$scope.guess = function () {
$scope.score = scoreService.getScore();
$scope.round = scoreService.getRound();
$scope.showScore = true;
};
$scope.ratingStates = [
{stateOn: 'glyphicon-ok-sign', stateOff: 'glyphicon-ok-circle'},
{stateOn: 'glyphicon-star', stateOff: 'glyphicon-star-empty'},
{stateOn: 'glyphicon-heart', stateOff: 'glyphicon-ban-circle'},
{stateOn: 'glyphicon-heart'},
{stateOff: 'glyphicon-off'}
];
})
;
|
import * as Chatbot from '../src/chatbot/chatbot-service';
import dialog from '../src/coaching-chatbot/dialog';
import * as Messenger from '../src/facebook-messenger/messenger-service';
import * as Sessions from '../src/util/sessions-service';
import * as sinon from 'sinon';
export function generate(discussions, states) {
const messengerSpy = sinon.spy(Messenger, "send");
var clock = sinon.useFakeTimers(new Date().getTime());
const sessions = new Sessions();
const bot = new Chatbot(dialog, sessions);
sessions.db.load(states);
let scenarios = [];
let promise = bot.receive('', '');
let messageQueue = {};
function newTitle(title) {
scenarios.push({
title: '# ' + title,
content: []
});
}
function newContent(line) {
scenarios[scenarios.length - 1].content.push(line);
}
function addBotReply(output) {
for (let botReply of output) {
for (let message of botReply.message.replace('\n\n', '\n').split('\n')) {
if (message.length > 0) {
newContent('| ' + message + ' | |');
}
}
if (botReply.quickReplies.length > 0) {
newContent('| [' +
botReply.quickReplies
.map((quickReply) => quickReply.title)
.join('] [') + '] | |');
}
}
}
for (let scenario in discussions) {
const messages = discussions[scenario].messages;
const sessionID = discussions[scenario].session;
if (discussions[scenario].time) {
promise = promise.then(() => {
clock = sinon.useFakeTimers(new Date(discussions[scenario].time).getTime());
});
}
if (discussions[scenario].hide) {
for (let message of messages) {
promise = promise.then(() => {
return bot.receive(sessionID, message);
});
}
} else {
promise = promise.then(() => {
newTitle(scenario);
newContent('| Kehitystön vertaisohjausrobotti | ' + discussions[scenario].player + ' |');
newContent('|-|-|');
});
promise = promise.then(() => {
if (messageQueue[sessionID] != undefined) {
addBotReply(messageQueue[sessionID]);
messageQueue[sessionID] = undefined;
}
});
for (let message of messages) {
promise = promise.then(() => {
newContent('| | ' + message + ' |');
return bot.receive(sessionID, message);
}).then((output) => {
addBotReply(output);
});
}
}
promise = promise.then(() => {
if (messengerSpy.callCount > 0) {
for (let call of messengerSpy.args) {
if (!messageQueue[call[0]]) {
messageQueue[call[0]] = [];
}
messageQueue[call[0]].push({
message: call[1],
quickReplies: call[2] || {}
});
}
messengerSpy.reset();
clock.reset();
}
});
}
return promise
.then(() => messengerSpy.restore())
.then(() => scenarios);
}
|
/**
* @author GJS <1353990812@qq.com>
*
* GJS reserves all rights not expressly granted.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 GJS
*
* 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.
*
* @providesModule CustomDropDownPage
* @flow
*/
/*
控件功能:弹出框,drop-down 动画
相关界面:...
*/
'use strict';
import React,{
Component
} from 'react'
import {
View,
StyleSheet,
Animated,
Dimensions,
ListView,
Text,
Easing,
TouchableWithoutFeedback,
TouchableOpacity,
Image,
} from 'react-native'
import {
Platform
} from 'react-native'
import BasePopupPage from './BasePopupPage'
var animConfigs = {
isRTL: true,
}
export default class CustomDropDownPage extends BasePopupPage{
constructor(props){
super(props);
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
...this.state,
bounceValueAnimated: new Animated.Value(1),
ds: ds.cloneWithRows(['x', 'x', 'o', 'o']),
}
}
dismissAnimate = (animateConfigs) => {
if (animateConfigs && typeof animateConfigs.animate === 'function') {
animateConfigs.animate();
return;
};
Animated.sequence([ // 首先执行decay动画,结束后同时执行spring和twirl动画
// Animated.decay(position, { // 滑行一段距离后停止
// velocity: {x: gestureState.vx, y: gestureState.vy}, // 根据用户的手势设置速度
// deceleration: 0.997,
// }),
Animated.parallel([ // 在decay之后并行执行:
// Animated.spring(position, {
// toValue: {x: 0, y: 0} // 返回到起始点开始
// }),
// Animated.timing(twirl, { // 同时开始旋转
// toValue: 360,
// }),
Animated.timing(this.state.fadeInOpacity, {
toValue: 0, // 目标值
duration: 200, // 动画时间
easing: Easing.linear // 缓动函数
}),
Animated.timing(this.state.heightAnimated, {
toValue: 0, // 目标值
duration: 200, // 动画时间
easing: Easing.linear // 缓动函数
}),
]),
]).start(); // 执行这一整套动画序列
}
showAnimate = (animateConfigs, width, height) => {
if (animateConfigs && typeof animateConfigs.animate === 'function') {
animateConfigs.animate(width, height);
return;
};
this.setState({
width: width || this.state.width,
height: height || this.state.height,
});
Animated.timing(this.state.fadeInOpacity, {
toValue: 0.4, // 目标值
duration: 200, // 动画时间
easing: Easing.linear // 缓动函数
}).start();
Animated.timing(this.state.heightAnimated, {
toValue: this.state.height, // 目标值
duration: 200, // 动画时间
easing: Easing.linear // 缓动函数
}).start();
}
componentDidMount(){
//
console.log('this.state.widthAnimated.__getValue(): --> ' + this.state.widthAnimated.__getValue());
console.log('this.state.heightAnimated.__getValue(): --> ' + this.state.heightAnimated.__getValue());
// console.log('this.state.translateAnimated: --> (' + this.state.translateAnimated.__getValue().x + ', ' + this.state.translateAnimated.__getValue().y + ')');
}
render(){
return this.renderBaseContainer(
{
style: {
top: 0,
// left: (Dimensions.get('window').width - this.state.widthAnimated) / 2,
alignSelf: 'flex-start',
},
children: (
<ListView
enableEmptySections={true}
dataSource={this.state.ds}
renderRow={this._renderRow}
/>
)
}
);
}
_renderRow=(rowData: Object, sectionID: number, rowID: number) =>{
return (
<TouchableOpacity >
<View style={styles.row}>
<Text style={[styles.text, {fontSize:15,color:'#3b3b3b',marginLeft:0,marginTop:13}]}>
{rowData}
</Text>
</View>
<View style={{width:Dimensions.get('window').width,height:0.7,backgroundColor:'#D0D0D0'}}/>
</TouchableOpacity>
);
}
}
const side = animConfigs.isRTL ? 'right' : 'left';
const styles = StyleSheet.create({
modal: {
position: 'absolute',
},
modalContainer: {
position: 'absolute',
[side] : 0,
top: 0,
},
text: {
textAlign: 'center',
marginLeft: 6,
marginTop: 13,
flex: 1,
fontSize: 15,
color: '#3b3b3b',
},
overlay:{
position: 'absolute',
zIndex: 998,
backgroundColor: 'black',
top: 0,
left: 0,
right: 0,
bottom: 0,
},
container:{
// position: 'absolute',
position: 'relative',
flex: 1,
alignSelf: 'center',
zIndex: 999,
backgroundColor: '#ffffff',
// top: 0,
// left: 0,
},
row: {
flex: 1,
height: 44,
flexDirection: 'row',
overflow: 'hidden',
},
});
|
/**
* Copyright Victor Berchet
*
* This file is part of VisuGps3
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
/**
* @fileoverview Decorates an IProj for google maps.
* @author Victor Berchet <victor@suumit.com>
*/
goog.provide('vgps3.proj.GProj');
goog.require('vgps3.proj.IProj');
/**
* @param {vgps3.proj.IProj} projection
* @param {number=} opt_scale0 The resolution at zoom level 0 = world width in meters.
* @constructor
*/
vgps3.proj.GProj = function(projection, opt_scale0) {
/**
* @type {vgps3.proj.IProj}
* @private
*/
this.projection_ = projection;
/**
* @type {number} The resolution at zoom level 0
* @private
*/
this.scale0_;
/**
* @type {number}
* @private
*/
this.x0_ = projection.getOrigin().x;
/**
* @type {number}
* @private
*/
this.y0_ = projection.getOrigin().y;
this.setScale0(opt_scale0);
};
/**
* Forward projection
*
* @param {google.maps.LatLng} latLng The coordinates.
*
* @return {google.maps.Point} The projected coordinates.
*/
vgps3.proj.GProj.prototype.fromLatLngToPoint = function(latLng) {
var coord = this.projection_.forward(latLng.lat(), latLng.lng());
return new google.maps.Point(
(coord.x - this.x0_) / this.scale0_,
(this.y0_ - coord.y) / this.scale0_
);
};
/**
* Inverse projection
*
* @param {google.maps.Point} point The projected coordinates.
* @param {boolean=} opt_nowrap Whether to wrap the coordinates.
*
* @return {google.maps.LatLng} latLng The coordinates.
*/
vgps3.proj.GProj.prototype.fromPointToLatLng = function(point, opt_nowrap) {
var coord = this.projection_.inverse(
this.x0_ + point.x * this.scale0_,
this.y0_ - point.y * this.scale0_
);
return new google.maps.LatLng(coord.lat, coord.lng, opt_nowrap);
};
/**
* @param {number=} scale0
*/
vgps3.proj.GProj.prototype.setScale0 = function(scale0) {
this.scale0_ = scale0 ? scale0 : 1;
};
goog.exportSymbol('vgps3.proj.GProj', vgps3.proj.GProj);
goog.exportSymbol('vgps3.proj.GProj.fromLatLngToPoint', vgps3.proj.GProj.prototype.fromLatLngToPoint);
goog.exportSymbol('vgps3.proj.GProj.fromPointToLatLng', vgps3.proj.GProj.prototype.fromPointToLatLng);
|
{
String.prototype.startsWith.apply(null);
}
|
require("./modules/BarcodeScannerPage").create();
tabris.create("Drawer").append(tabris.create("PageSelector"));
tabris.ui.children("Page")[0].open();
|
version https://git-lfs.github.com/spec/v1
oid sha256:53bebd62154083f87bfb6129436b4665674e5662ee0179c440ff75cf6adf058c
size 12425
|
import { waitForEmails } from '/test/end-to-end/tests/_support/emails';
import { _ } from 'lodash';
module.exports = function() {
this.When(/^I send the email$/, function() {
server.execute((userEmail) => {
const emailActions = require('/imports/server/email-actions');
emailActions.sendPasswordResetEmail(userEmail);
}, this.user.email);
});
this.When(/^I send the email with (\d+) delay$/, function(delay) {
server.execute((userEmail, sendDelay) => {
const emailActions = require('/imports/server/email-actions');
Meteor.setTimeout(() => {
emailActions.sendPasswordResetEmail(userEmail);
}, sendDelay);
}, this.user.email, delay);
});
this.Then(/^I should receive it$/, function() {
const history = waitForEmails();
expect(history.length).to.equal(1);
// TODO check for email subject and body based on user i18n
console.log(history[0]);
expect(history[0].to).to.equal(this.user.email);
});
this.Then(/^I should receive it async$/, function() {
const emails = waitForEmails();
expect(emails[0].to).to.equal(this.user.email);
// TODO check for email subject and body based on user i18n
});
this.Then(/^I should receive both$/, function() {
const history = waitForEmails(2);
// TODO check for email subject and body based on user i18n
expect(history.length).to.equal(2);
});
const assetMailBasic = function(emailAddress, language, emailCode) {
const history = waitForEmails();
const matching = _.filter(history, (email) => {
return email.to === emailAddress && email.subject.indexOf(emailCode) > 0;
});
expect(matching.length).to.equal(1);
const email = matching[0];
// Assert footer data
expect(email.text).to.contain("******");
const supportEmail = server.execute( function(lang) {
const settings = require('/imports/lib/settings');
return settings.getSupportEmailByLanguage(lang);
}, language);
expect(email.text).to.contain(supportEmail);
return email;
};
this.Then(/^User (.*) should receive an email with code EU([0-9]+)$/, function(userKey, emailCode) {
const theUser = this.accounts.getUserByKey(userKey);
assetMailBasic.bind(this)(theUser.email, theUser.personalInformation.language,'EU' + emailCode);
});
this.Then(/^User (.*) should receive an email with code ET([0-9]+)$/, function(userKey, emailCode) {
const theUser = this.accounts.getUserByKey(userKey);
const email = assetMailBasic.bind(this)(theUser.email, theUser.personalInformation.language, 'ET' + emailCode);
console.log('email', email);
expect(email.text).to.contain("Invoice ID");
expect(email.text).to.contain("USD Requested");
expect(email.text).to.contain("Invoice Date");
});
this.Then(/^User (.*) should receive an email with code E([U,T][0-9]+) containing (.*)$/, function(userKey, emailCode, content) {
const theUser = this.accounts.getUserByKey(userKey);
const email = assetMailBasic.bind(this)(theUser.email, theUser.personalInformation.language, emailCode);
expect(email.text).to.contain(content);
});
this.Then(/^User (.*) should receive an email in '(.+)' with code E([U,T][0-9]+) containing (.*)$/, function(userKey, emailAddress, emailCode, content) {
const theUser = this.accounts.getUserByKey(userKey);
const email = assetMailBasic.bind(this)(emailAddress, theUser.personalInformation.language, emailCode);
expect(email.text).to.contain(content);
});
};
|
(function(){
//App.loop();
function connect(method, location, callback) {
var request = new XMLHttpRequest(),
response;
request.open(method, location, false);
request.send();
if (request.status === 200) {
response = request.responseText;
}
return {
respond: function() {
return response;
},
custom: callback || function() {
return this;
}
};
}
var numList = document.getElementById("numberList"),
listTwo = document.getElementById("listTwo"),
defaultTest = document.getElementById("defaultTest"),
duplicate = document.getElementById("multipleContainer"),
dataGrabber = connect("GET", "js/data.js");
var App = new TemplateHelper();
if (dataGrabber.respond() !== undefined){
dataGrabber = JSON.parse(dataGrabber.respond());
}
App.createItem("li", dataGrabber.list, numList, true);
App.createItem("section", dataGrabber.list, listTwo, true);
App.populateItem("all", dataGrabber.default, defaultTest, ["p", "div"]);
App.cloneItem(duplicate, ["div"], dataGrabber.multiple);
})();
|
'use strict';
const common = require('../common');
const assert = require('assert');
const spawn = require('child_process').spawn;
const expectedError = common.isWindows ? /\bENOTSUP\b/ : /\bEPERM\b/;
if (common.isWindows || process.getuid() !== 0) {
assert.throws(() => {
spawn('echo', ['fhqwhgads'], { uid: 0 });
}, expectedError);
}
if (common.isWindows || !process.getgroups().some((gid) => gid === 0)) {
assert.throws(() => {
spawn('echo', ['fhqwhgads'], { gid: 0 });
}, expectedError);
}
|
"use strict";
require("dotenv").config();
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const Emulator = require("../test-util/emulator");
const messenger_options = [{
name: "line",
options: {
line_channel_secret: process.env.LINE_CHANNEL_SECRET
}
}];
chai.use(chaiAsPromised);
const should = chai.should();
const user_id = "dummy_user_id";
for (let messenger_option of messenger_options){
let emu = new Emulator(messenger_option.name, messenger_option.options);
describe("Test modify_previous_parameter from " + emu.messenger_type, async function(){
beforeEach(async () => {
await emu.clear_context(user_id);
})
describe("Say expression which means modify previous parameter,", async function(){
it("asks previously confirmed parameter.", async function(){
let context = await emu.send(emu.create_postback_event(user_id, {data: JSON.stringify({
_type: "intent",
intent: {
name: "test-modify-previous-parameter"
},
language: "ja"
})}));
context.confirming.should.equal("a");
context = await emu.send(emu.create_message_event(user_id, "a"));
context.confirming.should.equal("b");
context.confirmed.a.should.equal("a");
context.previous.confirmed[0].should.equal("a");
context.previous.processed[0].should.equal("a");
context = await emu.send(emu.create_message_event(user_id, "訂正"));
context.confirming.should.equal("a");
context.confirmed.a.should.equal("a");
context.previous.confirmed.should.have.lengthOf(0);
context.previous.processed.should.have.lengthOf(0);
})
})
describe("If previously processed parameter is not confirmed,", async function(){
it("rewinds one more processed parameter.", async function(){
let context = await emu.send(emu.create_postback_event(user_id, {data: JSON.stringify({
_type: "intent",
intent: {
name: "test-modify-previous-parameter"
},
language: "ja"
})}));
context.confirming.should.equal("a");
context = await emu.send(emu.create_message_event(user_id, "skip"));
context.confirming.should.equal("c");
context.confirmed.a.should.equal("skip");
context.previous.confirmed.should.deep.equal(["a"]);
context.previous.processed.should.deep.equal(["b", "a"]);
context = await emu.send(emu.create_message_event(user_id, "訂正"));
context.confirming.should.equal("a");
context.confirmed.a.should.equal("skip");
context.previous.confirmed.should.deep.equal([]);
context.previous.processed.should.deep.equal([]);
context = await emu.send(emu.create_message_event(user_id, "a"));
context.confirming.should.equal("b");
context.confirmed.a.should.equal("a");
context.previous.confirmed.should.deep.equal(["a"]);
context.previous.processed.should.deep.equal(["a"]);
})
})
describe("If previously processed parameter has been confirmed before but not right before,", async function(){
it("rewinds one more processed parameter.", async function(){
let context = await emu.send(emu.create_postback_event(user_id, {data: JSON.stringify({
_type: "intent",
intent: {
name: "test-modify-previous-parameter"
},
language: "ja"
})}));
context.confirming.should.equal("a");
context = await emu.send(emu.create_message_event(user_id, "a"));
context.confirming.should.equal("b");
context = await emu.send(emu.create_message_event(user_id, "b"));
context.confirming.should.equal("c");
context = await emu.send(emu.create_message_event(user_id, "訂正"));
context.confirming.should.equal("b");
context = await emu.send(emu.create_message_event(user_id, "訂正"));
context.confirming.should.equal("a");
context = await emu.send(emu.create_message_event(user_id, "skip"));
context.confirming.should.equal("c");
context = await emu.send(emu.create_message_event(user_id, "訂正"));
context.confirming.should.equal("a");
})
})
describe("Trigger modify_previous_parameter by intent postback", async function(){
it("should ask previously confirmed parameter.", async function(){
let context = await emu.send(emu.create_postback_event(user_id, {data: JSON.stringify({
_type: "intent",
intent: {
name: "test-modify-previous-parameter"
},
language: "ja"
})}));
context.confirming.should.equal("a");
context = await emu.send(emu.create_message_event(user_id, "a"));
context.confirming.should.equal("b");
context = await emu.send(emu.create_postback_event(user_id, {data: JSON.stringify({
_type: "intent",
intent: {
name: "modify-previous-parameter"
}
})}));
context.confirming.should.equal("a");
})
})
describe("Run bot.modify_previous_parameter in reaction without options", async function(){
it("asks previously confirmed parameter and retain confirmed value.", async function(){
let context = await emu.send(emu.create_postback_event(user_id, {data: JSON.stringify({
_type: "intent",
intent: {
name: "test-modify-previous-parameter"
},
language: "ja"
})}));
context.confirming.should.equal("a");
context = await emu.send(emu.create_message_event(user_id, "a"));
context.confirming.should.equal("b");
context.confirmed.a.should.equal("a");
context = await emu.send(emu.create_message_event(user_id, "modify_prev_param"));
context.confirming.should.equal("a");
context.confirmed.a.should.equal("a");
})
})
describe("Run bot.modify_previous_parameter in reaction with clear_confirmed: true", async function(){
it("asks previously confirmed parameter and clear confirmed value.", async function(){
let context = await emu.send(emu.create_postback_event(user_id, {data: JSON.stringify({
_type: "intent",
intent: {
name: "test-modify-previous-parameter"
},
language: "ja"
})}));
context.confirming.should.equal("a");
context = await emu.send(emu.create_message_event(user_id, "a"));
context.confirming.should.equal("b");
context.confirmed.a.should.equal("a");
context = await emu.send(emu.create_message_event(user_id, "modify_prev_param_and_clear"));
context.confirming.should.equal("a");
should.not.exist(context.confirmed.a);
})
})
});
}
|
module.exports = function (app) {
var express = require('express'),
jwt = require('jsonwebtoken'),
config = require('./../../config'),
router = express.Router();
router.use(function (req, res, next) {
console.log('\n --- Server method: ' + req.method + ' ---\n');
next();
});
require('./root')(router);
require('./gameSettings')(router);
require('./auth')(router);
// route middleware to verify a token
router.use(function(req, res, next) {
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.secret, function(err, decoded) {
if (err) {
return res.status(403).json({ success: false, message: 'Failed to authenticate token.' });
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
require('./check')(router);
require('./users')(router);
app.use('/api', router);
}
|
require('./proof')(3, prove)
function prove (async, okay) {
var strata = createStrata({ directory: tmp, leafSize: 3, branchSize: 3 })
async(function () {
serialize(__dirname + '/fixtures/leaf-remainder.before.json', tmp, async())
}, function () {
strata.open(async())
}, function () {
strata.mutator('b', async())
}, function (cursor) {
cursor.insert('b', 'b', ~cursor.index)
cursor.unlock(async())
}, function () {
gather(strata, async())
}, function (records) {
okay(records, [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' ], 'records')
strata.balance(async())
}, function () {
gather(strata, async())
}, function (records) {
okay(records, [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' ], 'records after balance')
vivify(tmp, async())
load(__dirname + '/fixtures/leaf-remainder.after.json', async())
}, function (actual, expected) {
okay(actual, expected, 'split')
}, function() {
strata.close(async())
})
}
|
import FS from "fs";
import Path from "path";
import _ from "lodash-fp";
import { split, fill } from "../helpers";
export const title = "Day 6: Probably a Fire Hazard";
export function createGrid(width, height, value = false) {
let rows = fill(value, Array(height));
const columns = () => fill(value, Array(width));
return _.map(columns, rows);
}
function parse(instruction) {
const toIntegers = _.compose(_.map(_.parseInt(10)), split(","));
const [mode, pointA, pointB] = instruction.match(/(on|off|toggle)|(\d+),(\d+)/g);
return {
mode,
pointA: toIntegers(pointA),
pointB: toIntegers(pointB)
};
}
export function configureLighting(grid, modes, instructions) {
const {mode, pointA, pointB} = parse(instructions);
const operation = modes[mode];
const [x1, y1] = pointA;
const [x2, y2] = pointB;
const columns = _.range(x1, x2 + 1);
const rows = _.range(y1, y2 + 1);
_.map((y) => {
_.map((x) => {
grid[y][x] = operation(grid[y][x]);
}, columns);
}, rows);
return grid;
}
export function run() {
const inputPath = Path.join(__dirname, "input.txt");
const input = FS.readFileSync(inputPath, "utf-8").trim().split("\n");
const total = _.compose(_.sum, _.map(_.sum));
const grid = createGrid(1000, 1000);
const modes = {
"on": () => true,
"off": () => false,
"toggle": (x) => !x
};
const grid2 = createGrid(1000, 1000);
const modes2 = {
"on": (x) => x + 1,
"off": (x) => Math.max(0, x - 1),
"toggle": (x) => x + 2
};
input.forEach((instructions) => {
configureLighting(grid, modes, instructions);
configureLighting(grid2, modes2, instructions);
});
console.log("After following the instructions, how many lights are lit?", total(grid));
console.log("What is the total brightness of all lights combined after following Santa's instructions?", total(grid2));
}
|
/*global expect*/
describe('to have an item satisfying assertion', function() {
it('requires a third argument', function() {
expect(
function() {
expect([1, 2, 3], 'to have an item satisfying');
},
'to throw',
'expected [ 1, 2, 3 ] to have an item satisfying\n' +
' The assertion does not have a matching signature for:\n' +
' <array> to have an item satisfying\n' +
' did you mean:\n' +
' <array-like> [not] to have an item [exhaustively] satisfying <any>\n' +
' <array-like> [not] to have an item [exhaustively] satisfying <assertion>'
);
});
it('only accepts arrays as the subject', function() {
expect(
function() {
expect(42, 'to have an item satisfying', 'to be a number');
},
'to throw',
"expected 42 to have an item satisfying 'to be a number'\n" +
' The assertion does not have a matching signature for:\n' +
' <number> to have an item satisfying <string>\n' +
' did you mean:\n' +
' <array-like> [not] to have an item [exhaustively] satisfying <any>\n' +
' <array-like> [not] to have an item [exhaustively] satisfying <assertion>'
);
});
it('fails if the given array is empty', function() {
expect(
function() {
expect([], 'to have an item satisfying', 'to be a number');
},
'to throw',
'expected [] to have an item satisfying to be a number\n' +
' expected [] not to be empty'
);
});
it('asserts that at least one item in the array satisfies the RHS expectation', function() {
expect(['foo', 1], 'to have an item satisfying', 'to be a number');
expect(['foo', 1], 'to have an item satisfying', function(item) {
expect(item, 'to be a number');
});
expect(
[0, 1, 'foo', 2],
'to have an item satisfying',
'not to be a number'
);
expect(
[[1], [2]],
'to have an item satisfying',
'to have an item satisfying',
'to be a number'
);
});
it('asserts that no items in the array satisfies the RHS expectation', function() {
expect(['foo', 'bar'], 'not to have an item satisfying', 'to be a number');
expect(['foo', 'bar'], 'not to have an item satisfying', function(item) {
expect(item, 'to be a number');
});
expect(
[0, 1, 42, 2],
'not to have an item satisfying',
'not to be a number'
);
expect(
[['bar'], ['bar']],
'not to have an item satisfying',
'to have an item satisfying',
'to be a number'
);
});
it("throws the correct error if none of the subject's values match the RHS expectation", function() {
expect(
function() {
expect(
['foo', 'bar'],
'to have an item satisfying',
expect.it('to be a number')
);
},
'to throw',
"expected [ 'foo', 'bar' ] to have an item satisfying expect.it('to be a number')"
);
});
it("throws the correct error, when negated, if any of the subject's values match the RHS expectation", function() {
expect(
function() {
expect(
['foo', 1],
'not to have an item satisfying',
expect.it('to be a number')
);
},
'to throw',
"expected [ 'foo', 1 ] not to have an item satisfying expect.it('to be a number')\n\n" +
'[\n' +
" 'foo',\n" +
' 1 // should be removed\n' +
']'
);
});
it('formats non-Unexpected errors correctly', function() {
expect(
function() {
expect(
[
[
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20
]
],
'to have an item satisfying',
// prettier-ignore
function (item) {
expect.fail(function (output) {
output.text('foo').nl().text('bar');
});
}
);
},
'to throw',
'expected\n' +
'[\n' +
' [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]\n' +
']\n' +
'to have an item satisfying\n' +
'function (item) {\n' +
' expect.fail(function (output) {\n' +
" output.text('foo').nl().text('bar');\n" +
' });\n' +
'}'
);
});
it('provides the item index to the callback function', function() {
var arr = ['0', '1', '2', '3'];
expect(arr, 'to have an item satisfying', function(item, index) {
expect(index, 'to be a number');
expect(index, 'to be', parseInt(item, 10));
});
});
describe('delegating to an async assertion', function() {
var clonedExpect = expect
.clone()
.addAssertion('to be a number after a short delay', function(
expect,
subject,
delay
) {
expect.errorMode = 'nested';
return expect.promise(function(run) {
setTimeout(
run(function() {
expect(subject, 'to be a number');
}),
1
);
});
});
it('should succeed', function() {
return clonedExpect(
[1, 2, 3],
'to have an item satisfying',
'to be a number after a short delay'
);
});
});
describe('with the exhaustively flag', function() {
it('should succeed', function() {
expect(
[{ foo: 'bar', quux: 'baz' }],
'to have an item exhaustively satisfying',
{ foo: 'bar', quux: 'baz' }
);
});
it('should fail when the spec is not met only because of the "exhaustively" semantics', function() {
expect(
function() {
expect(
[{ foo: 'bar', quux: 'baz' }],
'to have an item exhaustively satisfying',
{ foo: 'bar' }
);
},
'to throw',
"expected [ { foo: 'bar', quux: 'baz' } ]\n" +
"to have an item exhaustively satisfying { foo: 'bar' }"
);
});
});
});
|
'use strict';
var ENCODING = require('../Encoding');
require('../../ArrayExtensions');
var directoryNames = ['en', 'hu'];
var dirGlobPattern = '@(' + directoryNames.join('|') + ')';
var suffix = '.dict.txt';
// read through selected directories
var glob = require('glob');
var fs = require('fs');
var path = require('path');
var winston = require('winston');
var logger = winston.createLogger({
transports: [
new(winston.transports.Console)({
// colorize: true,
timestamp: true,
// prettyPrint: true,
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple(),
)
}),
new(winston.transports.File)({
filename: 'update_dictionaries.log',
json: false
})
]
});
var options = {
nocase: true
};
function normalize(word) {
return word.toLocaleLowerCase();
}
function encodeWord(word, encodeMap) {
var i,
j,
k,
currentLetter,
currentEncodedLetter,
doubleLetter,
tripleLetter,
currentEncodedDoubleLetter,
currentEncodedTripleLetter,
encodedWords = [],
doubleLetterWords = [],
tripleLetterWords = [],
result = [];
encodedWords.push('');
for (i = 0; i < word.length; i += 1) {
currentLetter = word[i];
if (encodeMap.has(currentLetter)) {
currentEncodedLetter = encodeMap.get(currentLetter);
} else {
currentEncodedLetter = currentLetter;
}
if (i < word.length - 1) {
doubleLetter = currentLetter + word[i + 1];
if (encodeMap.has(doubleLetter)) {
currentEncodedDoubleLetter = encodeMap.get(doubleLetter);
} else {
currentEncodedDoubleLetter = '';
}
}
if (i < word.length - 2) {
tripleLetter = currentLetter + word[i + 1] + word[i + 2];
if (encodeMap.has(tripleLetter)) {
currentEncodedTripleLetter = encodeMap.get(tripleLetter);
} else {
currentEncodedTripleLetter = '';
}
}
for (j = 0; j < encodedWords.length; j += 1) {
if (currentEncodedTripleLetter) {
if (!tripleLetterWords[i + 3]) {
tripleLetterWords[i + 3] = [];
}
tripleLetterWords[i + 3].push(encodedWords[j] + currentEncodedTripleLetter);
}
if (currentEncodedDoubleLetter) {
if (!doubleLetterWords[i + 2]) {
doubleLetterWords[i + 2] = [];
}
doubleLetterWords[i + 2].push(encodedWords[j] + currentEncodedDoubleLetter);
}
encodedWords[j] = encodedWords[j] + currentEncodedLetter;
}
for (j = 0; j < doubleLetterWords.length; j += 1) {
if (j === i + 1) {
if (doubleLetterWords[j]) {
for (k = 0; k < doubleLetterWords[j].length; k += 1) {
encodedWords.push(doubleLetterWords[j][k]);
}
}
}
}
for (j = 0; j < tripleLetterWords.length; j += 1) {
if (j === i + 1) {
if (tripleLetterWords[j]) {
for (k = 0; k < tripleLetterWords[j].length; k += 1) {
encodedWords.push(tripleLetterWords[j][k]);
}
}
}
}
}
for (i = 0; i < encodedWords.length; i += 1) {
if (encodedWords[i].length > 1) {
// include only words that have more than one character
result.push(encodedWords[i]);
}
}
return result;
};
function processWords(filename) {
var words = fs.readFileSync(filename).toString().split('\n');
words = words.LUnique();
logger.info('Processing ' + words.length + ' words ...');
var fname = path.basename(filename);
var language = path.basename(path.dirname(filename));
var name = fname.slice(0, fname.indexOf(suffix));
var dictFilename = name + '.json';
var result = {
source: path.join(language, fname),
language: language,
name: name,
numWords: 0,
numUniqueWords: 0,
dict: path.join(language, dictFilename)
};
var dict = {
language: language,
name: name,
numWords: 0,
numUniqueWords: 0,
encodeMap: {},
decodeMap: {},
root: {}
};
var i;
var j;
var k;
var key;
var value;
var shouldSkip;
var normalized;
var encodedWords;
var encodedWord;
var sortedEncodedWord;
var letter;
var node = dict.root;
var skipped = [];
var isConsonant = ENCODING.get(language).get('isConsonant');
var isVowel = ENCODING.get(language).get('isVowel');
var encodeMap = ENCODING.get(language).get('encodeMap');
dict.encodeMap = encodeMap.toJSON();
for (key in dict.encodeMap) {
if (dict.encodeMap.hasOwnProperty(key)) {
value = dict.encodeMap[key];
if (dict.decodeMap[value]) {
throw new Error('Ambiguous key/value: ' + key + ' ' + value + ' current value ' + dict.decodeMap[value]);
}
dict.decodeMap[value] = key;
}
}
for (i = 0; i < words.length; i += 1) {
// encode the word, then split letters to an array and sort them alphabetically.
shouldSkip = false;
words[i] = words[i].trim().toLowerCase();
normalized = normalize(words[i]);
for (j = 0; j < normalized.length; j += 1) {
if ((isConsonant(normalized[j]) ||
isVowel(normalized[j])) === false) {
shouldSkip = true;
break;
}
}
if (shouldSkip) {
skipped.push(words[i]);
continue;
}
encodedWords = encodeWord(normalized, encodeMap);
for (j = 0; j < encodedWords.length; j += 1) {
encodedWord = encodedWords[j];
sortedEncodedWord = encodedWord.split('').sort();
for (k = 0; k < sortedEncodedWord.length; k += 1) {
letter = sortedEncodedWord[k];
if (node.hasOwnProperty(letter) === false) {
node[letter] = {};
}
node = node[letter];
}
if (!node._) {
node._ = [];
}
node._.push(encodedWord);
//console.log(sortedEncodedWord, encodedWord, node._, node.$);
node = dict.root;
dict.numWords += 1;
}
dict.numUniqueWords += 1;
}
if (skipped.length) {
logger.warn(skipped.length + ' words were skipped.');
logger.warn('Skipped words: ' + skipped.join(', '));
}
result.numWords = dict.numWords;
result.numUniqueWords = dict.numUniqueWords;
fs.writeFileSync(path.join(path.dirname(filename), dictFilename), JSON.stringify(dict));
logger.info(result);
logger.info('Done.');
return result;
};
logger.info('Searching for word lists ... ');
glob(path.join(__dirname, '..', dirGlobPattern, '*' + suffix), options, function(err, files) {
if (err) {
logger.error(err);
return;
}
var i;
var info;
var dictionaries = [];
for (i = 0; i < files.length; i += 1) {
logger.info('Found: ' + files[i]);
info = processWords(files[i]);
dictionaries.push(info);
}
// generate an index file
fs.writeFileSync(path.join(__dirname, '..', 'info.json'), JSON.stringify(dictionaries, null, 2));
}); |
//static properties are accessible only on the class, rather than its instance.
//Circle.pi instead of var a = new Cricle, a.pi
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Grid = (function () {
function Grid(scale) {
this.scale = scale;
}
Grid.prototype.distanceFromOrigin = function (point) {
var xDist = point.x - Grid.origin.x;
var yDist = point.y - Grid.origin.y;
return Math.sqrt(xDist ^ 2 + yDist ^ 2) / this.scale;
};
Grid.origin = { x: 0, y: 0 }; //set static value
return Grid;
}());
var grid1 = new Grid(1);
var grid2 = new Grid(5);
console.log(Grid.origin);
console.log(grid1.distanceFromOrigin({ x: 10, y: 10 }));
console.log(grid2.distanceFromOrigin({ x: 10, y: 10 }));
//Abstract classes sets a guide for its subclasses. bit like interfaces.
//it has properties and methods
//methods with 'abstract' doesnt have implementation and must be implemented in subclass.
var Animal = (function () {
function Animal(name) {
this.name = name;
}
Animal.prototype.move = function () {
console.log('moving around..');
};
return Animal;
}());
var Cat = (function (_super) {
__extends(Cat, _super);
function Cat() {
_super.call(this, 'kitty'); //constructor in subclass must call super
}
//this method must be implemented
Cat.prototype.makeSound = function () {
console.log('meow meow');
};
return Cat;
}(Animal));
//let animal = new Animal() //error. cannot make instance of abstract class.
var cat = new Cat();
cat.makeSound();
|
import expect from 'expect'
import { ChatBotUtil } from 'src/'
describe('ChatBotUtil', () => {
it('Creates a text message', () => {
const callback = () => {}
expect(ChatBotUtil.textMessage('Hello')).toEqual({
content: {text: 'Hello'},
isInbound: false,
type: 'text',
actions: []
})
expect(ChatBotUtil.textMessage()).toEqual({content: {text: undefined}, isInbound: false, type: 'text', actions: []})
expect(ChatBotUtil.textMessage('Hi', ChatBotUtil.makeReplyButton('Hello')))
.toEqual({
content: {text: 'Hi'},
isInbound: false,
type: 'text',
actions: [{title: 'Hello', callback: undefined, type: 'quick-reply'}]
})
expect(ChatBotUtil.textMessage('Question?', ChatBotUtil.makeReplyButton('Yes'), ChatBotUtil.makeReplyButton('No', callback)))
.toEqual({
content: {text: 'Question?'},
isInbound: false,
type: 'text',
actions: [
{title: 'Yes', callback: undefined, type: 'quick-reply'},
{title: 'No', callback: callback, type: 'quick-reply'}]
})
})
it('Creates a user text message', () => {
expect(ChatBotUtil.userTextMessage('Hello')).toEqual({content: {text: 'Hello'}, isInbound: true, type: 'text'})
expect(ChatBotUtil.userTextMessage()).toEqual({content: {text: undefined}, isInbound: true, type: 'text'})
expect(ChatBotUtil.userTextMessage('Hi', ChatBotUtil.makeReplyButton('Hello')))
.toEqual({content: {text: 'Hi'}, isInbound: true, type: 'text'})
})
it('Creates a get started button', () => {
expect(ChatBotUtil.makeGetStartedButton('Start!')).toEqual({title: 'Start!', type: 'get-started'})
expect(ChatBotUtil.makeGetStartedButton('start')).toEqual({title: 'start', type: 'get-started'})
expect(ChatBotUtil.makeGetStartedButton()).toEqual({title: undefined, type: 'get-started'})
})
it('Creates a reply button', () => {
const callback = () => {}
expect(ChatBotUtil.makeReplyButton('Yes')).toEqual({title: 'Yes', callback: undefined, type: 'quick-reply'})
expect(ChatBotUtil.makeReplyButton('yes', callback)).toEqual({
title: 'yes',
callback: callback,
type: 'quick-reply'
})
expect(ChatBotUtil.makeReplyButton()).toEqual({title: undefined, callback: undefined, type: 'quick-reply'})
})
it('Creates a text input', () => {
const callback = () => {}
expect(ChatBotUtil.makeTextInputField('Send', 'Enter your name', callback))
.toEqual({submit: 'Send', placeholder: 'Enter your name', callback: callback, type: 'text-input'})
expect(ChatBotUtil.makeTextInputField('send', 'enter your name', callback))
.toEqual({submit: 'send', placeholder: 'enter your name', callback: callback, type: 'text-input'})
expect(ChatBotUtil.makeTextInputField('Ok'))
.toEqual({submit: 'Ok', placeholder: undefined, callback: undefined, type: 'text-input'})
expect(ChatBotUtil.makeTextInputField(undefined, 'Enter email'))
.toEqual({submit: undefined, placeholder: 'Enter email', callback: undefined, type: 'text-input'})
})
})
describe('ChatBotUtil Array extension', () => {
it('Returns random object from array', () => {
expect(['a', 'b', 'c'].any()).toExist()
expect(['a'].any()).toExist()
expect([].any()).toNotExist()
})
}) |
'use strict';
const isStandardSyntaxAtRule = require('../../utils/isStandardSyntaxAtRule');
const isStandardSyntaxRule = require('../../utils/isStandardSyntaxRule');
const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const styleSearch = require('style-search');
const validateOptions = require('../../utils/validateOptions');
const ruleName = 'no-extra-semicolons';
const messages = ruleMessages(ruleName, {
rejected: 'Unexpected extra semicolon',
});
const meta = {
url: 'https://stylelint.io/user-guide/rules/list/no-extra-semicolons',
};
/**
* @param {import('postcss').Node} node
* @returns {number}
*/
function getOffsetByNode(node) {
// @ts-expect-error -- TS2339: Property 'document' does not exist on type 'Document | Container<ChildNode>'
if (node.parent && node.parent.document) {
return 0;
}
const root = node.root();
if (!root.source) throw new Error('The root node must have a source');
if (!node.source) throw new Error('The node must have a source');
if (!node.source.start) throw new Error('The source must have a start position');
const string = root.source.input.css;
const nodeColumn = node.source.start.column;
const nodeLine = node.source.start.line;
let line = 1;
let column = 1;
let index = 0;
for (let i = 0; i < string.length; i++) {
if (column === nodeColumn && nodeLine === line) {
index = i;
break;
}
if (string[i] === '\n') {
column = 1;
line += 1;
} else {
column += 1;
}
}
return index;
}
/** @type {import('stylelint').Rule} */
const rule = (primary, _secondaryOptions, context) => {
return (root, result) => {
const validOptions = validateOptions(result, ruleName, { actual: primary });
if (!validOptions) {
return;
}
if (root.raws.after && root.raws.after.trim().length !== 0) {
const rawAfterRoot = root.raws.after;
/** @type {number[]} */
const fixSemiIndices = [];
styleSearch({ source: rawAfterRoot, target: ';' }, (match) => {
if (context.fix) {
fixSemiIndices.push(match.startIndex);
return;
}
if (!root.source) throw new Error('The root node must have a source');
complain(root.source.input.css.length - rawAfterRoot.length + match.startIndex);
});
// fix
if (fixSemiIndices.length) {
root.raws.after = removeIndices(rawAfterRoot, fixSemiIndices);
}
}
root.walk((node) => {
if (node.type === 'atrule' && !isStandardSyntaxAtRule(node)) {
return;
}
if (node.type === 'rule' && !isStandardSyntaxRule(node)) {
return;
}
if (node.raws.before && node.raws.before.trim().length !== 0) {
const rawBeforeNode = node.raws.before;
const allowedSemi = 0;
const rawBeforeIndexStart = 0;
/** @type {number[]} */
const fixSemiIndices = [];
styleSearch({ source: rawBeforeNode, target: ';' }, (match, count) => {
if (count === allowedSemi) {
return;
}
if (context.fix) {
fixSemiIndices.push(match.startIndex - rawBeforeIndexStart);
return;
}
complain(getOffsetByNode(node) - rawBeforeNode.length + match.startIndex);
});
// fix
if (fixSemiIndices.length) {
node.raws.before = removeIndices(rawBeforeNode, fixSemiIndices);
}
}
if (typeof node.raws.after === 'string' && node.raws.after.trim().length !== 0) {
const rawAfterNode = node.raws.after;
/**
* If the last child is a Less mixin followed by more than one semicolon,
* node.raws.after will be populated with that semicolon.
* Since we ignore Less mixins, exit here
*/
if (
'last' in node &&
node.last &&
node.last.type === 'atrule' &&
!isStandardSyntaxAtRule(node.last)
) {
return;
}
/** @type {number[]} */
const fixSemiIndices = [];
styleSearch({ source: rawAfterNode, target: ';' }, (match) => {
if (context.fix) {
fixSemiIndices.push(match.startIndex);
return;
}
const index =
getOffsetByNode(node) +
node.toString().length -
1 -
rawAfterNode.length +
match.startIndex;
complain(index);
});
// fix
if (fixSemiIndices.length) {
node.raws.after = removeIndices(rawAfterNode, fixSemiIndices);
}
}
if (typeof node.raws.ownSemicolon === 'string') {
const rawOwnSemicolon = node.raws.ownSemicolon;
const allowedSemi = 0;
/** @type {number[]} */
const fixSemiIndices = [];
styleSearch({ source: rawOwnSemicolon, target: ';' }, (match, count) => {
if (count === allowedSemi) {
return;
}
if (context.fix) {
fixSemiIndices.push(match.startIndex);
return;
}
const index =
getOffsetByNode(node) +
node.toString().length -
rawOwnSemicolon.length +
match.startIndex;
complain(index);
});
// fix
if (fixSemiIndices.length) {
node.raws.ownSemicolon = removeIndices(rawOwnSemicolon, fixSemiIndices);
}
}
});
/**
* @param {number} index
*/
function complain(index) {
report({
message: messages.rejected,
node: root,
index,
result,
ruleName,
});
}
/**
* @param {string} str
* @param {number[]} indices
* @returns {string}
*/
function removeIndices(str, indices) {
for (const index of indices.reverse()) {
str = str.slice(0, index) + str.slice(index + 1);
}
return str;
}
};
};
rule.ruleName = ruleName;
rule.messages = messages;
rule.meta = meta;
module.exports = rule;
|
var searchData=
[
['astaralgorithm',['AStarAlgorithm',['../d5/d12/classAStarAlgorithm.html',1,'']]]
];
|
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const logger = require('morgan');
const passport = require('passport');
const api = require('./routes/api.router');
const User = require('./auth/schema');
const databaseInit = require('./js/databaseInit');
process.on('unhandledRejection', console.log.bind(console));
// set mongoose's promise library to es6 promise library
mongoose.Promise = global.Promise;
// database config
const database = {
name: process.env.APP_DATABASE_NAME || 'app_default_database',
host: process.env.APP_DATABASE_HOST || 'localhost',
seed: process.env.APP_DATABASE_SEED || false,
createAdminUser: process.env.APP_CREATE_ADMIN_USER || false,
customApiKey: process.env.APP_CUSTOM_API_KEY || 'non-secure-api-key',
};
const {
handlePreviousAPIKey,
createAppApiKey,
createAppAdminUser,
} = databaseInit(database);
console.log('\x1b[33mConnecting to MongoDB:', database, '\x1b[0m');
const dbUri = `mongodb://${database.host}/${database.name}`;
mongoose.connect(dbUri);
// mongoose.set('debug', true)
var dbConnection = mongoose.connection;
dbConnection.on(
'error',
console.error.bind(console, 'MongoDB connection error:')
);
dbConnection.on('connected', () => {
console.log('\x1b[32mSuccessfully connected:', dbUri, '\x1b[0m');
const startServer = () => {
const app = express();
app.use(logger('dev'));
// Use the body-parser package in our application
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.use(bodyParser.json({ type: 'application/*+json' }));
// Use the passport package in our application
app.use(passport.initialize());
app.all('/*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header(
'Access-Control-Allow-Headers',
'Origin,X-Requested-With,Content-Type,Accept,X-Access-Token,X-Key,Authorization'
);
if (req.method === 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});
var landing = `<h1>Mock API</h1>`;
app.get('/', (req, res) => {
res.send(landing);
});
app.use('/api/beta/', api);
// If no route is matched by now, it must be a 404
app.use(function(req, res, next) {
res.status(404).send('API Not Found');
});
// Start the server
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
};
handlePreviousAPIKey()
.then(createAppApiKey)
.then(createAppAdminUser)
.then(startServer);
});
|
/**
* isAuthenticated
* @description :: Policy that inject user in `req` via JSON Web Token
*/
import passport from 'passport';
export default function (req, res, next) {
passport.authenticate('jwt', (error, user, info) => {
if (error || !user) return res.negotiate(Object.assign(error || {}, info));
req.user = user;
next();
})(req, res);
}
|
var VERSION = require('./constants').VERSION
function StatusUpdater (socket, titleElement, bannerElement, browsersElement) {
function updateBrowsersInfo (browsers) {
if (!browsersElement) {
return
}
var status
// clear browsersElement
while (browsersElement.firstChild) {
browsersElement.removeChild(browsersElement.firstChild)
}
for (var i = 0; i < browsers.length; i++) {
status = browsers[i].isConnected ? 'idle' : 'executing'
var li = document.createElement('li')
li.setAttribute('class', status)
li.textContent = browsers[i].name + ' is ' + status
browsersElement.appendChild(li)
}
}
var connectionText = 'never-connected'
var testText = 'loading'
var pingText = ''
function updateBanner () {
if (!titleElement || !bannerElement) {
return
}
titleElement.textContent = 'Karma v ' + VERSION + ' - ' + connectionText + '; test: ' + testText + '; ' + pingText
bannerElement.className = connectionText === 'connected' ? 'online' : 'offline'
}
function updateConnectionStatus (connectionStatus) {
connectionText = connectionStatus || connectionText
updateBanner()
}
function updateTestStatus (testStatus) {
testText = testStatus || testText
updateBanner()
}
function updatePingStatus (pingStatus) {
pingText = pingStatus || pingText
updateBanner()
}
socket.on('connect', function () {
updateConnectionStatus('connected')
})
socket.on('disconnect', function () {
updateConnectionStatus('disconnected')
})
socket.on('reconnecting', function (sec) {
updateConnectionStatus('reconnecting in ' + sec + ' seconds')
})
socket.on('reconnect', function () {
updateConnectionStatus('reconnected')
})
socket.on('reconnect_failed', function () {
updateConnectionStatus('reconnect_failed')
})
socket.on('info', updateBrowsersInfo)
socket.on('disconnect', function () {
updateBrowsersInfo([])
})
socket.on('ping', function () {
updatePingStatus('ping...')
})
socket.on('pong', function (latency) {
updatePingStatus('ping ' + latency + 'ms')
})
return { updateTestStatus: updateTestStatus }
}
module.exports = StatusUpdater
|
var Drawables = BaseRealtimeCollection.extend({
backend: 'drawables',
model: Drawable
});
|
jest.mock('src/lib/gql');
jest.mock('src/lib/ga');
import askingReplyFeedback from '../askingReplyFeedback';
import * as apiResult from '../__fixtures__/askingReplyFeedback';
import gql from 'src/lib/gql';
import ga from 'src/lib/ga';
import { UPVOTE_PREFIX, DOWNVOTE_PREFIX } from 'src/lib/sharedUtils';
beforeEach(() => {
gql.__reset();
ga.clearAllMocks();
});
const commonParamsYes = {
data: {
searchedText: '貼圖',
selectedArticleId: 'AWDZYXxAyCdS-nWhumlz',
selectedArticleText:
'(0)(1)(/)(0)(9)(line)免費貼圖\n\n「[全螢幕貼圖]生活市集x生活小黑熊」\nhttps://line.me/S/sticker/10299\n\n「松果購物 x 狗與鹿(動態貼圖) 」\nhttps://line.me/S/sticker/10300\n\n「LINE TV X 我的男孩限免貼圖」\nhttps://line.me/S/sticker/10207',
selectedReplyId: 'AWDZeeV0yCdS-nWhuml8',
},
event: {
type: 'text',
input: `${UPVOTE_PREFIX}Reply is good!`,
timestamp: 1519019734813,
},
issuedAt: 1519019735467,
userId: 'Uaddc74df8a3a176b901d9d648b0fc4fe',
replies: undefined,
isSkipUser: false,
};
it('handles "yes" postback with no other existing feedbacks', async () => {
gql.__push(apiResult.oneFeedback);
expect(await askingReplyFeedback(commonParamsYes)).toMatchSnapshot();
expect(gql.__finished()).toBe(true);
expect(ga.eventMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
Object {
"ea": "Feedback-Vote",
"ec": "UserInput",
"el": "AWDZYXxAyCdS-nWhumlz/AWDZeeV0yCdS-nWhuml8",
},
],
]
`);
expect(ga.sendMock).toHaveBeenCalledTimes(1);
});
it('handles "yes" postback with other existing feedbacks', async () => {
gql.__push(apiResult.twoFeedbacks);
expect(await askingReplyFeedback(commonParamsYes)).toMatchSnapshot();
expect(gql.__finished()).toBe(true);
});
const commonParamsNo = {
data: {
searchedText: '貼圖',
selectedArticleId: 'AWDZYXxAyCdS-nWhumlz',
selectedReplyId: 'AWDZeeV0yCdS-nWhuml8',
},
event: {
type: 'text',
input: `${DOWNVOTE_PREFIX}我覺得不行`,
timestamp: 1519019734813,
},
issuedAt: 1519019735467,
userId: 'Uaddc74df8a3a176b901d9d648b0fc4fe',
replies: undefined,
isSkipUser: false,
};
it('handles "no" postback with no other existing feedbacks', async () => {
gql.__push(apiResult.oneFeedback);
expect(await askingReplyFeedback(commonParamsNo)).toMatchSnapshot();
expect(gql.__finished()).toBe(true);
});
it('handles "no" postback with other existing feedback comments', async () => {
gql.__push(apiResult.twoFeedbacks);
expect(await askingReplyFeedback(commonParamsNo)).toMatchSnapshot();
expect(gql.__finished()).toBe(true);
});
const commonParamsInvalid = {
data: {
searchedText: '貼圖',
selectedArticleId: 'AWDZYXxAyCdS-nWhumlz',
// No selectedReplyId
},
event: {
type: 'text',
input: 'asdasdasd',
timestamp: 1519019734813,
},
issuedAt: 1519019735467,
userId: 'Uaddc74df8a3a176b901d9d648b0fc4fe',
replies: undefined,
isSkipUser: false,
};
it('handles invalid params', async () => {
await expect(
askingReplyFeedback(commonParamsInvalid)
).rejects.toMatchInlineSnapshot(`[Error: selectedReply not set in data]`);
expect(ga.sendMock).toHaveBeenCalledTimes(0);
});
it('gracefully handle graphql error', async () => {
gql.__push(apiResult.error);
await expect(
askingReplyFeedback(commonParamsYes)
).rejects.toMatchInlineSnapshot(
`[Error: Cannot record your feedback. Try again later?]`
);
expect(gql.__finished()).toBe(true);
expect(ga.sendMock).toHaveBeenCalledTimes(0);
});
|
'use strict'
var webpack = require('webpack')
var path = require('path')
var NODE_ENV = process.env.NODE_ENV || 'development'
module.exports = {
entry: {
app: './examples/app.js'
},
output: {
path: path.join(__dirname, './dist'),
filename: 'build.js'
},
watch: NODE_ENV === 'development',
watchOptions: {
aggregateTimeout: 100
},
devtool: NODE_ENV === 'development' ? 'cheap-inline-module-source-map' : null,
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
loader: 'style-loader!css-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.js', '.vue'],
alias: {
vue: 'vue/dist/vue.js'
}
}
}
if (NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
])
} |
Ext.provide('Phlexible.elements.MediaResourceTemplate');
Ext.provide('Phlexible.elements.MainPanel');
Ext.require('Phlexible.elements.ElementsTree');
Ext.require('Phlexible.teasers.ElementLayoutTree');
Ext.require('Phlexible.elements.ElementPanel');
Ext.require('Phlexible.elements.tab.List');
Ext.require('Phlexible.elements.TopToolbar');
Ext.require('Phlexible.elements.FileLinkWindow');
Phlexible.elements.MediaResourceTemplate = new Ext.XTemplate(
'<tpl for=".">',
'<div class="p-elements-result-wrap" id="result-wrap-{id}" style="text-align: center">',
'<div><img src="{[Phlexible.Router.generate(\"mediamanager_media\", {file_id: values.id, template_key: \"_mm_large\"})]}" width="96" height="96" /></div>',
'<span>{name}</span>',
'</div>',
'</tpl>'
);
/**
* Input params:
* - id
* Siteroot ID
* - title
* Siteroot Title
*/
Phlexible.elements.MainPanel = Ext.extend(Ext.Panel, {
title: Phlexible.elements.Strings.content,
strings: Phlexible.elements.Strings,
layout: 'border',
closable: true,
border: false,
cls: 'p-elements-main-panel',
iconCls: 'p-element-component-icon',
baseTitle: '',
loadParams: function (params) {
if (params.diff) {
this.getElementPanel().getComponent(1).getComponent(1).diffParams = params.diff;
}
// load element
if (params.id) {
var loadParams = {
id: params.id,
version: null
};
if (params.language) {
loadParams.language = params.language;
}
this.element.reload(loadParams);
}
// load tree
if (params.start_tid_path) {
if (params.start_tid_path && params.start_tid_path.substr(0, 3) !== '/-1') {
params.start_tid_path = '/-1' + params.start_tid_path;
}
var n = this.getElementsTree().getSelectionModel().getSelectedNode();
if (!n || n.getPath() !== params.start_tid_path) {
this.skipLoad = true;
this.getElementsTree().selectPath(params.start_tid_path, 'id');
}
}
},
initComponent: function () {
this.addEvents('load');
if (this.params.start_tid_path) {
this.skipLoad = true;
if (this.params.start_tid_path.substr(0, 3) !== '/-1') {
this.params.start_tid_path = '/-1' + this.params.start_tid_path;
}
}
if (this.params.title) {
this.setTitle(this.params.title);
this.baseTitle = this.params.title;
}
this.element = new Phlexible.elements.Element({
siteroot_id: this.params.siteroot_id,
language: Phlexible.Config.get('language.frontend'),
startParams: this.params
});
this.element.on({
load: this.onLoadElement,
scope: this
});
this.element.on({
beforeload: this.disable,
beforeSave: this.disable,
beforeSetOffline: this.disable,
beforeSetOfflineAdvanced: this.disable,
load: this.enable,
saveFailure: this.enable,
publishFailure: this.enable,
publishAdvancedFailure: this.enable,
setOfflineFailure: this.enable,
setOfflineAdvancedFailure: this.enable
})
var dummyElement = new Phlexible.elements.Element({});
dummyElement.properties = {
et_type: 'area'
};
this.elementPanelIndex = 0;
this.layoutListPanelIndex = 1;
this.items = [{
region: 'west',
header: false,
width: 230,
split: true,
collapsible: true,
collapseMode: 'mini',
border: false,
layout: 'fit',
items: [
{
xtype: 'tabpanel',
activeTab: 0,
border: true,
cls: 'p-elements-resource-tabs',
items: [
{
title: ' ',
tabTip: this.strings.tree,
iconCls: 'p-element-tree-icon',
layout: 'border',
border: false,
items: [{
xtype: 'elements-tree',
region: 'center',
header: false,
element: this.element,
start_tid_path: this.params.start_tid_path || false,
listeners: {
nodeSelect: this.onNodeSelect,
newElement: function (node) {
this.element.showNewElementWindow(node);
},
newAlias: function (node) {
this.element.showNewAliasWindow(node);
},
scope: this
}
},{
xtype: 'teasers-layout-tree',
region: 'south',
height: 200,
split: true,
collapsible: true,
// collapseMode: 'mini',
collapsed: true,
element: this.element,
listeners: {
teaserselect: function (teaser_id, node, language) {
// this.dataPanel.disable();
// this.catchPanel.disable();
// this.getTopToolbar().enable();
if (!language) language = null;
this.element.setTeaserNode(node);
this.getContentPanel().getLayout().setActiveItem(this.elementPanelIndex);
this.element.loadTeaser(teaser_id, false, language, true);
},
areaselect: function (area_id, node) {
// this.dataPanel.disable();
// this.catchPanel.disable();
// this.getTopToolbar().enable();
this.getContentPanel().getLayout().setActiveItem(this.layoutListPanelIndex);
this.getLayoutListPanel().element.tid = this.element.tid;
this.getLayoutListPanel().element.eid = this.element.eid;
this.getLayoutListPanel().element.language = this.element.language;
this.getLayoutListPanel().element.area_id = area_id;
this.getLayoutListPanel().element.treeNode = node.getOwnerTree().getRootNode();
this.getLayoutListPanel().element.properties.sort_mode = 'free';
this.getLayoutListPanel().element.properties.sort_dir = 'asc';
this.getLayoutListPanel().doLoad(this.getLayoutListPanel().element);
},
scope: this
}
}]
},
{
xtype: 'grid',
tabTip: this.strings.element_search,
title: ' ',
iconCls: 'p-element-preview-icon',
cls: 'p-elements-resource-search-panel',
viewConfig: {
forceFit: true,
emptyText: this.strings.no_results,
deferEmptyText: false
},
store: new Ext.data.JsonStore({
url: Phlexible.Router.generate('elements_search_elements'),
baseParams: {
siteroot_id: this.element.siteroot_id,
query: '',
language: this.element.language
},
root: 'results',
fields: ['tid', 'version', 'title', 'icon'],
sortInfo: {field: 'title', direction: 'ASC'}
}),
sm: new Ext.grid.RowSelectionModel({
singleSelect: true
}),
columns: [
{
dataIndex: 'title',
header: this.strings.elements,
renderer: function (v, md, r) {
var icon = '<img src="' + r.data.icon + '" width="18" height="18" style="vertical-align: middle;" />';
var title = r.data.title;
var meta = r.data.tid;
return icon + ' ' + title + ' [' + meta + ']';
}
}
],
tbar: [
{
xtype: 'textfield',
emptyText: this.strings.element_search,
enableKeyEvents: true,
anchor: '-10',
listeners: {
render: function (c) {
c.task = new Ext.util.DelayedTask(c.doSearch, this);
},
keyup: function (c, event) {
if (event.getKey() == event.ENTER) {
c.task.cancel();
c.doSearch();
return;
}
c.task.delay(500);
},
scope: this
},
doSearch: function () {
var c = this.getComponent(0).getComponent(0).getComponent(1);
var query = c.getTopToolbar().items.items[0].getValue();
if (!query) return;
var store = c.getStore();
store.baseParams.query = query;
store.baseParams.language = this.element.language;
store.load();
}.createDelegate(this)
}
],
listeners: {
rowdblclick: function (c, itemIndex) {
var r = c.getStore().getAt(itemIndex);
if (!r) return;
this.element.reload({id: r.data.tid, version: r.data.version, language: this.element.language, lock: 1});
},
scope: this
}
},
{
xtype: 'panel',
tabTip: this.strings.media_search,
title: ' ',
iconCls: 'p-mediamanager-component-icon',
layout: 'fit',
bodyStyle: 'padding: 5px',
autoScroll: true,
border: false,
items: {
xtype: 'dataview',
cls: 'p-elements-resource-media-panel',
store: new Ext.data.JsonStore({
url: Phlexible.Router.generate('elements_search_media'),
baseParams: {
siteroot_id: this.element.siteroot_id,
query: ''
},
root: 'results',
fields: ['id', 'version', 'name', 'folder_id'],
autoLoad: false
}),
itemSelector: 'div.p-elements-result-wrap',
overClass: 'p-elements-result-wrap-over',
style: 'overflow: auto',
singleSelect: true,
emptyText: this.strings.no_results,
deferEmptyText: false,
//autoHeight: true,
tpl: Phlexible.elements.MediaResourceTemplate,
listeners: {
render: function (c) {
var v = c;
this.imageDragZone = new Ext.dd.DragZone(v.getEl(), {
ddGroup: 'imageDD',
containerScroll: true,
getDragData: function (e) {
var sourceEl = e.getTarget(v.itemSelector, 10);
if (sourceEl) {
d = sourceEl.cloneNode(true);
d.id = Ext.id();
return v.dragData = {
sourceEl: sourceEl,
repairXY: Ext.fly(sourceEl).getXY(),
ddel: d,
record: v.getRecord(sourceEl)
};
}
},
getRepairXY: function () {
return this.dragData.repairXY;
}
});
},
contextmenu: function (view, index, node, event) {
var record = view.store.getAt(index);
if (!record) {
return;
}
if (this.imageSearchContextMenu) {
this.imageSearchContextMenu.destroy();
}
this.imageSearchContextMenu = new Ext.menu.Menu({
items: [
{
text: 'File Links',
handler: function (menu) {
var window = new Phlexible.elements.FileLinkWindow({
file_id: record.data.id,
file_name: record.data.name
});
window.show();
},
scope: this
}
]
});
event.stopEvent();
var coords = event.getXY();
this.imageSearchContextMenu.showAt([coords[0], coords[1]]);
},
scope: this
}
},
tbar: [
{
xtype: 'textfield',
emptyText: this.strings.media_search,
enableKeyEvents: true,
anchor: '-10',
listeners: {
render: function (c) {
c.task = new Ext.util.DelayedTask(c.doSearch, this);
},
keyup: function (c, event) {
if (event.getKey() == event.ENTER) {
c.task.cancel();
c.doSearch();
return;
}
c.task.delay(500);
},
scope: this
},
doSearch: function () {
var viewWrap = this.getComponent(0).getComponent(0).getComponent(2);
var view = viewWrap.getComponent(0);
var query = viewWrap.getTopToolbar().items.items[0].getValue();
if (!query) return;
var store = view.getStore();
store.baseParams.query = query;
store.load();
}.createDelegate(this)
}
]
},
{
xtype: 'grid',
tabTip: this.strings.history,
title: ' ',
iconCls: 'p-element-tab_history-icon',
cls: 'p-elements-resource-history-panel',
border: false,
viewConfig: {
forceFit: true
},
store: new Ext.data.SimpleStore({
fields: ['tid', 'version', 'language', 'title', 'icon', 'ts'],
sortInfo: {field: 'ts', direction: 'DESC'}
}),
sm: new Ext.grid.RowSelectionModel({
singleSelect: true
}),
columns: [
{
dataIndex: 'title',
header: this.strings.history,
renderer: function (v, md, r) {
var icon = '<img src="' + r.data.icon + '" width="18" height="18" style="vertical-align: middle;" />';
var date = Math.floor(new Date().getTime() / 1000 - r.data.ts / 1000);
if (date) {
date = 'Geöffnet vor ' + Phlexible.Format.age(date);
} else {
date = 'Gerade geöffnet';
}
var title = r.data.title;
var meta = r.data.tid + ', v' + r.data.version + ', ' + r.data.language;
return icon + ' ' + title + ' [' + meta + ']<br />' +
'<span style="color: gray; font-size: 10px;">' + date + '</span>';
}
}
],
listeners: {
rowdblclick: function (c, itemIndex) {
var r = c.getStore().getAt(itemIndex);
if (!r) return;
this.element.reload({id: r.data.tid, version: r.data.version, language: r.data.language, lock: 1});
},
scope: this
}
}
]
}
]
},{
xtype: 'panel',
region: 'center',
header: false,
layout: 'card',
activeItem: 0,
border: false,
hideMode: 'offsets',
items: [{
xtype: 'elements-elementpanel',
element: this.element,
listeners: {
listLoadTeaser: function (teaser_id) {
this.getContentPanel().getLayout().setActiveItem(this.elementPanelIndex);
this.element.loadTeaser(teaser_id, null, null, 1);
},
listLoadNode: function (tid) {
var node = this.getElementsTree().getNodeById(tid);
if (node) {
// uber-node settings gedöns
node.select();
node.expand();
node.ensureVisible();
this.element.setTreeNode(node);
} else {
this.element.setTreeNode(null);
}
this.element.load(tid, null, null, 1);
},
listReloadNode: function (tid) {
var node = this.getElementsTree().getNodeById(tid);
if (node) {
// uber-node settings gedöns
node.select();
node.expand();
node.ensureVisible();
this.element.setTreeNode(node);
node.reload();
} else {
this.element.setTreeNode(null);
}
},
scope: this
}
},{
xtype: 'elements-tab-list',
element: dummyElement,
mode: 'teaser',
listeners: {
listLoadTeaser: function (teaser_id) {
this.getContentPanel().getLayout().setActiveItem(this.elementPanelIndex);
this.element.loadTeaser(teaser_id, null, null, 1);
},
sortArea: function () {
this.getLayoutTree().getRootNode().reload();
},
scope: this
}
}]
}];
this.tbar = new Phlexible.elements.TopToolbar({
element: this.element
});
this.element.on({
historychange: function () {
var store = this.getComponent(0).getComponent(0).getComponent(3).getStore();
store.loadData(this.element.history.getRange());
},
scope: this
});
Phlexible.elements.MainPanel.superclass.initComponent.call(this);
this.on({
render: function () {
if (this.params.id) {
this.element.reload({
id: this.params.id,
lock: 1
});
}
},
close: function () {
// remove lock if element is currently locked by me
if (this.element.getLockStatus() == 'edit') {
this.element.unlock(Ext.emptyFn);
}
},
scope: this
});
// this.on('render', function() {
// this.mask = new Ext.LoadMask(this.el,{
// msg: 'Loading Element',
// removeMask: false
// });
// }, this);
// this.elementsTree.on('render', function(tree) {
// tree.load();
// });
// this.elementsTree.root.on('load', function(node) {
// node.item(0).select();
// this.load(node.item(0).id)
// }, this);
},
getLeftTabPanelWrap: function() {
return this.getComponent(0);
},
getLeftTabPanel: function() {
return this.getLeftTabPanelWrap().getComponent(0);
},
getTreeTab: function() {
return this.getLeftTabPanel().getComponent(0);
},
getMediaTab: function() {
return this.getLeftTabPanel().getComponent(1);
},
getElementSearchTab: function() {
return this.getLeftTabPanel().getComponent(2);
},
getElementHistoryTab: function() {
return this.getLeftTabPanel().getComponent(3);
},
getElementsTree: function() {
return this.getTreeTab().getComponent(0);
},
getLayoutTree: function() {
return this.getTreeTab().getComponent(1);
},
getContentPanel: function() {
return this.getComponent(1);
},
getElementPanel: function() {
return this.getContentPanel().getComponent(0);
},
getLayoutListPanel: function() {
return this.getContentPanel().getComponent(1);
},
onLoadElement: function (element) {
//var properties = element.properties;
// update element panel title
switch (element.properties.et_type) {
case 'part':
//this.setTitle(this.baseTitle + ' :: ' + this.strings['part_element'] + ' "' + element.title + '" (Teaser ID: ' + element.properties.teaser_id + ' - ' + this.strings.language + ': ' + element.language + ' - ' + this.strings.version + ': ' + element.version + ')');
break;
case 'full':
default:
//this.setTitle(this.baseTitle + ' :: ' + this.strings[element.properties.et_type + '_element'] + ' "' + element.title + '" (' + this.strings.tid + ': ' + element.tid + ' - ' + this.strings.language + ': ' + element.language + ' - ' + this.strings.version + ': ' + element.version + ')');
break;
}
/*
this.setIconClass(null);
if (this.header) {
var el = Ext.get(this.header.query('img')[0]);
el.dom.src = element.icon;
el.addClass('element-icon');
}
*/
//this.setIcon(element.icon);
//this.mask.hide();
},
onNodeSelect: function (node, doLock) {
if (!node) {
return;
}
this.getContentPanel().getLayout().setActiveItem(this.elementPanelIndex);
this.element.setTreeNode(node);
node.expand();
if (!this.skipLoad) {
this.element.load(node.id, null, null, doLock);
} else {
this.skipLoad = false;
}
}
});
Ext.reg('elements-main', Phlexible.elements.MainPanel);
|
$(document).ready(function(){
$('#frontpage').fadeIn('slow');
$('#frontpage-info').click(function(){
$('#frontpage-info-box').fadeIn('slow');
return false;
});
$('#frontpage-info-box').click(function(){
$(this).fadeOut('slow');
return false;
});
$('#frontpage-gotoapp').click(function(){
$('#frontpage').animate({
opacity: 0
},1000, function(){
$(this).css({'display':'none', 'opacity':1});
$('#pallomeri').fadeIn('slow');
$('#pallomeri-instructions-box').fadeIn('slow');
changewidth();
// ladataan kategoriat ja pallot
});
return false;
});
$('#frontpage-gotomap').click(function(){
window.open(
'http://www.fellmannia.fi/flash/fellmanniamap.swf',
'_blank'
);
return false;
});
$('#frontpage-link-lahti').click(function(){
window.open(
'http://www.lahti.fi',
'_blank'
);
return false;
});
$('#frontpage-link-matkahuolto').click(function(){
window.open(
'http://www.matkahuolto.fi',
'_blank'
);
return false;
});
$('#frontpage-link-vr').click(function(){
window.open(
'http://www.vr.fi',
'_blank'
);
return false;
});
}); |
import { mapGetters } from 'vuex'
import { I18N } from "../../utils/i18n"
const i18n = (messages, namespace='i18n.namespace' + Date.now()) => ({
computed: mapGetters([ 'lang' ]),
created() {
I18N.load(messages, this.lang, namespace)
},
methods: {
i18n(key, ns=namespace, vars={}) {
return I18N.translate(key, vars, ns, this.lang)
}
},
watch: {
lang() {
I18N.load(messages, this.lang, namespace)
}
}
})
const updateInput = {
methods: {
update(component, property, value) {
this.$store.dispatch('updateSettings', {
component: component,
property: property,
value: value
})
}
}
}
export { i18n, updateInput }
|
const middlewares = {
'path': './application/middlewares',
'enabled': {
'environment': true,
'log': true,
'response-time': true,
'revision': true,
'etags': true,
'jsonerror': true,
'basicauth': {
'enabled': false,
'credentials': {
'name': process.env.BOILERPLATE_SERVER_BASIC_AUTH_LOGIN || process.env.NODE_BASIC_AUTH_LOGIN || 'boilerplate-server',
'pass': process.env.BOILERPLATE_SERVER_BASIC_AUTH_PASS || process.env.NODE_BASIC_AUTH_PASS || 'boilerplate-server'
},
'exclude': '/health'
}
}
};
export default middlewares;
|
const SanjiWindowComponent = {
transclude: true,
bindings: {
windowId: '@',
windowName: '@',
showLoadingBtn: '@'
},
templateUrl: 'sanji-window.tpl.html',
controller: 'SanjiWindowController',
controllerAs: 'vm'
};
export default SanjiWindowComponent;
|
smalltalk.addPackage('Compiler-AST');
smalltalk.addClass('Node', smalltalk.Object, ['parent', 'position', 'nodes', 'shouldBeInlined', 'shouldBeAliased'], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.Node)})},
messageSends: ["visitNode:"]}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "addNode:",
fn: function (aNode){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._nodes())._add_(aNode);
_st(aNode)._parent_(self);
return self}, function($ctx1) {$ctx1.fill(self,"addNode:",{aNode:aNode},smalltalk.Node)})},
messageSends: ["add:", "nodes", "parent:"]}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "extent",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$3,$1;
$2=self._nextNode();
if(($receiver = $2) == nil || $receiver == undefined){
$3=self._parent();
if(($receiver = $3) == nil || $receiver == undefined){
$1=$3;
} else {
var node;
node=$receiver;
$1=_st(node)._extent();
};
} else {
var node;
node=$receiver;
$1=_st(node)._position();
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"extent",{},smalltalk.Node)})},
messageSends: ["ifNil:ifNotNil:", "ifNotNil:", "extent", "parent", "position", "nextNode"]}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "isAssignmentNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return false;
}, function($ctx1) {$ctx1.fill(self,"isAssignmentNode",{},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "isBlockNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return false;
}, function($ctx1) {$ctx1.fill(self,"isBlockNode",{},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "isBlockSequenceNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return false;
}, function($ctx1) {$ctx1.fill(self,"isBlockSequenceNode",{},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "isImmutable",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return false;
}, function($ctx1) {$ctx1.fill(self,"isImmutable",{},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "isJSStatementNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return false;
}, function($ctx1) {$ctx1.fill(self,"isJSStatementNode",{},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "isNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return true;
}, function($ctx1) {$ctx1.fill(self,"isNode",{},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "isReturnNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return false;
}, function($ctx1) {$ctx1.fill(self,"isReturnNode",{},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "isSendNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return false;
}, function($ctx1) {$ctx1.fill(self,"isSendNode",{},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "isValueNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return false;
}, function($ctx1) {$ctx1.fill(self,"isValueNode",{},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "nextNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self._parent();
if(($receiver = $2) == nil || $receiver == undefined){
$1=$2;
} else {
var node;
node=$receiver;
$1=_st(node)._nextNode_(self);
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"nextNode",{},smalltalk.Node)})},
messageSends: ["ifNotNil:", "nextNode:", "parent"]}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "nextNode:",
fn: function (aNode){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._nodes())._at_ifAbsent_(_st(_st(self._nodes())._indexOf_(aNode)).__plus((1)),(function(){
return smalltalk.withContext(function($ctx2) {
return nil;
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
return $1;
}, function($ctx1) {$ctx1.fill(self,"nextNode:",{aNode:aNode},smalltalk.Node)})},
messageSends: ["at:ifAbsent:", "+", "indexOf:", "nodes"]}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "nodes",
fn: function (){
var self=this;
function $Array(){return smalltalk.Array||(typeof Array=="undefined"?nil:Array)}
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@nodes"];
if(($receiver = $2) == nil || $receiver == undefined){
self["@nodes"]=_st($Array())._new();
$1=self["@nodes"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"nodes",{},smalltalk.Node)})},
messageSends: ["ifNil:", "new"]}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "nodes:",
fn: function (aCollection){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@nodes"]=aCollection;
_st(aCollection)._do_((function(each){
return smalltalk.withContext(function($ctx2) {
return _st(each)._parent_(self);
}, function($ctx2) {$ctx2.fillBlock({each:each},$ctx1)})}));
return self}, function($ctx1) {$ctx1.fill(self,"nodes:",{aCollection:aCollection},smalltalk.Node)})},
messageSends: ["do:", "parent:"]}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "parent",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@parent"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"parent",{},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "parent:",
fn: function (aNode){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@parent"]=aNode;
return self}, function($ctx1) {$ctx1.fill(self,"parent:",{aNode:aNode},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "position",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$3,$1;
$2=self["@position"];
if(($receiver = $2) == nil || $receiver == undefined){
$3=self._parent();
if(($receiver = $3) == nil || $receiver == undefined){
$1=$3;
} else {
var node;
node=$receiver;
$1=_st(node)._position();
};
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"position",{},smalltalk.Node)})},
messageSends: ["ifNil:", "ifNotNil:", "position", "parent"]}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "position:",
fn: function (aPosition){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@position"]=aPosition;
return self}, function($ctx1) {$ctx1.fill(self,"position:",{aPosition:aPosition},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "shouldBeAliased",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@shouldBeAliased"];
if(($receiver = $2) == nil || $receiver == undefined){
$1=false;
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"shouldBeAliased",{},smalltalk.Node)})},
messageSends: ["ifNil:"]}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "shouldBeAliased:",
fn: function (aBoolean){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@shouldBeAliased"]=aBoolean;
return self}, function($ctx1) {$ctx1.fill(self,"shouldBeAliased:",{aBoolean:aBoolean},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "shouldBeInlined",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@shouldBeInlined"];
if(($receiver = $2) == nil || $receiver == undefined){
$1=false;
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"shouldBeInlined",{},smalltalk.Node)})},
messageSends: ["ifNil:"]}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "shouldBeInlined:",
fn: function (aBoolean){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@shouldBeInlined"]=aBoolean;
return self}, function($ctx1) {$ctx1.fill(self,"shouldBeInlined:",{aBoolean:aBoolean},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "stopOnStepping",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return false;
}, function($ctx1) {$ctx1.fill(self,"stopOnStepping",{},smalltalk.Node)})},
messageSends: []}),
smalltalk.Node);
smalltalk.addMethod(
smalltalk.method({
selector: "subtreeNeedsAliasing",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(_st(self._shouldBeAliased())._or_((function(){
return smalltalk.withContext(function($ctx2) {
return self._shouldBeInlined();
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})})))._or_((function(){
return smalltalk.withContext(function($ctx2) {
return _st(_st(self._nodes())._detect_ifNone_((function(each){
return smalltalk.withContext(function($ctx3) {
return _st(each)._subtreeNeedsAliasing();
}, function($ctx3) {$ctx3.fillBlock({each:each},$ctx2)})}),(function(){
return smalltalk.withContext(function($ctx3) {
return false;
}, function($ctx3) {$ctx3.fillBlock({},$ctx2)})}))).__tild_eq(false);
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
return $1;
}, function($ctx1) {$ctx1.fill(self,"subtreeNeedsAliasing",{},smalltalk.Node)})},
messageSends: ["or:", "~=", "detect:ifNone:", "subtreeNeedsAliasing", "nodes", "shouldBeInlined", "shouldBeAliased"]}),
smalltalk.Node);
smalltalk.addClass('AssignmentNode', smalltalk.Node, ['left', 'right'], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitAssignmentNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.AssignmentNode)})},
messageSends: ["visitAssignmentNode:"]}),
smalltalk.AssignmentNode);
smalltalk.addMethod(
smalltalk.method({
selector: "isAssignmentNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return true;
}, function($ctx1) {$ctx1.fill(self,"isAssignmentNode",{},smalltalk.AssignmentNode)})},
messageSends: []}),
smalltalk.AssignmentNode);
smalltalk.addMethod(
smalltalk.method({
selector: "left",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@left"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"left",{},smalltalk.AssignmentNode)})},
messageSends: []}),
smalltalk.AssignmentNode);
smalltalk.addMethod(
smalltalk.method({
selector: "left:",
fn: function (aNode){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@left"]=aNode;
return self}, function($ctx1) {$ctx1.fill(self,"left:",{aNode:aNode},smalltalk.AssignmentNode)})},
messageSends: []}),
smalltalk.AssignmentNode);
smalltalk.addMethod(
smalltalk.method({
selector: "nodes",
fn: function (){
var self=this;
function $Array(){return smalltalk.Array||(typeof Array=="undefined"?nil:Array)}
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st($Array())._with_with_(self._left(),self._right());
return $1;
}, function($ctx1) {$ctx1.fill(self,"nodes",{},smalltalk.AssignmentNode)})},
messageSends: ["with:with:", "left", "right"]}),
smalltalk.AssignmentNode);
smalltalk.addMethod(
smalltalk.method({
selector: "right",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@right"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"right",{},smalltalk.AssignmentNode)})},
messageSends: []}),
smalltalk.AssignmentNode);
smalltalk.addMethod(
smalltalk.method({
selector: "right:",
fn: function (aNode){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@right"]=aNode;
return self}, function($ctx1) {$ctx1.fill(self,"right:",{aNode:aNode},smalltalk.AssignmentNode)})},
messageSends: []}),
smalltalk.AssignmentNode);
smalltalk.addClass('BlockNode', smalltalk.Node, ['parameters', 'scope'], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitBlockNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.BlockNode)})},
messageSends: ["visitBlockNode:"]}),
smalltalk.BlockNode);
smalltalk.addMethod(
smalltalk.method({
selector: "isBlockNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return true;
}, function($ctx1) {$ctx1.fill(self,"isBlockNode",{},smalltalk.BlockNode)})},
messageSends: []}),
smalltalk.BlockNode);
smalltalk.addMethod(
smalltalk.method({
selector: "parameters",
fn: function (){
var self=this;
function $Array(){return smalltalk.Array||(typeof Array=="undefined"?nil:Array)}
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@parameters"];
if(($receiver = $2) == nil || $receiver == undefined){
self["@parameters"]=_st($Array())._new();
$1=self["@parameters"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"parameters",{},smalltalk.BlockNode)})},
messageSends: ["ifNil:", "new"]}),
smalltalk.BlockNode);
smalltalk.addMethod(
smalltalk.method({
selector: "parameters:",
fn: function (aCollection){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@parameters"]=aCollection;
return self}, function($ctx1) {$ctx1.fill(self,"parameters:",{aCollection:aCollection},smalltalk.BlockNode)})},
messageSends: []}),
smalltalk.BlockNode);
smalltalk.addMethod(
smalltalk.method({
selector: "scope",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@scope"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"scope",{},smalltalk.BlockNode)})},
messageSends: []}),
smalltalk.BlockNode);
smalltalk.addMethod(
smalltalk.method({
selector: "scope:",
fn: function (aLexicalScope){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@scope"]=aLexicalScope;
return self}, function($ctx1) {$ctx1.fill(self,"scope:",{aLexicalScope:aLexicalScope},smalltalk.BlockNode)})},
messageSends: []}),
smalltalk.BlockNode);
smalltalk.addMethod(
smalltalk.method({
selector: "subtreeNeedsAliasing",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._shouldBeAliased())._or_((function(){
return smalltalk.withContext(function($ctx2) {
return self._shouldBeInlined();
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
return $1;
}, function($ctx1) {$ctx1.fill(self,"subtreeNeedsAliasing",{},smalltalk.BlockNode)})},
messageSends: ["or:", "shouldBeInlined", "shouldBeAliased"]}),
smalltalk.BlockNode);
smalltalk.addClass('CascadeNode', smalltalk.Node, ['receiver'], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitCascadeNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.CascadeNode)})},
messageSends: ["visitCascadeNode:"]}),
smalltalk.CascadeNode);
smalltalk.addMethod(
smalltalk.method({
selector: "receiver",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@receiver"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"receiver",{},smalltalk.CascadeNode)})},
messageSends: []}),
smalltalk.CascadeNode);
smalltalk.addMethod(
smalltalk.method({
selector: "receiver:",
fn: function (aNode){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@receiver"]=aNode;
return self}, function($ctx1) {$ctx1.fill(self,"receiver:",{aNode:aNode},smalltalk.CascadeNode)})},
messageSends: []}),
smalltalk.CascadeNode);
smalltalk.addClass('DynamicArrayNode', smalltalk.Node, [], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitDynamicArrayNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.DynamicArrayNode)})},
messageSends: ["visitDynamicArrayNode:"]}),
smalltalk.DynamicArrayNode);
smalltalk.addClass('DynamicDictionaryNode', smalltalk.Node, [], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitDynamicDictionaryNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.DynamicDictionaryNode)})},
messageSends: ["visitDynamicDictionaryNode:"]}),
smalltalk.DynamicDictionaryNode);
smalltalk.addClass('JSStatementNode', smalltalk.Node, ['source'], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitJSStatementNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.JSStatementNode)})},
messageSends: ["visitJSStatementNode:"]}),
smalltalk.JSStatementNode);
smalltalk.addMethod(
smalltalk.method({
selector: "isJSStatementNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return true;
}, function($ctx1) {$ctx1.fill(self,"isJSStatementNode",{},smalltalk.JSStatementNode)})},
messageSends: []}),
smalltalk.JSStatementNode);
smalltalk.addMethod(
smalltalk.method({
selector: "source",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@source"];
if(($receiver = $2) == nil || $receiver == undefined){
$1="";
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"source",{},smalltalk.JSStatementNode)})},
messageSends: ["ifNil:"]}),
smalltalk.JSStatementNode);
smalltalk.addMethod(
smalltalk.method({
selector: "source:",
fn: function (aString){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@source"]=aString;
return self}, function($ctx1) {$ctx1.fill(self,"source:",{aString:aString},smalltalk.JSStatementNode)})},
messageSends: []}),
smalltalk.JSStatementNode);
smalltalk.addClass('MethodNode', smalltalk.Node, ['selector', 'arguments', 'source', 'scope', 'classReferences', 'messageSends', 'superSends'], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitMethodNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.MethodNode)})},
messageSends: ["visitMethodNode:"]}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "arguments",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@arguments"];
if(($receiver = $2) == nil || $receiver == undefined){
$1=[];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"arguments",{},smalltalk.MethodNode)})},
messageSends: ["ifNil:"]}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "arguments:",
fn: function (aCollection){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@arguments"]=aCollection;
return self}, function($ctx1) {$ctx1.fill(self,"arguments:",{aCollection:aCollection},smalltalk.MethodNode)})},
messageSends: []}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "classReferences",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@classReferences"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"classReferences",{},smalltalk.MethodNode)})},
messageSends: []}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "classReferences:",
fn: function (aCollection){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@classReferences"]=aCollection;
return self}, function($ctx1) {$ctx1.fill(self,"classReferences:",{aCollection:aCollection},smalltalk.MethodNode)})},
messageSends: []}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "extent",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(_st(_st(self._source())._lines())._size()).__at(_st(_st(_st(_st(self._source())._lines())._last())._size()).__plus((1)));
return $1;
}, function($ctx1) {$ctx1.fill(self,"extent",{},smalltalk.MethodNode)})},
messageSends: ["@", "+", "size", "last", "lines", "source"]}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "messageSends",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@messageSends"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"messageSends",{},smalltalk.MethodNode)})},
messageSends: []}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "messageSends:",
fn: function (aCollection){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@messageSends"]=aCollection;
return self}, function($ctx1) {$ctx1.fill(self,"messageSends:",{aCollection:aCollection},smalltalk.MethodNode)})},
messageSends: []}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "scope",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@scope"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"scope",{},smalltalk.MethodNode)})},
messageSends: []}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "scope:",
fn: function (aMethodScope){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@scope"]=aMethodScope;
return self}, function($ctx1) {$ctx1.fill(self,"scope:",{aMethodScope:aMethodScope},smalltalk.MethodNode)})},
messageSends: []}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "selector",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@selector"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"selector",{},smalltalk.MethodNode)})},
messageSends: []}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "selector:",
fn: function (aString){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@selector"]=aString;
return self}, function($ctx1) {$ctx1.fill(self,"selector:",{aString:aString},smalltalk.MethodNode)})},
messageSends: []}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "source",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@source"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"source",{},smalltalk.MethodNode)})},
messageSends: []}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "source:",
fn: function (aString){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@source"]=aString;
return self}, function($ctx1) {$ctx1.fill(self,"source:",{aString:aString},smalltalk.MethodNode)})},
messageSends: []}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "superSends",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@superSends"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"superSends",{},smalltalk.MethodNode)})},
messageSends: []}),
smalltalk.MethodNode);
smalltalk.addMethod(
smalltalk.method({
selector: "superSends:",
fn: function (aCollection){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@superSends"]=aCollection;
return self}, function($ctx1) {$ctx1.fill(self,"superSends:",{aCollection:aCollection},smalltalk.MethodNode)})},
messageSends: []}),
smalltalk.MethodNode);
smalltalk.addClass('ReturnNode', smalltalk.Node, ['scope'], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitReturnNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.ReturnNode)})},
messageSends: ["visitReturnNode:"]}),
smalltalk.ReturnNode);
smalltalk.addMethod(
smalltalk.method({
selector: "isReturnNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return true;
}, function($ctx1) {$ctx1.fill(self,"isReturnNode",{},smalltalk.ReturnNode)})},
messageSends: []}),
smalltalk.ReturnNode);
smalltalk.addMethod(
smalltalk.method({
selector: "nonLocalReturn",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(_st(self._scope())._isMethodScope())._not();
return $1;
}, function($ctx1) {$ctx1.fill(self,"nonLocalReturn",{},smalltalk.ReturnNode)})},
messageSends: ["not", "isMethodScope", "scope"]}),
smalltalk.ReturnNode);
smalltalk.addMethod(
smalltalk.method({
selector: "scope",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@scope"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"scope",{},smalltalk.ReturnNode)})},
messageSends: []}),
smalltalk.ReturnNode);
smalltalk.addMethod(
smalltalk.method({
selector: "scope:",
fn: function (aLexicalScope){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@scope"]=aLexicalScope;
return self}, function($ctx1) {$ctx1.fill(self,"scope:",{aLexicalScope:aLexicalScope},smalltalk.ReturnNode)})},
messageSends: []}),
smalltalk.ReturnNode);
smalltalk.addClass('SendNode', smalltalk.Node, ['selector', 'arguments', 'receiver', 'superSend', 'index'], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitSendNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.SendNode)})},
messageSends: ["visitSendNode:"]}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "arguments",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@arguments"];
if(($receiver = $2) == nil || $receiver == undefined){
self["@arguments"]=[];
$1=self["@arguments"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"arguments",{},smalltalk.SendNode)})},
messageSends: ["ifNil:"]}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "arguments:",
fn: function (aCollection){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@arguments"]=aCollection;
_st(aCollection)._do_((function(each){
return smalltalk.withContext(function($ctx2) {
return _st(each)._parent_(self);
}, function($ctx2) {$ctx2.fillBlock({each:each},$ctx1)})}));
return self}, function($ctx1) {$ctx1.fill(self,"arguments:",{aCollection:aCollection},smalltalk.SendNode)})},
messageSends: ["do:", "parent:"]}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "cascadeNodeWithMessages:",
fn: function (aCollection){
var self=this;
var first;
function $SendNode(){return smalltalk.SendNode||(typeof SendNode=="undefined"?nil:SendNode)}
function $CascadeNode(){return smalltalk.CascadeNode||(typeof CascadeNode=="undefined"?nil:CascadeNode)}
function $Array(){return smalltalk.Array||(typeof Array=="undefined"?nil:Array)}
return smalltalk.withContext(function($ctx1) {
var $1,$2,$4,$5,$3;
$1=_st($SendNode())._new();
_st($1)._selector_(self._selector());
_st($1)._arguments_(self._arguments());
$2=_st($1)._yourself();
first=$2;
$4=_st($CascadeNode())._new();
_st($4)._receiver_(self._receiver());
_st($4)._nodes_(_st(_st($Array())._with_(first)).__comma(aCollection));
$5=_st($4)._yourself();
$3=$5;
return $3;
}, function($ctx1) {$ctx1.fill(self,"cascadeNodeWithMessages:",{aCollection:aCollection,first:first},smalltalk.SendNode)})},
messageSends: ["selector:", "selector", "new", "arguments:", "arguments", "yourself", "receiver:", "receiver", "nodes:", ",", "with:"]}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "index",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@index"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"index",{},smalltalk.SendNode)})},
messageSends: []}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "index:",
fn: function (anInteger){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@index"]=anInteger;
return self}, function($ctx1) {$ctx1.fill(self,"index:",{anInteger:anInteger},smalltalk.SendNode)})},
messageSends: []}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "isSendNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return true;
}, function($ctx1) {$ctx1.fill(self,"isSendNode",{},smalltalk.SendNode)})},
messageSends: []}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "nodes",
fn: function (){
var self=this;
function $Array(){return smalltalk.Array||(typeof Array=="undefined"?nil:Array)}
return smalltalk.withContext(function($ctx1) {
var $2,$3,$1;
$2=_st($Array())._withAll_(self._arguments());
_st($2)._add_(self._receiver());
$3=_st($2)._yourself();
$1=$3;
return $1;
}, function($ctx1) {$ctx1.fill(self,"nodes",{},smalltalk.SendNode)})},
messageSends: ["add:", "receiver", "withAll:", "arguments", "yourself"]}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "receiver",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@receiver"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"receiver",{},smalltalk.SendNode)})},
messageSends: []}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "receiver:",
fn: function (aNode){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
self["@receiver"]=aNode;
$1=_st(aNode)._isNode();
if(smalltalk.assert($1)){
_st(aNode)._parent_(self);
};
return self}, function($ctx1) {$ctx1.fill(self,"receiver:",{aNode:aNode},smalltalk.SendNode)})},
messageSends: ["ifTrue:", "parent:", "isNode"]}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "selector",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@selector"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"selector",{},smalltalk.SendNode)})},
messageSends: []}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "selector:",
fn: function (aString){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@selector"]=aString;
return self}, function($ctx1) {$ctx1.fill(self,"selector:",{aString:aString},smalltalk.SendNode)})},
messageSends: []}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "stopOnStepping",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return true;
}, function($ctx1) {$ctx1.fill(self,"stopOnStepping",{},smalltalk.SendNode)})},
messageSends: []}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "superSend",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@superSend"];
if(($receiver = $2) == nil || $receiver == undefined){
$1=false;
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"superSend",{},smalltalk.SendNode)})},
messageSends: ["ifNil:"]}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "superSend:",
fn: function (aBoolean){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@superSend"]=aBoolean;
return self}, function($ctx1) {$ctx1.fill(self,"superSend:",{aBoolean:aBoolean},smalltalk.SendNode)})},
messageSends: []}),
smalltalk.SendNode);
smalltalk.addMethod(
smalltalk.method({
selector: "valueForReceiver:",
fn: function (anObject){
var self=this;
function $SendNode(){return smalltalk.SendNode||(typeof SendNode=="undefined"?nil:SendNode)}
return smalltalk.withContext(function($ctx1) {
var $2,$3,$5,$4,$6,$1;
$2=_st($SendNode())._new();
_st($2)._position_(self._position());
$3=$2;
$5=self._receiver();
if(($receiver = $5) == nil || $receiver == undefined){
$4=anObject;
} else {
$4=_st(self._receiver())._valueForReceiver_(anObject);
};
_st($3)._receiver_($4);
_st($2)._selector_(self._selector());
_st($2)._arguments_(self._arguments());
$6=_st($2)._yourself();
$1=$6;
return $1;
}, function($ctx1) {$ctx1.fill(self,"valueForReceiver:",{anObject:anObject},smalltalk.SendNode)})},
messageSends: ["position:", "position", "new", "receiver:", "ifNil:ifNotNil:", "valueForReceiver:", "receiver", "selector:", "selector", "arguments:", "arguments", "yourself"]}),
smalltalk.SendNode);
smalltalk.addClass('SequenceNode', smalltalk.Node, ['temps', 'scope'], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitSequenceNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.SequenceNode)})},
messageSends: ["visitSequenceNode:"]}),
smalltalk.SequenceNode);
smalltalk.addMethod(
smalltalk.method({
selector: "asBlockSequenceNode",
fn: function (){
var self=this;
function $BlockSequenceNode(){return smalltalk.BlockSequenceNode||(typeof BlockSequenceNode=="undefined"?nil:BlockSequenceNode)}
return smalltalk.withContext(function($ctx1) {
var $2,$3,$1;
$2=_st($BlockSequenceNode())._new();
_st($2)._position_(self._position());
_st($2)._nodes_(self._nodes());
_st($2)._temps_(self._temps());
$3=_st($2)._yourself();
$1=$3;
return $1;
}, function($ctx1) {$ctx1.fill(self,"asBlockSequenceNode",{},smalltalk.SequenceNode)})},
messageSends: ["position:", "position", "new", "nodes:", "nodes", "temps:", "temps", "yourself"]}),
smalltalk.SequenceNode);
smalltalk.addMethod(
smalltalk.method({
selector: "scope",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@scope"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"scope",{},smalltalk.SequenceNode)})},
messageSends: []}),
smalltalk.SequenceNode);
smalltalk.addMethod(
smalltalk.method({
selector: "scope:",
fn: function (aLexicalScope){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@scope"]=aLexicalScope;
return self}, function($ctx1) {$ctx1.fill(self,"scope:",{aLexicalScope:aLexicalScope},smalltalk.SequenceNode)})},
messageSends: []}),
smalltalk.SequenceNode);
smalltalk.addMethod(
smalltalk.method({
selector: "temps",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@temps"];
if(($receiver = $2) == nil || $receiver == undefined){
$1=[];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"temps",{},smalltalk.SequenceNode)})},
messageSends: ["ifNil:"]}),
smalltalk.SequenceNode);
smalltalk.addMethod(
smalltalk.method({
selector: "temps:",
fn: function (aCollection){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@temps"]=aCollection;
return self}, function($ctx1) {$ctx1.fill(self,"temps:",{aCollection:aCollection},smalltalk.SequenceNode)})},
messageSends: []}),
smalltalk.SequenceNode);
smalltalk.addClass('BlockSequenceNode', smalltalk.SequenceNode, [], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitBlockSequenceNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.BlockSequenceNode)})},
messageSends: ["visitBlockSequenceNode:"]}),
smalltalk.BlockSequenceNode);
smalltalk.addMethod(
smalltalk.method({
selector: "isBlockSequenceNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return true;
}, function($ctx1) {$ctx1.fill(self,"isBlockSequenceNode",{},smalltalk.BlockSequenceNode)})},
messageSends: []}),
smalltalk.BlockSequenceNode);
smalltalk.addClass('ValueNode', smalltalk.Node, ['value'], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitValueNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.ValueNode)})},
messageSends: ["visitValueNode:"]}),
smalltalk.ValueNode);
smalltalk.addMethod(
smalltalk.method({
selector: "isImmutable",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._value())._isImmutable();
return $1;
}, function($ctx1) {$ctx1.fill(self,"isImmutable",{},smalltalk.ValueNode)})},
messageSends: ["isImmutable", "value"]}),
smalltalk.ValueNode);
smalltalk.addMethod(
smalltalk.method({
selector: "isValueNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return true;
}, function($ctx1) {$ctx1.fill(self,"isValueNode",{},smalltalk.ValueNode)})},
messageSends: []}),
smalltalk.ValueNode);
smalltalk.addMethod(
smalltalk.method({
selector: "value",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@value"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"value",{},smalltalk.ValueNode)})},
messageSends: []}),
smalltalk.ValueNode);
smalltalk.addMethod(
smalltalk.method({
selector: "value:",
fn: function (anObject){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@value"]=anObject;
return self}, function($ctx1) {$ctx1.fill(self,"value:",{anObject:anObject},smalltalk.ValueNode)})},
messageSends: []}),
smalltalk.ValueNode);
smalltalk.addClass('VariableNode', smalltalk.ValueNode, ['assigned', 'binding'], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitVariableNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.VariableNode)})},
messageSends: ["visitVariableNode:"]}),
smalltalk.VariableNode);
smalltalk.addMethod(
smalltalk.method({
selector: "alias",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._binding())._alias();
return $1;
}, function($ctx1) {$ctx1.fill(self,"alias",{},smalltalk.VariableNode)})},
messageSends: ["alias", "binding"]}),
smalltalk.VariableNode);
smalltalk.addMethod(
smalltalk.method({
selector: "assigned",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@assigned"];
if(($receiver = $2) == nil || $receiver == undefined){
$1=false;
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"assigned",{},smalltalk.VariableNode)})},
messageSends: ["ifNil:"]}),
smalltalk.VariableNode);
smalltalk.addMethod(
smalltalk.method({
selector: "assigned:",
fn: function (aBoolean){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@assigned"]=aBoolean;
return self}, function($ctx1) {$ctx1.fill(self,"assigned:",{aBoolean:aBoolean},smalltalk.VariableNode)})},
messageSends: []}),
smalltalk.VariableNode);
smalltalk.addMethod(
smalltalk.method({
selector: "beAssigned",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._binding())._validateAssignment();
self["@assigned"]=true;
return self}, function($ctx1) {$ctx1.fill(self,"beAssigned",{},smalltalk.VariableNode)})},
messageSends: ["validateAssignment", "binding"]}),
smalltalk.VariableNode);
smalltalk.addMethod(
smalltalk.method({
selector: "binding",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@binding"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"binding",{},smalltalk.VariableNode)})},
messageSends: []}),
smalltalk.VariableNode);
smalltalk.addMethod(
smalltalk.method({
selector: "binding:",
fn: function (aScopeVar){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@binding"]=aScopeVar;
return self}, function($ctx1) {$ctx1.fill(self,"binding:",{aScopeVar:aScopeVar},smalltalk.VariableNode)})},
messageSends: []}),
smalltalk.VariableNode);
smalltalk.addMethod(
smalltalk.method({
selector: "isImmutable",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return false;
}, function($ctx1) {$ctx1.fill(self,"isImmutable",{},smalltalk.VariableNode)})},
messageSends: []}),
smalltalk.VariableNode);
smalltalk.addClass('ClassReferenceNode', smalltalk.VariableNode, [], 'Compiler-AST');
smalltalk.addMethod(
smalltalk.method({
selector: "accept:",
fn: function (aVisitor){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aVisitor)._visitClassReferenceNode_(self);
return $1;
}, function($ctx1) {$ctx1.fill(self,"accept:",{aVisitor:aVisitor},smalltalk.ClassReferenceNode)})},
messageSends: ["visitClassReferenceNode:"]}),
smalltalk.ClassReferenceNode);
smalltalk.addMethod(
smalltalk.method({
selector: "isNode",
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return false;
}, function($ctx1) {$ctx1.fill(self,"isNode",{},smalltalk.Object)})},
messageSends: []}),
smalltalk.Object);
smalltalk.addMethod(
smalltalk.method({
selector: "ast",
fn: function (){
var self=this;
function $Smalltalk(){return smalltalk.Smalltalk||(typeof Smalltalk=="undefined"?nil:Smalltalk)}
return smalltalk.withContext(function($ctx1) {
var $1;
_st(self._source())._ifEmpty_((function(){
return smalltalk.withContext(function($ctx2) {
return self._error_("Method source is empty");
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
$1=_st(_st($Smalltalk())._current())._parse_(self._source());
return $1;
}, function($ctx1) {$ctx1.fill(self,"ast",{},smalltalk.CompiledMethod)})},
messageSends: ["ifEmpty:", "error:", "source", "parse:", "current"]}),
smalltalk.CompiledMethod);
|
import chai, { expect } from 'chai';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import Promise from 'bluebird';
chai.use(sinonChai);
import Audits from '../src/audits';
describe('Audits', () => {
describe('#findAll', () => {
const audits = ['1', '2', '3'];
const get = sinon.stub().returns(Promise.resolve({ audits }));
it('should return all audits from request', () => {
return Audits({ get }, console).findAll()
.then(res => {
expect(res).to.equal(audits);
});
});
it('should call api with correct endpoint', () => {
return Audits({ get }, console).findAll()
.then(() => {
expect(get.calledWith('/audits/search')).to.be.true;
});
});
it('should pass since into querystring', () => {
const since = new Date().toISOString();
return Audits({ get }, console).findAll({ since })
.then(() => {
const qs = {
modified_after: since,
field: ['audit_id', 'modified_at'],
order: 'asc'
};
expect(get.calledWith('/audits/search', { qs: qs })).to.be.true;
});
});
it('should pass order into querystring', () => {
const order = 'desc';
return Audits({ get }, console).findAll({ order })
.then(() => {
const qs = {
modified_after: undefined,
field: ['audit_id', 'modified_at'],
order
};
expect(get.calledWith('/audits/search', { qs: qs })).to.be.true;
});
});
it('should default order to asc in querystring', () => {
return Audits({ get }, console).findAll()
.then(() => {
const qs = {
modified_after: undefined,
field: ['audit_id', 'modified_at'],
order: 'asc'
};
expect(get.calledWith('/audits/search', { qs: qs })).to.be.true;
});
});
it('should include additional parameters in the querystring', () => {
const template = 'TEST';
let params = {template: template};
return Audits({ get }, console).findAll({ params })
.then(() => {
const qs = {
modified_after: undefined,
field: ['audit_id', 'modified_at'],
order: 'asc',
template: template
};
expect(get.calledWith('/audits/search', { qs: qs })).to.be.true;
});
});
});
describe('#findById', () => {
const get = sinon.stub().returns(Promise.resolve());
it('send a request with the right id', () => {
return Audits({ get }, console).findById(1)
.then(() => {
expect(get.calledWith('/audits/1')).to.be.true;
});
});
});
});
|
export default (aeroflow, execute, expect) => describe('aeroflow().replay', () => {
it('Is instance method', () =>
execute(
context => aeroflow.empty.replay,
context => expect(context.result).to.be.a('function')));
describe('aeroflow().replay()', () => {
it('Returns instance of Aeroflow', () =>
execute(
context => aeroflow.empty.replay(),
context => expect(context.result).to.be.an('Aeroflow')));
});
});
|
exports.info = { FormatID: '1116',
FormatName: 'ASPRS Lidar Data Exchange Format',
FormatVersion: '1.1',
FormatAliases: '',
FormatFamilies: '',
FormatTypes: 'GIS, Image (Raster)',
FormatDisclosure: 'Full',
FormatDescription: 'The Lidar Data Exchange Format is a binary file format for the interchange of LIDAR (Light Detection and Ranging) optical remote sensing data. Specifications available at http://www.asprs.org/Committee-General/LASer-LAS-File-Format-Exchange-Activities.html',
BinaryFileFormat: 'Binary',
ByteOrders: 'Little-endian (Intel)',
ReleaseDate: '07 Mar 2005',
WithdrawnDate: '',
ProvenanceSourceID: '1',
ProvenanceName: 'Digital Preservation Department / The National Archives',
ProvenanceSourceDate: '03 Nov 2011',
ProvenanceDescription: 'Format information supplied by the Geospatial Multistate Access and Preservation Partnership (GeoMAPP), a grant funded collaboration involving North Carolina, Kentucky, Utah, and Montana state archives, and sponsored by the National Digital Information Infrastructure Preservation Program (NDIIPP) of the Library of Congress.',
LastUpdatedDate: '03 Nov 2011',
FormatNote: '',
FormatRisk: '',
TechnicalEnvironment: '',
FileFormatIdentifier: { Identifier: 'fmt/369', IdentifierType: 'PUID' },
Developers:
{ DeveloperID: '173',
DeveloperName: 'American Soc. For Photogrammetry & Remote Sensing',
OrganisationName: 'American Soc. for Photogrammetry & Remote Sensing',
DeveloperCompoundName: 'American Soc. For Photogrammetry & Remote Sensing / American Soc. for Photogrammetry & Remote Sensing' },
ExternalSignature:
[ { ExternalSignatureID: '1149',
Signature: 'las',
SignatureType: 'File extension' },
{ ExternalSignatureID: '1150',
Signature: 'laz',
SignatureType: 'File extension' } ],
InternalSignature:
{ SignatureID: '540',
SignatureName: 'ASPRS Lidar Data Exchange Format 1.1',
SignatureNote: 'ASCII header: LASF, followed after 20 bytes by version number 1.1',
ByteSequence:
{ ByteSequenceID: '670',
PositionType: 'Absolute from BOF',
Offset: '0',
MaxOffset: '',
IndirectOffsetLocation: '',
IndirectOffsetLength: '',
Endianness: '',
ByteSequenceValue: '4C415346{20}0101{78}[00:99]' } },
RelatedFormat:
[ { RelationshipType: 'Is previous version of',
RelatedFormatID: '1117',
RelatedFormatName: 'ASPRS Lidar Data Exchange Format',
RelatedFormatVersion: '1.2' },
{ RelationshipType: 'Is subsequent version of',
RelatedFormatID: '1115',
RelatedFormatName: 'ASPRS Lidar Data Exchange Format',
RelatedFormatVersion: '1.0' } ] } |
const path = require('path');
const colors = require('colors');
const fs = require('fs-extra');
const klawSync = require('klaw-sync');
const readline = require('readline');
const { once } = require('events');
const insertLine = require('insert-line');
const BaseCommand = require('./base');
module.exports = class Command extends BaseCommand {
constructor(cli) {
super(cli);
}
async execute() {
const parentProjectFolder = path.join(this.cli.currentLocation, '../');
if (!this.cli.program.force) {
if (fs.existsSync(path.join(parentProjectFolder, '.no-snapdev-project'))) {
console.log(colors.yellow('Project folder conatins .no-snapdev-project file'));
process.exit(1);
}
}
const srcFolder = this.cli.distFolder;
const distFolder = parentProjectFolder;
if (!this.cli.program.silent) {
console.log('Destination:', distFolder);
}
const filterCopyFiles = async (src, dist) => {
if (src !== this.cli.distFolder) {
const fileFound = await fs.pathExists(dist);
if (!fileFound || this.cli.program.force) {
console.log(colors.green('Copied:'), src.replace(path.join(this.cli.distFolder, '/'), ''));
}
} else {
// console.log(
// colors.yellow(src, '*********', this.cli.distFolder)
// );
}
return true;
};
// copy the files but don't override
await fs.copy(srcFolder, distFolder, {
overwrite: this.cli.program.force,
filter: filterCopyFiles,
});
/**
* ========================
* Build a copy list
* ========================
*/
// get a list of all files
let paths = klawSync(srcFolder, {
nodir: true,
});
const generatedFiles = paths.map((p) => p.path);
const copyList = await this.getCopyPlaceholderList(generatedFiles);
// console.log(copyList);
/**
* ========================
* Build a paste list
* ========================
*/
const filterDistFn = (item) => {
// ignore hidden directories
const basename = path.basename(item.path);
const notHidden = basename === '.' || basename[0] !== '.';
if (notHidden) {
const relativeFile = item.path.replace(distFolder, '');
if (
!(
relativeFile.indexOf('snapdev') > -1 ||
relativeFile.indexOf('snapdev/') > -1 ||
relativeFile.indexOf('node_modules') > -1 ||
relativeFile.indexOf('node_modules/') > -1
)
) {
// console.log(item.path);
return true;
}
}
return false;
};
paths = klawSync(distFolder, {
nodir: true,
filter: filterDistFn,
});
const projectFiles = paths.map((p) => p.path);
let pasteList = await this.getPastePlaceholderList(projectFiles, distFolder);
// console.log(pasteList);
/**
* ========================
* Inject code where a matching paste command is found
* ========================
*/
// console.log('***********', pasteList);
const pasted = [];
for (let index = 0; index < pasteList.length; index++) {
const pasteItem = pasteList[index];
const hasPasted =
pasted.filter((i) => i.dist === pasteItem.dist && i.index === pasteItem.index && i.marker === pasteItem.marker)
.length > 0;
if (!hasPasted) {
for (let index2 = 0; index2 < copyList.length; index2++) {
const copyItem = copyList[index2];
if (copyItem.dist === pasteItem.dist && copyItem.marker === pasteItem.marker) {
// inject the copy code into the pastItem dist file
const distFile = path.join(distFolder, pasteItem.dist);
await this.injectCodeIntoFile(distFile, pasteItem.lineNo, copyItem.code);
console.log(colors.green('Updated:'), pasteItem.dist);
pasted.push(pasteItem);
// reset paste line numbers
pasteList = await this.getPastePlaceholderList(projectFiles, distFolder);
index = 0; // reset loop 1
break; // exit loop 2
}
}
}
}
if (!this.cli.program.silent) {
console.log('');
console.log('Deploy Done.');
}
return true;
}
injectCodeIntoFile(file, insertLineNo, codeList) {
return new Promise((resolve) => {
insertLine(file)
.content(codeList.join('\n'))
.at(insertLineNo)
.then(function (err) {
if (err) {
console.log(colors.yellow(`snapdev::paste failed`), err);
process.exit(1);
}
resolve();
});
});
}
removeComments(line) {
return line.replace('<!-- ', '').replace(' -->', '').replace('# // ', '');
}
// snapdev::copy-start::{"marker": "route", "dist": "src/app/app.routing.ts"}
// snapdev:copy-end
async getCopyPlaceholderList(files) {
let output = [];
/**
* structure
* {
* marker: "", dist: "", code: ""
* }
*/
async function processLine(file, removeComments) {
const fileStream = fs.createReadStream(file);
const results = [];
let marker = '';
let dist = '';
let code = [];
let copyLine = false;
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
rl.on('line', (line) => {
// Process the line.
if (line.indexOf('// snapdev::copy-end') > -1) {
// end copy
copyLine = false;
results.push({
marker,
dist,
code,
});
marker = '';
dist = '';
code = [];
}
if (copyLine) {
code.push(line);
}
if (line.indexOf('// snapdev::copy-start') > -1) {
// start copy
copyLine = true;
// snapdev::command::parameters
const commandSplit = removeComments(line).split('::');
let jsonParams;
try {
jsonParams = JSON.parse(commandSplit[2]);
} catch (error) {
console.log(colors.yellow(`Invalid JSON for snapdev::copy-start, ${file}`));
process.exit(1);
}
if (jsonParams.marker === undefined) {
console.log(colors.yellow(`snapdev::copy-start missing marker key, ${file}`));
process.exit(1);
}
if (jsonParams.dist === undefined) {
console.log(colors.yellow(`snapdev::copy-start missing dist key, ${file}`));
process.exit(1);
}
// command is valid
marker = jsonParams.marker;
dist = jsonParams.dist;
}
});
await once(rl, 'close');
if (copyLine) {
console.log(colors.yellow(`snapdev::copy-end not found, ${file}`));
process.exit(1);
}
return results;
}
for (let index = 0; index < files.length; index++) {
const file = files[index];
if (this.cli.program.verbose) {
console.log('Copy Scan:', file);
}
const results = await processLine(file, this.removeComments);
// console.log(results);
output = output.concat(results);
}
return output;
}
// snapdev::paste::{"marker": "route", "index": 0}
async getPastePlaceholderList(files, distFolder) {
let output = [];
/**
* structure
* {
* marker: '',
* index: 0,
* lineNo: 0,
* dist: ''
* }
*/
async function processLine(file, removeComments) {
const fileStream = fs.createReadStream(file);
const results = [];
let marker = '';
let lineNo = 0;
let index = 0;
const relativeFile = file.replace(distFolder, '');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
rl.on('line', (line) => {
// Process the line.
lineNo += 1;
if (line.indexOf('// snapdev::paste') > -1) {
// snapdev::command::parameters
const commandSplit = removeComments(line).split('::');
let jsonParams;
try {
const jsonData = commandSplit[2];
// make sure to only extract json data
const endBraceIndex = jsonData.indexOf('}');
jsonParams = JSON.parse(jsonData.substring(0, endBraceIndex + 1));
} catch (error) {
console.log(colors.yellow(`Invalid JSON for snapdev::paste, ${file}`));
process.exit(1);
}
if (jsonParams.marker === undefined) {
console.log(colors.yellow(`snapdev::paste missing marker key, ${file}`));
process.exit(1);
}
if (jsonParams.index !== undefined) {
index = jsonParams.index;
}
// command is valid
marker = jsonParams.marker;
results.push({
marker,
lineNo,
index,
dist: relativeFile,
});
marker = '';
}
});
await once(rl, 'close');
return results;
}
for (let index = 0; index < files.length; index++) {
const file = files[index];
if (this.cli.program.verbose) {
console.log('Paste Scan:', file);
}
const results = await processLine(file, this.removeComments);
// console.log(results);
output = output.concat(results);
}
return output;
}
};
|
// Generated on 2015-06-18 using generator-angular-fullstack 2.0.13
'use strict';
module.exports = function (grunt) {
var localConfig;
try {
localConfig = require('./server/config/local.env');
} catch(e) {
localConfig = {};
}
// Load grunt tasks automatically, when needed
require('jit-grunt')(grunt, {
express: 'grunt-express-server',
useminPrepare: 'grunt-usemin',
ngtemplates: 'grunt-angular-templates',
cdnify: 'grunt-google-cdn',
protractor: 'grunt-protractor-runner',
injector: 'grunt-asset-injector',
buildcontrol: 'grunt-build-control'
});
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
pkg: grunt.file.readJSON('package.json'),
yeoman: {
// configurable paths
client: require('./bower.json').appPath || 'client',
dist: 'dist'
},
express: {
options: {
port: process.env.PORT || 9000
},
dev: {
options: {
script: 'server/app.js',
debug: true
}
},
prod: {
options: {
script: 'dist/server/app.js'
}
}
},
open: {
server: {
url: 'http://localhost:<%= express.options.port %>'
}
},
watch: {
injectJS: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.js',
'!<%= yeoman.client %>/{app,components}/**/*.spec.js',
'!<%= yeoman.client %>/{app,components}/**/*.mock.js',
'!<%= yeoman.client %>/app/app.js'],
tasks: ['injector:scripts']
},
injectCss: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.css'
],
tasks: ['injector:css']
},
mochaTest: {
files: ['server/**/*.spec.js'],
tasks: ['env:test', 'mochaTest']
},
jsTest: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.spec.js',
'<%= yeoman.client %>/{app,components}/**/*.mock.js'
],
tasks: ['newer:jshint:all', 'karma']
},
injectSass: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.{scss,sass}'],
tasks: ['injector:sass']
},
sass: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.{scss,sass}'],
tasks: ['sass', 'autoprefixer']
},
jade: {
files: [
'<%= yeoman.client %>/{app,components}/*',
'<%= yeoman.client %>/{app,components}/**/*.jade'],
tasks: ['jade']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
files: [
'{.tmp,<%= yeoman.client %>}/{app,components}/**/*.css',
'{.tmp,<%= yeoman.client %>}/{app,components}/**/*.html',
'{.tmp,<%= yeoman.client %>}/{app,components}/**/*.js',
'!{.tmp,<%= yeoman.client %>}{app,components}/**/*.spec.js',
'!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.mock.js',
'<%= yeoman.client %>/assets/images/{,*//*}*.{png,jpg,jpeg,gif,webp,svg}'
],
options: {
livereload: true
}
},
express: {
files: [
'server/**/*.{js,json}'
],
tasks: ['express:dev', 'wait'],
options: {
livereload: true,
nospawn: true //Without this option specified express won't be reloaded
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '<%= yeoman.client %>/.jshintrc',
reporter: require('jshint-stylish')
},
server: {
options: {
jshintrc: 'server/.jshintrc'
},
src: [
'server/**/*.js',
'!server/**/*.spec.js'
]
},
serverTest: {
options: {
jshintrc: 'server/.jshintrc-spec'
},
src: ['server/**/*.spec.js']
},
all: [
'<%= yeoman.client %>/{app,components}/**/*.js',
'!<%= yeoman.client %>/{app,components}/**/*.spec.js',
'!<%= yeoman.client %>/{app,components}/**/*.mock.js'
],
test: {
src: [
'<%= yeoman.client %>/{app,components}/**/*.spec.js',
'<%= yeoman.client %>/{app,components}/**/*.mock.js'
]
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/*',
'!<%= yeoman.dist %>/.git*',
'!<%= yeoman.dist %>/.openshift',
'!<%= yeoman.dist %>/Procfile'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/',
src: '{,*/}*.css',
dest: '.tmp/'
}]
}
},
// Debugging with node inspector
'node-inspector': {
custom: {
options: {
'web-host': 'localhost'
}
}
},
// Use nodemon to run server in debug mode with an initial breakpoint
nodemon: {
debug: {
script: 'server/app.js',
options: {
nodeArgs: ['--debug-brk'],
env: {
PORT: process.env.PORT || 9000
},
callback: function (nodemon) {
nodemon.on('log', function (event) {
console.log(event.colour);
});
// opens browser on initial server start
nodemon.on('config:update', function () {
setTimeout(function () {
require('open')('http://localhost:8080/debug?port=5858');
}, 500);
});
}
}
}
},
// Automatically inject Bower components into the app
wiredep: {
target: {
src: '<%= yeoman.client %>/index.html',
ignorePath: '<%= yeoman.client %>/',
exclude: [/bootstrap-sass-official/, /bootstrap.js/, '/json3/', '/es5-shim/', /bootstrap.css/, /font-awesome.css/ ]
}
},
// Renames files for browser caching purposes
rev: {
dist: {
files: {
src: [
'<%= yeoman.dist %>/public/{,*/}*.js',
'<%= yeoman.dist %>/public/{,*/}*.css',
'<%= yeoman.dist %>/public/assets/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/public/assets/fonts/*'
]
}
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: ['<%= yeoman.client %>/index.html'],
options: {
dest: '<%= yeoman.dist %>/public'
}
},
// Performs rewrites based on rev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/public/{,*/}*.html'],
css: ['<%= yeoman.dist %>/public/{,*/}*.css'],
js: ['<%= yeoman.dist %>/public/{,*/}*.js'],
options: {
assetsDirs: [
'<%= yeoman.dist %>/public',
'<%= yeoman.dist %>/public/assets/images'
],
// This is so we update image references in our ng-templates
patterns: {
js: [
[/(assets\/images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the JS to reference our revved images']
]
}
}
},
// The following *-min tasks produce minified files in the dist folder
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.client %>/assets/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/public/assets/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.client %>/assets/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/public/assets/images'
}]
}
},
// Allow the use of non-minsafe AngularJS files. Automatically makes it
// minsafe compatible so Uglify does not destroy the ng references
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat',
src: '*/**.js',
dest: '.tmp/concat'
}]
}
},
// Package all the html partials into a single javascript payload
ngtemplates: {
options: {
// This should be the name of your apps angular module
module: 'proyectXApp',
htmlmin: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
removeEmptyAttributes: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true
},
usemin: 'app/app.js'
},
main: {
cwd: '<%= yeoman.client %>',
src: ['{app,components}/**/*.html'],
dest: '.tmp/templates.js'
},
tmp: {
cwd: '.tmp',
src: ['{app,components}/**/*.html'],
dest: '.tmp/tmp-templates.js'
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/public/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.client %>',
dest: '<%= yeoman.dist %>/public',
src: [
'*.{ico,png,txt}',
'.htaccess',
'bower_components/**/*',
'assets/images/{,*/}*.{webp}',
'assets/fonts/**/*',
'index.html'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/public/assets/images',
src: ['generated/*']
}, {
expand: true,
dest: '<%= yeoman.dist %>',
src: [
'package.json',
'server/**/*'
]
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.client %>',
dest: '.tmp/',
src: ['{app,components}/**/*.css']
}
},
buildcontrol: {
options: {
dir: 'dist',
commit: true,
push: true,
connectCommits: false,
message: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%'
},
heroku: {
options: {
remote: 'heroku',
branch: 'master'
}
},
openshift: {
options: {
remote: 'openshift',
branch: 'master'
}
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'jade',
'sass',
],
test: [
'jade',
'sass',
],
debug: {
tasks: [
'nodemon',
'node-inspector'
],
options: {
logConcurrentOutput: true
}
},
dist: [
'jade',
'sass',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true
}
},
mochaTest: {
options: {
reporter: 'spec'
},
src: ['server/**/*.spec.js']
},
protractor: {
options: {
configFile: 'protractor.conf.js'
},
chrome: {
options: {
args: {
browser: 'chrome'
}
}
}
},
env: {
test: {
NODE_ENV: 'test'
},
prod: {
NODE_ENV: 'production'
},
all: localConfig
},
// Compiles Jade to html
jade: {
compile: {
options: {
data: {
debug: false
}
},
files: [{
expand: true,
cwd: '<%= yeoman.client %>',
src: [
'{app,components}/**/*.jade'
],
dest: '.tmp',
ext: '.html'
}]
}
},
// Compiles Sass to CSS
sass: {
server: {
options: {
loadPath: [
'<%= yeoman.client %>/bower_components',
'<%= yeoman.client %>/app',
'<%= yeoman.client %>/components'
],
compass: false
},
files: {
'.tmp/app/app.css' : '<%= yeoman.client %>/app/app.scss'
}
}
},
injector: {
options: {
},
// Inject application script files into index.html (doesn't include bower)
scripts: {
options: {
transform: function(filePath) {
filePath = filePath.replace('/client/', '');
filePath = filePath.replace('/.tmp/', '');
return '<script src="' + filePath + '"></script>';
},
starttag: '<!-- injector:js -->',
endtag: '<!-- endinjector -->'
},
files: {
'<%= yeoman.client %>/index.html': [
['{.tmp,<%= yeoman.client %>}/{app,components}/**/*.js',
'!{.tmp,<%= yeoman.client %>}/app/app.js',
'!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.spec.js',
'!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.mock.js']
]
}
},
// Inject component scss into app.scss
sass: {
options: {
transform: function(filePath) {
filePath = filePath.replace('/client/app/', '');
filePath = filePath.replace('/client/components/', '');
return '@import \'' + filePath + '\';';
},
starttag: '// injector',
endtag: '// endinjector'
},
files: {
'<%= yeoman.client %>/app/app.scss': [
'<%= yeoman.client %>/{app,components}/**/*.{scss,sass}',
'!<%= yeoman.client %>/app/app.{scss,sass}'
]
}
},
// Inject component css into index.html
css: {
options: {
transform: function(filePath) {
filePath = filePath.replace('/client/', '');
filePath = filePath.replace('/.tmp/', '');
return '<link rel="stylesheet" href="' + filePath + '">';
},
starttag: '<!-- injector:css -->',
endtag: '<!-- endinjector -->'
},
files: {
'<%= yeoman.client %>/index.html': [
'<%= yeoman.client %>/{app,components}/**/*.css'
]
}
}
},
});
// Used for delaying livereload until after server has restarted
grunt.registerTask('wait', function () {
grunt.log.ok('Waiting for server reload...');
var done = this.async();
setTimeout(function () {
grunt.log.writeln('Done waiting!');
done();
}, 1500);
});
grunt.registerTask('express-keepalive', 'Keep grunt running', function() {
this.async();
});
grunt.registerTask('serve', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'env:all', 'env:prod', 'express:prod', 'wait', 'open', 'express-keepalive']);
}
if (target === 'debug') {
return grunt.task.run([
'clean:server',
'env:all',
'injector:sass',
'concurrent:server',
'injector',
'wiredep',
'autoprefixer',
'concurrent:debug'
]);
}
grunt.task.run([
'clean:server',
'env:all',
'injector:sass',
'concurrent:server',
'injector',
'wiredep',
'autoprefixer',
'express:dev',
'wait',
'open',
'watch'
]);
});
grunt.registerTask('server', function () {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve']);
});
grunt.registerTask('test', function(target) {
if (target === 'server') {
return grunt.task.run([
'env:all',
'env:test'/*,
'mochaTest'*/
]);
}
else if (target === 'client') {
return grunt.task.run([
'clean:server',
'env:all',
'injector:sass',
'concurrent:test',
'injector',
'autoprefixer',
'karma'
]);
}
else if (target === 'e2e') {
return grunt.task.run([
'clean:server',
'env:all',
'env:test',
'injector:sass',
'concurrent:test',
'injector',
'wiredep',
'autoprefixer',
'express:dev',
'protractor'
]);
}
else grunt.task.run([
'test:server',
'test:client'
]);
});
grunt.registerTask('build', [
'clean:dist',
'injector:sass',
'concurrent:dist',
'injector',
'wiredep',
'useminPrepare',
'autoprefixer',
'ngtemplates',
'concat',
'ngAnnotate',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'rev',
'usemin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
|
'use strict';
angular.module('jhipsterApp')
.controller('LanguageController', function ($scope, $translate, Language, tmhDynamicLocale) {
$scope.changeLanguage = function (languageKey) {
$translate.use(languageKey);
tmhDynamicLocale.set(languageKey);
};
Language.getAll().then(function (languages) {
$scope.languages = languages;
});
})
.filter('findLanguageFromKey', function () {
return function (lang) {
return {
"en": "English",
"fr": "Français",
"de": "Deutsch",
"it": "Italiano",
"ru": "Русский",
"tr": "Türkçe",
"ca": "Català",
"da": "Dansk",
"es": "Español",
"hu": "Magyar",
"ja": "日本語",
"kr": "한국어",
"pl": "Polski",
"pt-br": "Português (Brasil)",
"ro": "Română",
"sv": "Svenska",
"zh-cn": "中文(简体)",
"zh-tw": "繁體中文",
}[lang];
}
});
|
/*--------------------------------------------------------------------------
*
* Key Oriented JSON Application Cache (KOJAC)
* (c) 2011-12 Buzzware Solutions
* https://github.com/buzzware/KOJAC
*
* KOJAC is freely distributable under the terms of an MIT-style license.
*
*--------------------------------------------------------------------------*/
/* Ideas for future
stop using ids in collections, use full key instead
so then cache can be like :
{
allProducts: ['product__1','product__2'],
product__1: {
name: 'red toy'
},
product__2: {
name: 'blue toy'
}
productCol: Emberjac.modelCollection(
'allProducts', // idCollection property, potentially path eg. 'App.cache.allProducts'. Binds to this and its contents
function(aArray){
// optionally filter and/or sort array here, return result leaving original unmodified
}
)
}
*/
// recommended http://www.cerebris.com/blog/2012/03/06/understanding-ember-object/
//var Person = Ember.Object.extend({
// chromosomes: null,
// init: function() {
// this._super();
// this.chromosomes = ["x"]; // everyone gets at least one X chromosome
// }
//});
// declaring property : {chromosomes: null}
// for values, generate function that calls this._super(); then loops thru setting values
// example :
//
//Product = Kojac.EmberModel.extend({
// name: String,
// purchases: Int,
// weight: Number,
// isMember: Boolean,
// init: function() {
// this._super();
// this.weight = 0.0;
// }
//});
//
//
// 1. Create extendObject with properties: null
// 2.
Kojac.EmberObjectFactory = Kojac.ObjectFactory.extend({
defaultClass: Ember.Object,
createInstance: function(aClass,aProperties) {
aProperties = aProperties || {};
return aClass.create(aProperties);
}
});
Kojac.EmberModel = Ember.Object.extend({
// set: function(k,v) {
// var def = this.constructor.getDefinitions();
// var t = (def && def[k]);
// if (t)
// v = Kojac.interpretValueAsType(v,t);
// return this._super(k,v);
// },
//
// setProperties: function(values) {
// values = Kojac.readTypedProperties({},values,this.constructor.getDefinitions());
// return this._super(values);
// },
// copy the property from source to dest
// this could be a static fn
toJsonoCopyFn: function(aDest,aSource,aProperty,aOptions) {
aDest[aProperty] = Kojac.Utils.toJsono(Ember.get(aSource,aProperty),aOptions);
},
// return array of names, or an object and all keys will be used
// this could be a static fn
toPropListFn: function(aSource,aOptions) {
var p;
if (p = aSource && aSource.constructor && aSource.constructor.proto && aSource.constructor.proto()) {
if ((p = Ember.meta(p)) && (p = p.descs)) {
var result = [];
var m;
var d;
var k;
var keys = _.keys(p);
for (var i=0;i<keys.length;i++) {
k = keys[i];
if (!(d = p[k]))
continue;
if (!(m = d.meta()))
continue;
if (m.kemp)
result.push(k);
}
return result;
} else
return [];
} else {
return aSource;
}
},
toJsono: function(aOptions) {
return Kojac.Utils.toJsono(this,aOptions,this.toPropListFn,this.toJsonoCopyFn)
}
});
// in create, set cache with defaults merged with given values
// getter - use cacheFor
// setter - set cache with converted value
// in extend, generate with Ember.computed().cacheable(true)
Kojac.EmberModel.reopenClass({
extend: function() {
var defs = arguments[0];
var extender = {};
var _type;
var _value;
if (defs) {
var destType;
var defaultValue;
for (p in defs) {
var pValue = defs[p];
destType = null;
defaultValue = null;
if (Kojac.FieldTypes.indexOf(pValue)>=0) { // pValue is field type
destType = pValue;
defaultValue = null;
} else {
var ft=Kojac.getPropertyValueType(pValue);
if (ft && (Kojac.SimpleTypes.indexOf(ft)>=0)) { // pValue is simple field value
destType = ft;
defaultValue = pValue;
}
}
if (destType) {
extender[p] = Ember.computed(function(aKey,aValue){
// MyClass.metaForProperty('person');
var m = Ember.meta(this,false);
var d = m && m.descs[aKey];
var v;
if (arguments.length==2) { // set
var t = d && d._meta && d._meta.type;
if (t)
v = Kojac.interpretValueAsType(aValue,t);
else
v = aValue;
//cache[aKey] = v;
} else { // get
var cache = m.cache;
v = Ember.cacheFor(this,aKey);
if (cache && aKey in cache) {
return cache[aKey];
} else {
return d && d._meta && d._meta.value;
}
}
return v;
}).meta({
kemp: true, // Kojac Ember Model Property
type: destType,
value: defaultValue
})
} else {
extender[p] = pValue;
}
}
}
var result = this._super(extender);
return result;
}
});
Kojac.EmberCache = Ember.Object.extend({
generateKey: function(aPrefix) {
var key;
do {
key = aPrefix+'__'+(-_.random(1000000,2000000)).toString();
} while (key in this);
return key;
},
generateId: function(aPrefix) {
var key;
var id;
do {
id = -_.random(1000000,2000000)
key = aPrefix+'__'+id.toString();
} while (key in this);
return id;
},
retrieve: function(k) {
return this.get(k);
},
store: function(k,v) {
this.beginPropertyChanges();
if (v===undefined) {
this.set(k,v);
delete this[k];
} else {
this.set(k,v);
}
this.endPropertyChanges();
},
collectIds: function(aPrefix, aIds, aFilterFn) {
if (!aIds)
aIds = this.get(aPrefix);
return Kojac.collectIds(aPrefix,aIds,this,aFilterFn);
}
});
Kojac.collectIds = function(aPrefix,aIds,aCache,aFilterFn) {
if (!aIds)
return [];
var result = [];
var item;
for (var i=0;i<aIds.length;i++) {
item = aCache.get(aPrefix+'__'+aIds[i]);
if (!aFilterFn || aFilterFn(item))
result.push(item);
}
return result;
};
Ember.computed.collectIds = function(aCollectionProperty,aPrefix,aModelCachePath,aFilterFn){
if (!aPrefix)
aPrefix = _.last(aCollectionProperty.split('.'));
var result = Ember.computed(aCollectionProperty, function(){
var cache;
if (aModelCachePath)
cache = Ember.Handlebars.get(this,aModelCachePath); //(aModelCachePath && Ember.get(aModelCachePath));
else
cache = this;
var ids = Ember.Handlebars.get(this,aCollectionProperty);
if (!ids)
return [];
var objects = [];
var item;
for (var i=0;i<ids.length;i++) {
item = cache.get(aPrefix+'__'+ids[i]);
if (!aFilterFn || aFilterFn(item))
objects.push(item);
}
return objects;
});
return result.property.apply(result, _.compact([aModelCachePath,aCollectionProperty+'.@each']));
};
Ember.computed.has_many = function(aResource,aForeignKey,aLocalPropertyPath,aModelCachePath,aFilterFn){
return Ember.computed(function(){
var cache;
if (aModelCachePath)
cache = Ember.Handlebars.get(this,aModelCachePath); //(aModelCachePath && Ember.get(aModelCachePath));
else
cache = this;
var localValue = Ember.Handlebars.get(this,aLocalPropertyPath);
if (!_.endsWith(aResource,'__'))
aResource = aResource+'__';
var results = [];
// get all keys that begin with aPrefix
var keys = _.keys(cache);
for (var i=0;i<keys.length;i++) {
var k = keys[i];
if (!_.beginsWith(k,aResource))
continue;
var v = cache.get(k);
if (!v || (v.get(aForeignKey) != localValue))
continue;
if (aFilterFn && !aFilterFn(k,v))
continue;
results.push(v);
}
return results;
}).property(aModelCachePath,aLocalPropertyPath);
};
Ember.computed.modelById = function(aIdProperty,aPrefix,aModelCachePath) {
if (!aModelCachePath)
aModelCachePath = 'App.cache';
return Ember.computed(aIdProperty, function(){
var id = Ember.Handlebars.get(this,aIdProperty);
if (!id)
return null;
var cache = Ember.Handlebars.get(this,aModelCachePath);
var key = keyJoin(aPrefix,id);
if (!key || !cache)
return null;
return Ember.Handlebars.get(cache,key);
}).property(aModelCachePath,aIdProperty);
};
Ember.computed.modelByIdVersioned = function(aIdProperty,aVerProperty,aPrefix,aModelCachePath) {
if (!aModelCachePath)
aModelCachePath = 'App.cache';
return Ember.computed(aIdProperty, function(){
var id = Ember.Handlebars.get(this,aIdProperty);
var cache = Ember.Handlebars.get(this,aModelCachePath);
if (!id || !cache)
return null;
var key;
var ver = Ember.Handlebars.get(this,aVerProperty);
if (ver) {
id = [id,ver].join('_');
key = keyJoin(aPrefix,id);
return Ember.Handlebars.get(cache,key);
} else {
var versions = _.pickWithPrefix(cache,keyJoin(aPrefix,id)+'_');
var v,vi;
key = _.max(_.keys(versions), function(k){
vi = k.lastIndexOf('_');
return Number(k.substr(vi+1));
});
return key ? versions[key] : null;
}
}).property(aModelCachePath,aIdProperty,aVerProperty);
};
|
'use strict';
var _ = require('underscore'),
http = require('http'),
querystring = require('querystring'),
url = require('url'),
Command = require('./command'),
NameMap = require('./name-map');
var App, PayloadError;
App = function(config) {
if (!(this instanceof App)) {
return new App(config);
}
this.config = _.defaults(config, {
botName: 'Name Map Server',
command: '/irc',
fileName: './map.json',
token: '',
port: 80
});
this.nameMap = NameMap(this.config.fileName);
this.command = Command(this.nameMap);
this.nameMap.setMappigQuota(this.config.mappigQuota);
};
App.prototype._server = function() {
var server = http.createServer(function(req, res) {
if (req.method === 'GET') {
this._getHandler(req, res);
} else if (req.method === 'POST') {
this._postHandler(req, res);
} else {
res.end('Error! InvalidMethod');
}
}.bind(this));
return server;
};
App.prototype._getHandler = function(req, res) {
try {
var token = url.parse(req.url, true).query.token;
if (token !== this.config.token) {
throw new PayloadError('Invalid token! Please check your configure.');
}
res.end(JSON.stringify(this.nameMap.getMap()));
} catch(e) {
if (_.contains(['PayloadError', 'NameMapError'], e.name)) {
res.end(e.toString());
} else {
throw e;
}
}
};
App.prototype._postHandler = function(req, res) {
req.on('data', function(data) {
try {
var payload = this._payloadHandler(querystring.parse(data.toString()));
this.nameMap.setSlackName(payload.user_name);
this.command.execute(payload.text);
res.end(this.command.getResponse());
} catch(e) {
if (_.contains(['PayloadError', 'NameMapError', 'CommandError'], e.name)) {
res.end(e.toString());
} else {
throw e;
}
}
}.bind(this));
};
App.prototype._payloadHandler = function(payload) {
payload = _.defaults(payload, {
token: '',
user_name: '',
text: ''
});
if (payload.command !== this.config.command) {
throw new PayloadError('Invalid command! Please check your slash command interaction.');
} else if (_.isEmpty(payload.user_name)) {
throw new PayloadError('Empty username!');
} else if (payload.token !== this.config.token) {
throw new PayloadError('Invalid token! Please check your configure.');
}
return payload;
};
App.prototype.listen = function() {
this._server().listen(this.config.port);
console.log('Server running at ' +
'http://localhost:' + this.config.port + '/');
};
PayloadError = function(message) {
this.name = 'PayloadError';
this.message = (message || '');
};
PayloadError.prototype = new Error();
PayloadError.prototype.constructor = PayloadError;
module.exports = App;
|
angular.module('RESTAPIDemo', []);
angular.module('RESTAPIDemo').controller('RESTAPIDemoController', function ($scope, $http) {
$scope.token;
$scope.requestToken = function () {
//var url = "/auth/getauthtoken";
var url = "/api/1.0/tokenauth";
var data = {
username: "ben",
password: "123"
}
$http.post(url, data).success(function (data) {
$scope.apiReturn = data;
$scope.token = data.token;
console.log($scope.apiReturn);
});
};
$scope.accessPublicResource = function () {
var url = '/api/hello'
$http.get(url).success(function (data) {
$scope.apiReturn = data;
});
};
$scope.accessPrivateResource = function () {
//$scope.token ????
var url = '/api/1.0/privatehello'
$http.get(url).success(function (data) {
$scope.apiReturn = data;
}).error(function (data, status) {
$scope.apiReturn = status;
return status;
});
};
$scope.accessAdminResource = function () {
var url = '/getauthtoken'
$http.get(url).success(function (data) {
$scope.apiReturn = data;
});
};
}); |
// bad
[1, 2, 3].map(function (x) {
return x * x;
});
// good
[1, 2, 3].map((x) => {
return x * x;
});
// good
[1, 2, 3].map(x => x * x);
// good
[1, 2, 3].reduce((total, n) => {
return total + n;
}, 0);
|
/** Nub frame functionality tests cases. */
(function($) {
module('Nub: menu');
function resetFrameElement(){
$('#dynamic-menu-frame').replaceWith('<div id="dynamic-menu-frame">Frame:</div>');
}
// Test Dynamic Menu with a set of pre-configured values.
test('DynamicMenuConfiguration', function(){
expect( );
// Test Dynamic Menu with default values.
var frame = $('#dynamic-menu').nubDynamicMenu();
// Check default values
$.nub.set('/data/contentKeyRef', 'section1');
same(frame, $('#dynamic-menu-frame'),"Create dynamic frame for menu with defaults configuration");
// TODO : Reset element
resetFrameElement();
// Simple Dyamic Menu test : Read data from url : data/section1...
var frame = $('#dynamic-menu').nubDynamicMenu({
'frame' : {
'contentKeyRef' : '/data/contentKeyRef',
'makeLayoutURI' : function( key ){
var path = 'data/' + key + '/main.html';
console.log('setting the path to ... ' +path );
return path;
}
},
'frameLookup' : function(menuItem){
console.log("frameLookup : " + menuItem.attr('id') + '-frame');
return $('#' + menuItem.attr('id') + '-frame');
}
});
function testSection( section ){
$.nub.set('/data/contentKeyRef', section);
var temp = $.nub.get('/data/contentKeyRef');
same(frame, $('#dynamic-menu-frame'),"Dynamic Frame to show menu's section created");
// TODO: How to test dynamic frames ??
console.log("Frame html: %o", $('#dynamic-menu-frame').html());// div element is empty
}
testSection("section1");
//$.nub.set('/data/contentKeyRef', 'section2');
//testSection("section1");
});
})(jQuery);
|
import React from "react";
import ReactDOM from "react-dom";
import hljsThemes from "../../src/hljs-themes.json";
import { THEMES, PRETTY_THEME_NAMES_MAP } from '../constants';
export default class ThemeList extends React.Component {
constructor() {
super(...arguments);
this.state = {
searchValue: '',
luminosity: 'dark',
}
this.filteredThemes = THEMES.filter((theme) => hljsThemes[theme].isDark);
this.onClick = this.onClick.bind(this);
this.onSearch = this.onSearch.bind(this);
this.onLuminosityChange = this.onLuminosityChange.bind(this);
}
componentWillUpdate(nextProps, nextState) {
const luminosityChanged = this.state.luminosity !== nextState.luminosity;
const searchChanged = this.state.searchValue !== nextState.searchValue;
if (luminosityChanged || searchChanged) {
this.filterThemes(nextState);
}
if (luminosityChanged && this.filteredThemes.length) {
this.props.onThemeSelected(this.filteredThemes[0]);
}
}
componentDidMount() {
setTimeout(() => {
this.refs.search && this.refs.search.focus();
});
document.body.addEventListener('keydown', (event) => {
const keyCode = event.keyCode;
const arrow = {
left: keyCode === 37,
up: keyCode === 38,
right: keyCode === 39,
down: keyCode === 40,
}
if (this.state.searchValue.length && (arrow.left || arrow.right) && event.target.matches('input, textarea')) {
return;
}
if (arrow.left || arrow.up || arrow.right || arrow.down) {
event.preventDefault();
arrow.left && this.setState({ luminosity: 'dark' });
arrow.right && this.setState({ luminosity: 'light' });
arrow.up && this.prevTheme();;
arrow.down && this.nextTheme();;
mixpanel.track('Arrow Navigation', { direction: Object.keys(arrow).find((key) => arrow[key]) });
}
});
}
onClick(e) {
const theme = e.target.getAttribute('data-value');
this.props.onThemeSelected(theme);
}
filterThemes({ searchValue, luminosity } = this.state) {
this.filteredThemes = THEMES.filter((theme) => {
const isDark = hljsThemes[theme].isDark;
const matches = !searchValue || theme.toLowerCase().indexOf(searchValue.toLowerCase()) > -1;
if (matches && luminosity === 'dark' && isDark) {
return true;
} else if (matches && luminosity === 'light' && !isDark) {
return true;
}
return false;
});
}
onSearch(e) {
const query = e.target.value;
this.setState({
searchValue: query
});
mixpanel.track('Search', { query: query });
}
onLuminosityChange(e) {
const luminosity = e.target.getAttribute('data-value');
mixpanel.track('Theme Luminosity Changed', { luminosity: luminosity });
this.setState({ luminosity: luminosity });
}
scrollItemIntoView(theme) {
const li = this.refs.list.querySelector(`li[data-value="${theme}"]`);
li && li.scrollIntoView(false);
}
nextTheme() {
const currentIndex = this.filteredThemes.indexOf(this.props.selected);
const nextIndex = Math.min(this.filteredThemes.length - 1, currentIndex + 1);
const theme = this.filteredThemes[nextIndex];
this.props.onThemeSelected(theme);
this.scrollItemIntoView(theme);
}
prevTheme() {
const currentIndex = this.filteredThemes.indexOf(this.props.selected);
const nextIndex = Math.max(0, currentIndex - 1);
const theme = this.filteredThemes[nextIndex];
this.props.onThemeSelected(theme);
this.scrollItemIntoView(theme);
}
render() {
const themes = this.filteredThemes.map((theme, i) => {
let className = `ThemeList-listItem ${theme == this.props.selected ? 'is-active' : ''}`;
return (
<li
onClick={this.onClick}
data-value={theme}
className={className}
key={i}>
{PRETTY_THEME_NAMES_MAP[theme]}
</li>
);
});
return(
<div className="ThemeList">
<div className="ThemeList-segmentedControl">
<nav className="SegmentedControl">
<button data-value="dark" onClick={this.onLuminosityChange} className={this.state.luminosity === 'dark' ? 'is-active' : ''}>Dark</button>
<button data-value="light" onClick={this.onLuminosityChange} className={this.state.luminosity === 'light' ? 'is-active' : ''}>Light</button>
</nav>
</div>
<input ref="search" className="ThemeList-search" type="search" placeholder="Search..." value={this.state.searchValue} onChange={this.onSearch} autoComplete="off" autoCorrect="off" autoCapitalize="off" spellCheck="false" />
<ul ref="list" className="ThemeList-list">
{ themes }
</ul>
</div>
);
}
}
|
import { VERSION, LEG_CAVE, LEG_SPLAY, LEG_DUPLICATE, LEG_SURFACE } from '../core/constants';
import { Page } from './Page';
class InfoPage extends Page {
constructor ( frame, viewer, fileSelector ) {
super( 'icon_info', 'info' );
frame.addPage( this );
this.addHeader( 'header' );
this.addHeader( 'stats.header' );
this.addText( this.i18n( 'file' ) + ': ' + fileSelector.file );
const stats = viewer.getLegStats( LEG_CAVE );
this.addBlankLine();
this.addLine( this.i18n( 'stats.legs' ) + ': ' + stats.legCount );
this.addLine( this.i18n( 'stats.totalLength' ) + ': ' + stats.legLength.toFixed( 2 ) + '\u202fm' );
this.addLine( this.i18n( 'stats.minLength' ) + ': ' + stats.minLegLength.toFixed( 2 ) + '\u202fm' );
this.addLine( this.i18n( 'stats.maxLength' ) + ': ' + stats.maxLegLength.toFixed( 2 ) + '\u202fm' );
if ( viewer.hasSplays || viewer.hasDuplicateLegs || viewer.hasSurfaceLegs ) {
this.addBlankLine();
this.addLine( 'Other legs' );
this.addBlankLine();
}
if ( viewer.hasSplays ) {
const splayStats = viewer.getLegStats( LEG_SPLAY );
this.addLine( this.i18n( 'stats.splayCount' ) + ': ' + splayStats.legCount );
}
if ( viewer.hasDuplicateLegs ) {
const duplicateStats = viewer.getLegStats( LEG_DUPLICATE );
this.addLine( this.i18n( 'stats.duplicateCount' ) + ': ' + duplicateStats.legCount );
}
if ( viewer.hasSurfaceLegs ) {
const surfaceStats = viewer.getLegStats( LEG_SURFACE );
this.addLine( this.i18n( 'stats.surfaceCount' ) + ': ' + surfaceStats.legCount );
}
this.addHeader( 'CaveView v' + VERSION + '.' );
this.addLogo();
this.addText( this.i18n( 'summary' ) );
this.addText( this.i18n( 'more' ) + ': ' );
this.addLink( 'https://aardgoose.github.io/CaveView.js/', this.i18n( 'github' ) );
this.addText( '© Angus Sawyer, 2021' );
}
}
export { InfoPage }; |
require('babel-register');
//projection transformation
const proj4 = require('proj4');
proj4.defs('EPSG:25832', "+proj=utm +zone=32 +ellps=GRS80 +units=m +no_defs");
const targetProjection = 'EPSG:4326';
const rp = require('request-promise-native');
const deepmerge = require('deepmerge');
const promisify = require("es6-promisify");
const parseXMLString = promisify(require('xml2js').parseString);
//setup target DB
const config = require('../../config');
const getModel = require('../../src/helper/mongoDB.js')(config.mongoDB);
const LocationModel = getModel('location');
//arguments that are identical for all calls
const baseArgs = {
uri: 'https://www.kulturarv.dk/repox/OAIHandler',
qs: {
'verb': 'ListRecords'
}
};
//arguments just for the first call
const firstCallArgs = deepmerge(baseArgs, {
qs: {
set: 'Listed',
metadataPrefix: 'fbb'
}
});
/**
* prepare a dataset for the DB
* @param data
* @returns {{resumptionToken: *, records: *}}
*/
function prepareForImport(data) {
const listRecords = data['OAI-PMH'].ListRecords;
const records = listRecords[0].record;
const resumptionTokenObject = listRecords[0].resumptionToken[0];
console.log(listRecords[0].record.length);
console.log(resumptionTokenObject._);
if (resumptionTokenObject['$']) {
console.log(resumptionTokenObject['$'].cursor + '+' + records.length + ' of ' + resumptionTokenObject['$'].completeListSize);
}
return {
resumptionToken: resumptionTokenObject._,
records: listRecords[0].record.map(prepareRecord)
};
}
/**
* transforming all geo data to a standard
* @param coordinates
* @param projection
* @returns {*}
*/
function normalizeGeo(coordinates, projection) {
return proj4(projection, targetProjection, coordinates);
}
function prepareRecord(record) {
try {
var building = record.metadata[0]['fbb:buildingWrap'][0]['fbb:building'][0];
var BBR = building['fbb:BBR'][0];
var caseStudy = building['fbb:caseWrap'][0]['fbb:case'][0];
var primaryAdress = BBR['fbb:primaryAddress'][0];
var coordinates = normalizeGeo(primaryAdress['fbb:location'][0]['gml:MultiPoint'][0]['gml:pointMember'][0]['gml:Point'][0]['gml:coordinates'][0].split(','), primaryAdress['fbb:location'][0]['gml:MultiPoint'][0]['$']['srsName']);
var data = {
originalUrl: building['fbb:id'][0],
name: caseStudy['fbb:name'] && caseStudy['fbb:name'][0] || caseStudy['fbb:caseLocation'] && caseStudy['fbb:caseLocation'][0],
extent: caseStudy['fbb:extent'] && caseStudy['fbb:extent'][0],
address : {
streetNumber: primaryAdress['fbb:streetNumber'] && primaryAdress['fbb:streetNumber'][0],
streetName: primaryAdress['fbb:streetName'] && primaryAdress['fbb:streetName'][0],
house_no: primaryAdress['fbb:house_no'] && primaryAdress['fbb:house_no'][0],
post_code: primaryAdress['fbb:post_code'] && primaryAdress['fbb:post_code'][0],
postal_district: primaryAdress['fbb:postal_district'] && primaryAdress['fbb:postal_district'][0]
},
location: {coordinates},
municipalityId: BBR['fbb:municipality'][0] && BBR['fbb:municipality'][0]['fbb:conceptID'][0],
municipalityTerm: BBR['fbb:municipality'][0] && BBR['fbb:municipality'][0]['fbb:term'][0],
postCode: primaryAdress['fbb:post_code'][0],
postDistrict: primaryAdress['fbb:postal_district'][0],
complexTypeId: caseStudy['fbb:complexType'] && caseStudy['fbb:complexType'][0] && caseStudy['fbb:complexType'][0]['fbb:conceptID'][0],
complexTypeTerm: caseStudy['fbb:complexType'] && caseStudy['fbb:complexType'][0] && caseStudy['fbb:complexType'][0]['fbb:term'][0],
constructionYear: typeof BBR['fbb:constructionYear'][0] === 'string' && BBR['fbb:constructionYear'][0].split('-')[0],
conversionYear: typeof BBR['fbb:conversionYear'][0] === 'string' && BBR['fbb:conversionYear'][0].split('-')[0],
floors: BBR['fbb:floors'] && BBR['fbb:floors'][0],
buildArea: BBR['fbb:builtArea'] && BBR['fbb:builtArea'][0],
totalArea: BBR['fbb:totalArea'] && BBR['fbb:totalArea'][0],
material: {
outerWallsId: BBR['fbb:outerWalls'] && BBR['fbb:outerWalls'][0] && BBR['fbb:outerWalls'][0]['fbb:conceptID'] && BBR['fbb:outerWalls'][0]['fbb:conceptID'][0],
outerWallsTerm: BBR['fbb:outerWalls'] && BBR['fbb:outerWalls'][0] && BBR['fbb:outerWalls'][0]['fbb:term'] && BBR['fbb:outerWalls'][0]['fbb:term'][0],
roofId: BBR['fbb:roof'] && BBR['fbb:roof'][0] && BBR['fbb:roof'][0]['fbb:conceptID'] && BBR['fbb:roof'][0]['fbb:conceptID'][0],
roofTerm: BBR['fbb:roof'] && BBR['fbb:roof'][0] && BBR['fbb:roof'][0]['fbb:term'] && BBR['fbb:roof'][0]['fbb:term'][0],
materialsSourceId: BBR['fbb:materialsSource'] && BBR['fbb:materialsSource'][0] && BBR['fbb:materialsSource'][0]['fbb:conceptID'] && BBR['fbb:materialsSource'][0]['fbb:conceptID'][0],
materialsSourceTerm: BBR['fbb:materialsSource'] && BBR['fbb:materialsSource'][0] && BBR['fbb:materialsSource'][0]['fbb:term'] && BBR['fbb:materialsSource'][0]['fbb:term'][0],
areaSourceId: BBR['fbb:areaSource'] && BBR['fbb:areaSource'][0] && BBR['fbb:areaSource'][0]['fbb:conceptID'] && BBR['fbb:areaSource'][0]['fbb:conceptID'][0],
areaSourceTerm: BBR['fbb:areaSource'] && BBR['fbb:areaSource'][0] && BBR['fbb:areaSource'][0]['fbb:term'] && BBR['fbb:areaSource'][0]['fbb:term'][0]
},
usageId: BBR['fbb:usage'] && BBR['fbb:usage'][0] && BBR['fbb:usage'][0]['fbb:conceptID'] && BBR['fbb:usage'][0]['fbb:conceptID'][0],
usageTerm: BBR['fbb:usage'] && BBR['fbb:usage'][0] && BBR['fbb:usage'][0]['fbb:term'] && BBR['fbb:usage'][0]['fbb:term'][0],
source : 'frededeBygninger'
};
} catch (e) {
console.log('cannot extract data from record', e, JSON.stringify(record));
}
//Interesting -> category?
//BBR['fbb:usage'][0]['fbb:conceptID'][0] //406
//BBR['fbb:usage'][0]['fbb:term'][0] //Anden bygning til fritidsformål
//more about the material of walls, roof, area etc under BBR.
//fbb:photographWrap is crap -> just a house on a crappy map
return data;
}
/**
* method for post-harvesting, like storing in a database
* @param data
*/
const harvestingCompleted = (data) => {
console.log('harvestingCompleted: ' + data.length + ' records');
Promise.all(data.map((data)=> {
return new LocationModel(data).save();
}))
.then(()=> {
console.log('done');
})
.catch((e)=> {
console.log('error:', e);
});
};
const next =
(function () {
const recordCollector = [];
var nextToken;
var firstRun = true;
return function () {
if (!firstRun && !nextToken) {
harvestingCompleted(recordCollector);
return;
}
var options = firstRun ? firstCallArgs : deepmerge(baseArgs, {
qs: {
resumptionToken: nextToken
}
});
firstRun = false;
return rp(options)
.then((xmlString) => parseXMLString(xmlString))
.then(prepareForImport)
.then((data) => {
nextToken = data.resumptionToken;
return data.records;
})
.then((records) => {
if (records.length) {
Array.prototype.push.apply(recordCollector, records);
console.log('harvesting in progress:', recordCollector.length);
//start next iteration
setTimeout(next);
return;
}
harvestingCompleted(recordCollector);
}).catch(function (err) {
console.log(err);
});
};
})();
//initial trigger
next(); |
import React from 'react'
import DocumentTitle from 'react-document-title'
import { config } from 'config'
import FrontPagePosts from 'components/FrontPagePosts'
export default class Index extends React.Component {
render () {
return (
<DocumentTitle title={config.siteTitle}>
<FrontPagePosts pages={this.props.route.pages} />
</DocumentTitle>
)
}
}
|
// // JavaScript Olympics
// // I paired with Tyler Doershuck on this challenge.
// // This challenge took me [#] hours.
// // Warm Up
// /* PC
// function that takes an array
// create an array
// function that takes the array an argument
// iterate through array to add 'win' property
// create a function
// function accepts a string as argument
// use method to reverse string
/*
create a function that accepts array argument
iterate through array
use modulus to determind even or odd
put even into new array
return new array
*/
// */
// // Bulk Up
// var olympic_array = [
// {
// name: "Sarah Hughes",
// event: "Ladies Singles",
// },
// {
// name: "Michael Phelps",
// event: "Mens 100m Freestyle",
// },
// {
// name: "Usain Bolt",
// event: "Mens 100m Dash",
// }
// ];
// // console.log(olympic_array)
// function add_won (array) {
// for (var i = 0; i < array.length; i++)
// {var add_prop = olympic_array[i].name + " won the " + olympic_array[i].event;
// array[i].win = add_prop;
// }
// return olympic_array;
// }
// console.log(add_won(olympic_array))
// Jumble your words
// var string = "Reverse Me";
// function reverse(string)
// {return string.split("").reverse().join("");}
// console.log(reverse(string))
//function reverse(string) {}
// 2,4,6,8
// var numbers = [1,4,5,6,10,13,14];
// var return_array = [];
// function even(array) {
// for (var i = 0; i < array.length; i++ ) {
// if (array[i] % 2 === 0) {
// return_array.push(array[i]);
// // return_array = array[i];
// }
// }
// return return_array;
// }
// console.log(even(numbers))
// "We built this city"
var michaelPhelps = new Athlete("Michael Phelps", 29, "swimming", "It's medicinal I swear!")
console.log(michaelPhelps.constructor === Athlete)
console.log(michaelPhelps.name + " " + michaelPhelps.sport + " " + michaelPhelps.quote)
// Example can be run directly in your JavaScript console
function Athlete(name, age, sport, quote){
this.name = name;
this.age = age;
this.sport = sport;
this.quote = quote;
};
// function myObject(what){
// this.iAm = what;
// this.whatAmI = function(language){
// alert('I am ' + this.iAm + ' of the ' + language + ' language');
// };
// };
/*
What JavaScript knowledge did you solidify in this challenge?
The for loop. My partner did a great job describing to me how it works. The three sections of data have confused me. It was nice to use it correctly.
What are constructor functions?
They are a function that can be used to create many objects of one type.
How are constructors different from Ruby classes (in your research)?
Ruby classes are more about methods and variables revelant to the data manipulation while constructors are able to create new data quickly.
*/ |
module.exports = {
plugins: [
require('postcss-salad')({
browsers: ['ie > 6', 'last 2 versions'],
features: {
autoprefixer: {
remove: false,
},
},
}),
],
};
|
"use strict";
var yaml = require('js-yaml');
exports.jsNull = null;
exports.objToHash = function(valueToYAMLImpl, fst, snd, obj) {
var hash = {};
for(var i = 0; i < obj.length; i++) {
hash[fst(obj[i])] = valueToYAMLImpl(snd(obj[i]));
}
return hash;
};
exports.toYAMLImpl = function(a) {
// noCompatMode does not support YAML 1.1
return yaml.safeDump(a, {noCompatMode : true});
}
|
var MATRIX_SIZE = 10;
var VERTICAL = 0, HORIZONTAL = 1;
var SHIP_SIZES = [4, 3, 3, 2, 2, 2, 1, 1, 1, 1];
var WEST = new Direction(-1), EAST = new Direction(1), NORTH = new Direction(-1), SOUTH = new Direction(1);
var CELL_EMPTY = 0, CELL_WITH_SHIP = 1, CELL_BLOCKED = 2, CELL_MISSED = 3, CELL_SHIP_DESTROYED = 4;
var CELL_SIZE = 33;
var opponent, you, setup;
var DELAY_BETWEEN_MOVES = 500;
var game;
$(function() {
if (isGameInProgress()){
startGame();
} else {
settlement();
}
});
function settlement(){
$("#game").hide();
$("#settlement").show();
setup = new Player($('#SettlePlayer'), "Settle your ships", true);
setup.render();
setup.setClickEnabled(false);
setup.setActive(false);
$("#StartGame").click(function() {
startGame();
});
$("#ResetSettlement").click(function() {
location.reload();
});
renderNonSettledShips($("#AvailableShipsHolder"));
$('#StartGame').attr("disabled", true);
$(document).on("allShipsSettled", function (e){
$('#StartGame').attr("disabled", false);
});
}
function startGame(){
$("#game").show();
$("#settlement").hide();
you = new Player($('#You'), 'Player');
if (setup) {
you.setStateMatrix(setup.getStateMatrix());
}
you.render();
you.setClickEnabled(false);
you.setActive(false);
opponent = new Player($('#Computer'), 'Computer');
opponent.setShowShips(false);
opponent.populateRandomly();
opponent.render();
setGameInProgress();
game = new Game(you, opponent);
game.start();
$("#NewGame").click(function() {
if (!isGameInProgress() || confirm("Are you sure you want to quit current game?")) {
removeFromLocalStorage(you.getContainerId());
removeFromLocalStorage(opponent.getContainerId());
location.reload();
}
});
}
function Game(me, opponent) {
this.start = function(){
$(document).on('nextPlayer', function(e) {
if (e.target.id === opponent.getContainerId()){
opponent.setClickEnabled(false);
setTimeout(function(){
opponent.setActive(false);
me.setActive(true);
}, DELAY_BETWEEN_MOVES);
setTimeout(function(){
me.autoShotNextField();
}, DELAY_BETWEEN_MOVES*2);
} else if (e.target.id === me.getContainerId()){
setTimeout(function(){
opponent.setClickEnabled(true);
opponent.setActive(true);
me.setActive(false);
}, DELAY_BETWEEN_MOVES);
}
});
$(document).on('playAgain', function(e) {
if (e.target.id === me.getContainerId()) {
setTimeout(function(){
me.autoShotNextField();
}, DELAY_BETWEEN_MOVES * 1.5);
}
});
$(document).on('gameOver', function(e) {
opponent.setClickEnabled(false);
opponent.setActive(false);
me.setClickEnabled(false);
me.setActive(false);
if (e.target.id === me.getContainerId()) {
opponent.setShowShips(true);
opponent.render();
}
removeFromLocalStorage(me.getContainerId());
removeFromLocalStorage(opponent.getContainerId());
alert ("" + e.target.id + " lost! Game over!");
});
};
}
function Direction(value){
var _value = value;
this.getValue = function(){
return _value;
};
}
|
(function() {
"use strict";
angular.module('angular-carousel-extended')
.service('DeviceCapabilities', function() {
// TODO: merge in a single function
// detect supported CSS property
function detectTransformProperty() {
var transformProperty = 'transform',
safariPropertyHack = 'webkitTransform';
if (typeof document.body.style[transformProperty] !== 'undefined') {
['webkit', 'moz', 'o', 'ms'].every(function (prefix) {
var e = '-' + prefix + '-transform';
if (typeof document.body.style[e] !== 'undefined') {
transformProperty = e;
return false;
}
return true;
});
} else if (typeof document.body.style[safariPropertyHack] !== 'undefined') {
transformProperty = '-webkit-transform';
} else {
transformProperty = undefined;
}
return transformProperty;
}
//Detect support of translate3d
function detect3dSupport() {
var el = document.createElement('p'),
has3d,
transforms = {
'webkitTransform': '-webkit-transform',
'msTransform': '-ms-transform',
'transform': 'transform'
};
// Add it to the body to get the computed style
document.body.insertBefore(el, null);
for (var t in transforms) {
if (el.style[t] !== undefined) {
el.style[t] = 'translate3d(1px,1px,1px)';
has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
}
}
document.body.removeChild(el);
return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
}
return {
has3d: detect3dSupport(),
transformProperty: detectTransformProperty()
};
})
.service('computeCarouselSlideStyle', function(DeviceCapabilities) {
// compute transition transform properties for a given slide and global offset
return function(slideIndex, offset, transitionType) {
var style = {
display: 'inline-block'
},
opacity,
absoluteLeft = (slideIndex * 100) + offset,
slideTransformValue = DeviceCapabilities.has3d ? 'translate3d(' + absoluteLeft + '%, 0, 0)' : 'translate3d(' + absoluteLeft + '%, 0)',
distance = ((100 - Math.abs(absoluteLeft)) / 100);
if (!DeviceCapabilities.transformProperty) {
// fallback to default slide if transformProperty is not available
style['margin-left'] = absoluteLeft + '%';
} else {
if (transitionType == 'fadeAndSlide') {
style[DeviceCapabilities.transformProperty] = slideTransformValue;
opacity = 0;
if (Math.abs(absoluteLeft) < 100) {
opacity = 0.3 + distance * 0.7;
}
style.opacity = opacity;
} else if (transitionType == 'hexagon') {
var transformFrom = 100,
degrees = 0,
maxDegrees = 60 * (distance - 1);
transformFrom = offset < (slideIndex * -100) ? 100 : 0;
degrees = offset < (slideIndex * -100) ? maxDegrees : -maxDegrees;
style[DeviceCapabilities.transformProperty] = slideTransformValue + ' ' + 'rotateY(' + degrees + 'deg)';
style[DeviceCapabilities.transformProperty + '-origin'] = transformFrom + '% 50%';
} else if (transitionType == 'zoom') {
style[DeviceCapabilities.transformProperty] = slideTransformValue;
var scale = 1;
if (Math.abs(absoluteLeft) < 100) {
scale = 1 + ((1 - distance) * 2);
}
style[DeviceCapabilities.transformProperty] += ' scale(' + scale + ')';
style[DeviceCapabilities.transformProperty + '-origin'] = '50% 50%';
opacity = 0;
if (Math.abs(absoluteLeft) < 100) {
opacity = 0.3 + distance * 0.7;
}
style.opacity = opacity;
} else {
style[DeviceCapabilities.transformProperty] = slideTransformValue;
}
}
return style;
};
})
.service('createStyleString', function() {
return function(object) {
var styles = [];
angular.forEach(object, function(value, key) {
styles.push(key + ':' + value);
});
return styles.join(';');
};
})
.directive('rnCarousel', ['$swipe', '$window', '$document', '$parse', '$compile', '$timeout', '$interval', '$rootScope', 'computeCarouselSlideStyle', 'createStyleString', 'Tweenable',
function($swipe, $window, $document, $parse, $compile, $timeout, $interval, $rootScope, computeCarouselSlideStyle, createStyleString, Tweenable) {
// internal ids to allow multiple instances
var carouselId = 0,
// in absolute pixels, at which distance the slide stick to the edge on release
rubberTreshold = 3;
var requestAnimationFrame = $window.requestAnimationFrame || $window.webkitRequestAnimationFrame || $window.mozRequestAnimationFrame;
function getItemIndex(collection, target, defaultIndex) {
var result = defaultIndex;
collection.every(function(item, index) {
if (angular.equals(item, target)) {
result = index;
return false;
}
return true;
});
return result;
}
return {
restrict: 'A',
scope: true,
compile: function(tElement, tAttributes) {
// use the compile phase to customize the DOM
var firstChild = tElement[0].querySelector('li'),
firstChildAttributes = (firstChild) ? firstChild.attributes : [],
isRepeatBased = false,
isBuffered = false,
repeatItem,
repeatCollection;
// try to find an ngRepeat expression
// at this point, the attributes are not yet normalized so we need to try various syntax
['ng-repeat', 'data-ng-repeat', 'ng:repeat', 'x-ng-repeat'].every(function(attr) {
var repeatAttribute = firstChildAttributes[attr];
if (angular.isDefined(repeatAttribute)) {
// ngRepeat regexp extracted from angular 1.2.7 src
var exprMatch = repeatAttribute.value.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),
trackProperty = exprMatch[3];
repeatItem = exprMatch[1];
repeatCollection = exprMatch[2];
if (repeatItem) {
if (angular.isDefined(tAttributes['rnCarouselBuffered'])) {
// update the current ngRepeat expression and add a slice operator if buffered
isBuffered = true;
repeatAttribute.value = repeatItem + ' in ' + repeatCollection + '|carouselSlice:carouselBufferIndex:carouselBufferSize';
if (trackProperty) {
repeatAttribute.value += ' track by ' + trackProperty;
}
}
isRepeatBased = true;
return false;
}
}
return true;
});
return function(scope, iElement, iAttributes, containerCtrl) {
carouselId++;
var defaultOptions = {
transitionType: iAttributes.rnCarouselTransition || 'slide',
transitionEasing: iAttributes.rnCarouselEasing || 'easeTo',
transitionDuration: parseInt(iAttributes.rnCarouselDuration, 10) || 300,
isSequential: true,
autoSlideDuration: 3,
bufferSize: 5,
/* in container % how much we need to drag to trigger the slide change */
moveTreshold: 0.1,
defaultIndex: 0
};
// TODO
var options = angular.extend({}, defaultOptions);
var pressed,
startX,
isIndexBound = false,
offset = 0,
destination,
swipeMoved = false,
//animOnIndexChange = true,
currentSlides = [],
elWidth = null,
elX = null,
animateTransitions = true,
intialState = true,
animating = false,
mouseUpBound = false,
locked = false;
//rn-swipe-disabled =true will only disable swipe events
if(iAttributes.rnSwipeDisabled !== "true") {
$swipe.bind(iElement, {
start: swipeStart,
move: swipeMove,
end: swipeEnd,
cancel: function(event) {
swipeEnd({}, event);
}
});
}
function getSlidesDOM() {
return iElement[0].querySelectorAll('ul[rn-carousel] > li');
}
function documentMouseUpEvent(event) {
// in case we click outside the carousel, trigger a fake swipeEnd
swipeMoved = true;
swipeEnd({
x: event.clientX,
y: event.clientY
}, event);
}
function updateSlidesPosition(offset) {
// manually apply transformation to carousel childrens
// todo : optim : apply only to visible items
var x = scope.carouselBufferIndex * 100 + offset;
angular.forEach(getSlidesDOM(), function(child, index) {
child.style.cssText = createStyleString(computeCarouselSlideStyle(index, x, options.transitionType));
});
}
scope.nextSlide = function(slideOptions) {
var index = scope.carouselIndex + 1;
if (index > currentSlides.length - 1) {
index = 0;
}
if (!locked) {
goToSlide(index, slideOptions);
}
};
scope.prevSlide = function(slideOptions) {
var index = scope.carouselIndex - 1;
if (index < 0) {
index = currentSlides.length - 1;
}
goToSlide(index, slideOptions);
};
function goToSlide(index, slideOptions) {
//console.log('goToSlide', arguments);
// move a to the given slide index
$rootScope.$broadcast('slideChangeBegin', { 'slideIndex': arguments[0] });
if (index === undefined) {
index = scope.carouselIndex;
}
slideOptions = slideOptions || {};
if (slideOptions.animate === false || options.transitionType === 'none') {
locked = false;
offset = index * -100;
scope.carouselIndex = index;
updateBufferIndex();
return;
}
locked = true;
var tweenable = new Tweenable();
tweenable.tween({
from: {
'x': offset
},
to: {
'x': index * -100
},
duration: options.transitionDuration,
easing: options.transitionEasing,
step: function(state) {
updateSlidesPosition(state.x);
},
finish: function() {
scope.$apply(function() {
scope.carouselIndex = index;
offset = index * -100;
updateBufferIndex();
$rootScope.$broadcast('slideChangeEnd', { 'slideIndex': index });
$timeout(function () {
locked = false;
}, 0, false);
});
}
});
}
function getContainerWidth() {
var rect = iElement[0].getBoundingClientRect();
return rect.width ? rect.width : rect.right - rect.left;
}
function updateContainerWidth() {
elWidth = getContainerWidth();
}
function bindMouseUpEvent() {
if (!mouseUpBound) {
mouseUpBound = true;
$document.bind('mouseup', documentMouseUpEvent);
}
}
function unbindMouseUpEvent() {
if (mouseUpBound) {
mouseUpBound = false;
$document.unbind('mouseup', documentMouseUpEvent);
}
}
function swipeStart(coords, event) {
// console.log('swipeStart', coords, event);
if (locked || currentSlides.length <= 1) {
return;
}
updateContainerWidth();
elX = iElement[0].querySelector('li').getBoundingClientRect().left;
pressed = true;
startX = coords.x;
return false;
}
function swipeMove(coords, event) {
//console.log('swipeMove', coords, event);
var x, delta;
bindMouseUpEvent();
if (pressed) {
x = coords.x;
delta = startX - x;
if (delta > 2 || delta < -2) {
swipeMoved = true;
var moveOffset = offset + (-delta * 100 / elWidth);
updateSlidesPosition(moveOffset);
}
}
return false;
}
var init = true;
scope.carouselIndex = 0;
if (!isRepeatBased) {
// fake array when no ng-repeat
currentSlides = [];
angular.forEach(getSlidesDOM(), function(node, index) {
currentSlides.push({id: index});
});
}
if (iAttributes.rnCarouselControls!==undefined) {
// dont use a directive for this
var canloop = ((isRepeatBased ? scope[repeatCollection.replace('::', '')].length : currentSlides.length) > 1) ? angular.isDefined(tAttributes['rnCarouselControlsAllowLoop']) : false;
var nextSlideIndexCompareValue = isRepeatBased ? repeatCollection.replace('::', '') + '.length - 1' : currentSlides.length - 1;
var tpl = '<div class="rn-carousel-controls">\n' +
'<button class="rn-carousel-control rn-carousel-control-prev" ng-click="prevSlide()" ng-disabled="carouselIndex < 1 || ' + canloop + '"></button>\n' +
'<button class="rn-carousel-control rn-carousel-control-next" ng-click="nextSlide()" ng-disabled="carouselIndex >= ' + nextSlideIndexCompareValue + ' || ' + canloop + '"></button>\n' +
'</div>';
var controlsContainer = iElement.parent();
if (iAttributes.rnCarouselControlsContainerId!==undefined){
controlsContainer = angular.element(document.querySelector('#' + iAttributes.rnCarouselControlsContainerId));
}
controlsContainer.append($compile(angular.element(tpl))(scope));
}
if (iAttributes.rnCarouselAutoSlide!==undefined) {
var duration = parseInt(iAttributes.rnCarouselAutoSlide, 10) || options.autoSlideDuration;
scope.autoSlide = function() {
if (scope.autoSlider) {
$interval.cancel(scope.autoSlider);
scope.autoSlider = null;
}
scope.autoSlider = $interval(function() {
if (!locked && !pressed) {
scope.nextSlide();
}
}, duration * 1000);
};
}
if (iAttributes.rnCarouselDefaultIndex) {
var defaultIndexModel = $parse(iAttributes.rnCarouselDefaultIndex);
options.defaultIndex = defaultIndexModel(scope.$parent) || 0;
}
if (iAttributes.rnCarouselIndex) {
var updateParentIndex = function(value) {
indexModel.assign(scope.$parent, value);
};
var indexModel = $parse(iAttributes.rnCarouselIndex);
if (angular.isFunction(indexModel.assign)) {
/* check if this property is assignable then watch it */
scope.$watch('carouselIndex', function(newValue) {
updateParentIndex(newValue);
});
scope.$parent.$watch(indexModel, function(newValue, oldValue) {
if (newValue !== undefined && newValue !== null) {
if (currentSlides && currentSlides.length > 0 && newValue >= currentSlides.length) {
newValue = currentSlides.length - 1;
updateParentIndex(newValue);
} else if (currentSlides && newValue < 0) {
newValue = 0;
updateParentIndex(newValue);
}
if (!locked) {
goToSlide(newValue, {
animate: !init
});
}
init = false;
}
});
isIndexBound = true;
if (options.defaultIndex) {
goToSlide(options.defaultIndex, {
animate: !init
});
}
} else if (!isNaN(iAttributes.rnCarouselIndex)) {
/* if user just set an initial number, set it */
goToSlide(parseInt(iAttributes.rnCarouselIndex, 10), {
animate: false
});
}
} else {
goToSlide(options.defaultIndex, {
animate: !init
});
init = false;
}
if (iAttributes.rnCarouselLocked) {
scope.$watch(iAttributes.rnCarouselLocked, function(newValue, oldValue) {
// only bind swipe when it's not switched off
if(newValue === true) {
locked = true;
} else {
locked = false;
}
});
}
if (isRepeatBased) {
// use rn-carousel-deep-watch to fight the Angular $watchCollection weakness : https://github.com/angular/angular.js/issues/2621
// optional because it have some performance impacts (deep watch)
var deepWatch = (iAttributes.rnCarouselDeepWatch!==undefined);
scope[deepWatch?'$watch':'$watchCollection'](repeatCollection, function(newValue, oldValue) {
//console.log('repeatCollection', currentSlides);
currentSlides = newValue;
// if deepWatch ON ,manually compare objects to guess the new position
if (deepWatch && angular.isArray(newValue)) {
var activeElement = oldValue[scope.carouselIndex];
var newIndex = getItemIndex(newValue, activeElement, scope.carouselIndex);
goToSlide(newIndex, {animate: false});
} else {
goToSlide(scope.carouselIndex, {animate: false});
}
}, true);
}
function swipeEnd(coords, event, forceAnimation) {
// console.log('swipeEnd', 'scope.carouselIndex', scope.carouselIndex);
// Prevent clicks on buttons inside slider to trigger "swipeEnd" event on touchend/mouseup
// console.log(iAttributes.rnCarouselOnInfiniteScroll);
if (event && !swipeMoved) {
return;
}
unbindMouseUpEvent();
pressed = false;
swipeMoved = false;
destination = startX - coords.x;
if (destination===0) {
return;
}
if (locked) {
return;
}
offset += (-destination * 100 / elWidth);
if (options.isSequential) {
var minMove = options.moveTreshold * elWidth,
absMove = -destination,
slidesMove = -Math[absMove >= 0 ? 'ceil' : 'floor'](absMove / elWidth),
shouldMove = Math.abs(absMove) > minMove;
if (currentSlides && (slidesMove + scope.carouselIndex) >= currentSlides.length) {
slidesMove = currentSlides.length - 1 - scope.carouselIndex;
}
if ((slidesMove + scope.carouselIndex) < 0) {
slidesMove = -scope.carouselIndex;
}
var moveOffset = shouldMove ? slidesMove : 0;
destination = (scope.carouselIndex + moveOffset);
goToSlide(destination);
if(iAttributes.rnCarouselOnInfiniteScrollRight!==undefined && slidesMove === 0 && scope.carouselIndex !== 0) {
$parse(iAttributes.rnCarouselOnInfiniteScrollRight)(scope)
goToSlide(0);
}
if(iAttributes.rnCarouselOnInfiniteScrollLeft!==undefined && slidesMove === 0 && scope.carouselIndex === 0 && moveOffset === 0) {
$parse(iAttributes.rnCarouselOnInfiniteScrollLeft)(scope)
goToSlide(currentSlides.length);
}
} else {
scope.$apply(function() {
scope.carouselIndex = parseInt(-offset / 100, 10);
updateBufferIndex();
});
}
}
scope.$on('$destroy', function() {
unbindMouseUpEvent();
});
scope.carouselBufferIndex = 0;
scope.carouselBufferSize = options.bufferSize;
function updateBufferIndex() {
// update and cap te buffer index
var bufferIndex = 0;
var bufferEdgeSize = (scope.carouselBufferSize - 1) / 2;
if (isBuffered) {
if (scope.carouselIndex <= bufferEdgeSize) {
// first buffer part
bufferIndex = 0;
} else if (currentSlides && currentSlides.length < scope.carouselBufferSize) {
// smaller than buffer
bufferIndex = 0;
} else if (currentSlides && scope.carouselIndex > currentSlides.length - scope.carouselBufferSize) {
// last buffer part
bufferIndex = currentSlides.length - scope.carouselBufferSize;
} else {
// compute buffer start
bufferIndex = scope.carouselIndex - bufferEdgeSize;
}
scope.carouselBufferIndex = bufferIndex;
$timeout(function() {
updateSlidesPosition(offset);
}, 0, false);
} else {
$timeout(function() {
updateSlidesPosition(offset);
}, 0, false);
}
}
function onOrientationChange() {
updateContainerWidth();
// goToSlide(); << not sure why this was here
}
// handle orientation change
var winEl = angular.element($window);
winEl.bind('orientationchange', onOrientationChange);
winEl.bind('resize', onOrientationChange);
scope.$on('$destroy', function() {
unbindMouseUpEvent();
winEl.unbind('orientationchange', onOrientationChange);
winEl.unbind('resize', onOrientationChange);
});
};
}
};
}
]);
})();
|
version https://git-lfs.github.com/spec/v1
oid sha256:cd18d49d69c767a2b47648d5e1692ba4d74811f9f13d7d18f0f1b93d2a04dce7
size 28296
|
import { Field, Formik } from 'formik'
import React, { Component } from 'react'
import {
Button,
ButtonToolbar,
ControlLabel,
FormControl,
FormGroup,
HelpBlock,
Label,
ToggleButton,
ToggleButtonGroup
} from 'react-bootstrap'
import { FormattedMessage, injectIntl } from 'react-intl'
import { formatPhoneNumber, isPossiblePhoneNumber } from 'react-phone-number-input'
import Input from 'react-phone-number-input/input'
import styled, { css } from 'styled-components'
import * as yup from 'yup'
import SpanWithSpace from '../util/span-with-space'
import { getErrorStates, isBlank } from '../../util/ui'
const allowedNotificationChannels = ['email', 'sms', 'none']
// Styles
// HACK: Preserve container height.
const Details = styled.div`
min-height: 60px;
margin-bottom: 15px;
`
const ControlStrip = styled.div`
> * {
margin-right: 4px;
}
`
const phoneFieldCss = css`
display: inline-block;
vertical-align: middle;
width: 14em;
`
const InlineTextInput = styled(FormControl)`
${phoneFieldCss}
`
const InlineStatic = styled(FormControl.Static)`
${phoneFieldCss}
`
const InlinePhoneInput = styled(Input)`
${phoneFieldCss}
`
const FlushLink = styled(Button)`
padding-left: 0;
padding-right: 0;
`
const StyledToggleButton = styled(ToggleButton)`
&::first-letter {
text-transform: uppercase;
}
`
// Because we show the same message for the two validation conditions below,
// there is no need to pass that message here,
// that is done in the corresponding `<HelpBlock>` in PhoneNumberEditor.
const codeValidationSchema = yup.object({
validationCode: yup.string()
.required()
.matches(/^\d{6}$/) // 6-digit string
})
/**
* User notification preferences pane.
*/
const NotificationPrefsPane = ({
handleBlur, // Formik prop
handleChange, // Formik prop
loggedInUser,
onRequestPhoneVerificationCode,
onSendPhoneVerificationCode,
phoneFormatOptions,
values: userData // Formik prop
}) => {
const {
email,
isPhoneNumberVerified,
phoneNumber
} = loggedInUser
const {
notificationChannel
} = userData
const initialFormikValues = {
validationCode: ''
}
return (
<div>
<p>
<FormattedMessage id='components.NotificationPrefsPane.description' />
</p>
<FormGroup>
<ControlLabel>
<FormattedMessage id='components.NotificationPrefsPane.notificationChannelPrompt' />
</ControlLabel>
<ButtonToolbar>
<ToggleButtonGroup
defaultValue={notificationChannel}
name='notificationChannel'
type='radio'
>
{allowedNotificationChannels.map((type, index) => (
// TODO: If removing the Save/Cancel buttons on the account screen,
// persist changes immediately when onChange is triggered.
<StyledToggleButton
bsStyle={notificationChannel === type ? 'primary' : 'default'}
key={index}
// onBlur and onChange have to be set on individual controls instead of the control group
// in order for Formik to correctly process the changes.
onBlur={handleBlur}
onChange={handleChange}
value={type}
>
{type === 'email'
? <FormattedMessage id='common.notifications.email' />
: type === 'sms'
? <FormattedMessage id='common.notifications.sms' />
: <FormattedMessage id='components.NotificationPrefsPane.noneSelect' />
}
</StyledToggleButton>
))}
</ToggleButtonGroup>
</ButtonToolbar>
</FormGroup>
<Details>
{notificationChannel === 'email' && (
<FormGroup>
<ControlLabel>
<FormattedMessage id='components.NotificationPrefsPane.notificationEmailDetail' />
</ControlLabel>
<FormControl.Static>{email}</FormControl.Static>
</FormGroup>
)}
{notificationChannel === 'sms' && (
<Formik
initialValues={initialFormikValues}
validateOnChange
validationSchema={codeValidationSchema}
>
{
// Pass Formik props to the component rendered so Formik can manage its validation.
// (The validation for this component is independent of the validation set in UserAccountScreen.)
innerProps => {
return (
<PhoneNumberEditorWithIntl
{...innerProps}
initialPhoneNumber={phoneNumber}
initialPhoneNumberVerified={isPhoneNumberVerified}
onRequestCode={onRequestPhoneVerificationCode}
onSubmitCode={onSendPhoneVerificationCode}
phoneFormatOptions={phoneFormatOptions}
/>
)
}
}
</Formik>
)}
</Details>
</div>
)
}
export default NotificationPrefsPane
/**
* Sub-component that handles phone number and validation code editing and validation intricacies.
*/
class PhoneNumberEditor extends Component {
constructor (props) {
super(props)
const { initialPhoneNumber } = props
this.state = {
// If true, phone number is being edited.
// For new users, render component in editing state.
isEditing: isBlank(initialPhoneNumber),
// Holds the new phone number (+15555550123 format) entered by the user
// (outside of Formik because (Phone)Input does not have a standard onChange event or simple valitity test).
newPhoneNumber: ''
}
}
_handleEditNumber = () => {
this.setState({
isEditing: true,
newPhoneNumber: ''
})
}
_handleNewPhoneNumberChange = newPhoneNumber => {
this.setState({
newPhoneNumber
})
}
_handleCancelEditNumber = () => {
this.setState({
isEditing: false
})
}
_handlePhoneNumberKeyDown = e => {
if (e.keyCode === 13) {
// On the user pressing enter (keyCode 13) on the phone number field,
// prevent form submission and request the code.
e.preventDefault()
this._handleRequestCode()
}
}
_handleValidationCodeKeyDown = e => {
if (e.keyCode === 13) {
// On the user pressing enter (keyCode 13) on the validation code field,
// prevent form submission and send the validation code.
e.preventDefault()
this._handleSubmitCode()
}
}
/**
* Send phone verification request with the entered values.
*/
_handleRequestCode = () => {
const { initialPhoneNumber, initialPhoneNumberVerified, onRequestCode } = this.props
const { newPhoneNumber } = this.state
this._handleCancelEditNumber()
// Send the SMS request if one of these conditions apply:
// - the user entered a valid phone number different than their current verified number,
// - the user clicks 'Request new code' for an already pending number
// (they could have refreshed the page in between).
let submittedNumber
if (newPhoneNumber &&
isPossiblePhoneNumber(newPhoneNumber) &&
!(newPhoneNumber === initialPhoneNumber && initialPhoneNumberVerified)) {
submittedNumber = newPhoneNumber
} else if (this._isPhoneNumberPending()) {
submittedNumber = initialPhoneNumber
}
if (submittedNumber) {
onRequestCode(submittedNumber)
}
}
_handleSubmitCode = () => {
const { errors, onSubmitCode, values } = this.props
const { validationCode } = values
if (!errors.validationCode) {
onSubmitCode(validationCode)
}
}
_isPhoneNumberPending = () => {
const { initialPhoneNumber, initialPhoneNumberVerified } = this.props
return !isBlank(initialPhoneNumber) && !initialPhoneNumberVerified
}
componentDidUpdate (prevProps) {
// If new phone number and verified status are received,
// then reset/clear the inputs.
if (this.props.phoneNumber !== prevProps.phoneNumber ||
this.props.isPhoneNumberVerified !== prevProps.isPhoneNumberVerified
) {
this._handleCancelEditNumber()
this.props.resetForm()
}
}
render () {
const {
errors, // Formik prop
initialPhoneNumber,
intl,
phoneFormatOptions,
touched // Formik prop
} = this.props
const { isEditing, newPhoneNumber } = this.state
const isPending = this._isPhoneNumberPending()
// Here are the states we are dealing with:
// - First time entering a phone number/validation code (blank value, not modified)
// => no color, no feedback indication.
// - Typing backspace all the way to erase a number/code (blank value, modified)
// => red error.
// - Typing a phone number that doesn't match the configured phoneNumberRegEx
// => red error.
const isPhoneInvalid = !isPossiblePhoneNumber(newPhoneNumber)
const showPhoneError = isPhoneInvalid && !isBlank(newPhoneNumber)
const phoneErrorState = showPhoneError ? 'error' : null
const codeErrorState = getErrorStates(this.props).validationCode
return (
<>
{isEditing
? (
// FIXME: If removing the Save/Cancel buttons on the account screen,
// make this <FormGroup> a <form> and remove onKeyDown handler.
<FormGroup validationState={phoneErrorState}>
<ControlLabel>
<FormattedMessage id='components.PhoneNumberEditor.prompt' />
</ControlLabel>
<ControlStrip>
<InlinePhoneInput
className='form-control'
country={phoneFormatOptions.countryCode}
onChange={this._handleNewPhoneNumberChange}
onKeyDown={this._handlePhoneNumberKeyDown}
placeholder={intl.formatMessage({id: 'components.PhoneNumberEditor.placeholder'})}
type='tel'
value={newPhoneNumber}
/>
<Button
bsStyle='primary'
disabled={isPhoneInvalid}
onClick={this._handleRequestCode}
>
<FormattedMessage id='components.PhoneNumberEditor.sendVerificationText' />
</Button>
{ // Show cancel button only if a phone number is already recorded.
initialPhoneNumber && (
<Button onClick={this._handleCancelEditNumber}>
<FormattedMessage id='common.forms.cancel' />
</Button>
)}
{showPhoneError && (
<HelpBlock>
<FormattedMessage id='components.PhoneNumberEditor.invalidPhone' />
</HelpBlock>
)}
</ControlStrip>
</FormGroup>
) : (
<FormGroup>
<ControlLabel>
<FormattedMessage id='components.PhoneNumberEditor.smsDetail' />
</ControlLabel>
<ControlStrip>
<InlineStatic>
<SpanWithSpace margin={0.5}>{formatPhoneNumber(initialPhoneNumber)}</SpanWithSpace>
{isPending
? (
// eslint-disable-next-line jsx-a11y/label-has-for
<Label bsStyle='warning'>
<FormattedMessage id='components.PhoneNumberEditor.pending' />
</Label>
)
: (
// eslint-disable-next-line jsx-a11y/label-has-for
<Label bsStyle='success'>
<FormattedMessage id='components.PhoneNumberEditor.verified' />
</Label>
)
}
</InlineStatic>
<Button onClick={this._handleEditNumber}>
<FormattedMessage id='components.PhoneNumberEditor.changeNumber' />
</Button>
</ControlStrip>
</FormGroup>
)}
{isPending && !isEditing && (
// FIXME: If removing the Save/Cancel buttons on the account screen,
// make this <FormGroup> a <form> and remove onKeyDown handler.
<FormGroup validationState={codeErrorState}>
<p>
<FormattedMessage id='components.PhoneNumberEditor.verificationInstructions' />
</p>
<ControlLabel>
<FormattedMessage id='components.PhoneNumberEditor.verificationCode' />
</ControlLabel>
<ControlStrip>
<Field as={InlineTextInput}
maxLength={6}
name='validationCode'
onKeyDown={this._handleValidationCodeKeyDown}
placeholder='123456'
// HACK: <input type='tel'> triggers the numerical keypad on mobile devices, and otherwise
// behaves like <input type='text'> with support of leading zeros and the maxLength prop.
// <input type='number'> causes values to be stored as Number, resulting in
// leading zeros to be invalid and stripped upon submission.
type='tel'
// onBlur, onChange, and value are passed automatically by Formik
/>
<Button
bsStyle='primary'
disabled={!!errors.validationCode}
onClick={this._handleSubmitCode}
>
<FormattedMessage id='components.PhoneNumberEditor.verify' />
</Button>
{touched.validationCode && errors.validationCode && (
<HelpBlock>
<FormattedMessage id='components.PhoneNumberEditor.invalidCode' />
</HelpBlock>
)}
</ControlStrip>
<FlushLink bsStyle='link' onClick={this._handleRequestCode}>
<FormattedMessage id='components.PhoneNumberEditor.requestNewCode' />
</FlushLink>
</FormGroup>
)}
</>
)
}
}
const PhoneNumberEditorWithIntl = injectIntl(PhoneNumberEditor)
|
import Users from 'meteor/nova:users';
import { Utils } from 'meteor/nova:core';
Users.isSubscribedTo = (user, document) => {
if (!user || !document) {
// should return an error
return false;
}
const { __typename, _id: itemId } = document;
const documentType = Utils.capitalize(Utils.getCollectionNameFromTypename(__typename));
if (user.subscribedItems && user.subscribedItems[documentType]) {
return !!user.subscribedItems[documentType].find(subscribedItems => subscribedItems.itemId === itemId);
} else {
return false;
}
};
|
import Manage from '../components/Question/Manage';
const manageRoute = store => ({
path: 'manage',
component: Manage,
onEnter() {
const account_id = store.getState().auth.key
store.dispatch({
type: 'topic/list',
payload: {
params: {
offset: 1, limit: 9, account_id, state: 1
}
}
})
store.dispatch({
type: 'topic/info',
payload: {
params: { account_id, state:1 }
}
})
}
})
const questionRoutes = store => ({
path: 'question',
childRoutes: [manageRoute(store)]
})
export default questionRoutes |
/*eslint no-console:0 */
'use strict';
require('core-js/fn/object/assign');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const config = require('./webpack.config');
const open = require('open');
/**
* Flag indicating whether webpack compiled for the first time.
* @type {boolean}
*/
let isInitialCompilation = true;
const compiler = webpack(config);
new WebpackDevServer(compiler, config.devServer)
.listen(config.port, 'localhost', (err) => {
if (err) {
console.log(err);
}
console.log('Listening at localhost:' + config.port);
open('http://localhost:'+config.port);
});
compiler.plugin('done', () => {
if (isInitialCompilation) {
// Ensures that we log after webpack printed its stats (is there a better way?)
setTimeout(() => {
console.log('\n✓ The bundle is now ready for serving!\n');
console.log(' Open in iframe mode:\t\x1b[33m%s\x1b[0m', 'http://localhost:' + config.port + '/webpack-dev-server/');
console.log(' Open in inline mode:\t\x1b[33m%s\x1b[0m', 'http://localhost:' + config.port + '/\n');
console.log(' \x1b[33mHMR is active\x1b[0m. The bundle will automatically rebuild and live-update on changes.')
}, 350);
}
isInitialCompilation = false;
});
|
// load the things we need
var mongoose = require('mongoose');
// os: { name: 'Windows NT', version: '10.0', arch: 'x86_64' },
// project: { name: 'FastoNoSQL', version: '1.16.2.0', arch: 'x86_64', owner: '123', exec_count: 187 }
var AnonProjectSchema = mongoose.Schema({
name: String,
version: String,
arch: String
});
var OperationSystemSchema = require('./operation_system');
// define the schema for our programme model
var AnonymousStatisticSchema = mongoose.Schema({
created_date: {type: Date, default: Date.now},
os: OperationSystemSchema,
project: AnonProjectSchema
});
// create the model for statistics and expose it to our app
module.exports = mongoose.model('AnonymousStatistic', AnonymousStatisticSchema); |
var http = require('http');
var _ = require('lodash');
var moment = require('moment');
module.exports = function(app, nodesDb, params) {
// create todo and send back all todos after creation
app.get('/node/rgb', function(req, res) {
console.log("GET :: /energymeter actual data");
console.log(params.server_ip);
console.log(params.application_port.relay_station);
var options = {
host: "10.0.0.100",//params.server_ip,
port: params.application_port.relay_station,
path: '/energymeterdata/1'
};
http.get(options, function(request) {
var body = '';
request.on('data', function(chunk) {
body += chunk;
});
request.on('end', function() {
var result = JSON.parse(body);
result[0].pv_meter = -result[0].pv_meter;
// Dont show export yet
if (result[0].kwh_meter <= 0) {
result[0].kwh_meter = 0;
}
// Find the biggest value
//var biggest = getBiggest(result[0]);
//var divider = biggest / 255;
// console.log("Var 1 == " + result[0].kwh_meter);
// console.log("Var 2 == " + result[0].hh_meter);
// console.log("Var 3 == " + result[0].pv_meter);
// console.log("Big == " + biggest);
// console.log("Div == " + divider);
// console.log("Var 1 == " + parseInt(result[0].kwh_meter/divider));
// console.log("Var 2 == " + parseInt(result[0].hh_meter/divider));
// console.log("Var 3 == " + parseInt(result[0].pv_meter/divider));
return res.status(200).send(
{
r:parseInt(result[0].kwh_meter),
g:parseInt(result[0].hh_meter),
b:parseInt(result[0].pv_meter)
}
);
return res.status(200).send(JSON.parse(body));
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
return res.status(500).send('getting actual energymeterdata failed');
});
});
// create todo and send back all todos after creation
app.get('/energymeterdata/actual', function(req, res) {
console.log("GET :: /energymeter actual data");
console.log(params.server_ip);
console.log(params.application_port.relay_station);
var options = {
host: params.server_ip,
port: params.application_port.relay_station,
path: '/energymeterdata/1'
};
http.get(options, function(request) {
var body = '';
request.on('data', function(chunk) {
body += chunk;
});
request.on('end', function() {
return res.status(200).send(JSON.parse(body));
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
return res.status(500).send('getting actual energymeterdata failed');
});
});
// create todo and send back all todos after creation
app.get('/energymeterdata/:amount', function(req, res) {
console.log("GET :: Current meterdata");
var amount = 30;
if(req.params.amount !== undefined){
amount = req.params.amount;
}
nodesDb.getEnergyMeterValue(amount, function(result){
_.forEach(result, function(field) {
field.utc = moment.utc(field.timestamp).valueOf();
});
return res.status(200).send(result);
});
});
// create todo and send back all todos after creation
app.get('/energymeterdata/day/:day', function(req, res) {
console.log("GET :: Day meterdata");
var start = new Date();
nodesDb.getEnergyMeterValueDay(req.params.day, function(result){
// for(var index = 0; index < result.length; ++index) {
// result[index].utx = moment.utc(result[index].timestamp).valueOf();
// }
var before = new Date();
_.forEach(result, function(field) {
field.utc = moment.utc(field.timestamp).valueOf();
});
var end = new Date();
console.log('db call = ' + (before - start));
console.log('data = ' + (end - before));
console.log('total = ' + (end - start));
return res.status(200).send(result);
});
});
};
function getBiggest(result){
var biggest = 0;
if( result.kwh_meter > biggest) {
biggest = result.kwh_meter;
}
if( result.hh_meter > biggest) {
biggest = result.hh_meter;
}
if( result.pv_meter > biggest) {
biggest = result.pv_meter;
}
return biggest;
}
|
angular.module('app.states.index', [
'ui.router',
'app.states.login',
'app.states.search'
])
.config([
'$stateProvider',
'$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('index', {
abstract: true,
url: '',
views: {
header: {
templateUrl: '/states/index/header.html',
controller: 'indexCtrl'
}
}
});
$urlRouterProvider.otherwise('/login');
}]);
|
const errors = require("../errors");
const utils = require("../utils");
class AclLegacy {
constructor(consul) {
this.consul = consul;
}
/**
* Creates a new token with policy
*/
async create(opts) {
opts = utils.normalizeKeys(opts);
opts = utils.defaults(opts, this.consul._defaults);
const req = {
name: "acl.legacy.create",
path: "/acl/create",
query: {},
type: "json",
body: {},
};
if (opts.name) req.body.Name = opts.name;
if (opts.type) req.body.Type = opts.type;
if (opts.rules) req.body.Rules = opts.rules;
utils.options(req, opts);
return await this.consul._put(req, utils.body);
}
/**
* Update the policy of a token
*/
async update(opts) {
opts = utils.normalizeKeys(opts);
opts = utils.defaults(opts, this.consul._defaults);
const req = {
name: "acl.legacy.update",
path: "/acl/update",
query: {},
type: "json",
body: {},
};
if (!opts.id) {
throw this.consul._err(errors.Validation("id required"), req);
}
req.body.ID = opts.id;
if (opts.name) req.body.Name = opts.name;
if (opts.type) req.body.Type = opts.type;
if (opts.rules) req.body.Rules = opts.rules;
utils.options(req, opts);
return await this.consul._put(req, utils.empty);
}
/**
* Destroys a given token
*/
async destroy(opts) {
if (typeof opts === "string") {
opts = {id: opts};
}
opts = utils.normalizeKeys(opts);
opts = utils.defaults(opts, this.consul._defaults);
const req = {
name: "acl.legacy.destroy",
path: "/acl/destroy/{id}",
params: {id: opts.id},
query: {},
};
if (!opts.id) {
throw this.consul._err(errors.Validation("id required"), req);
}
utils.options(req, opts);
return await this.consul._put(req, utils.empty);
}
/**
* Queries the policy of a given token
*/
async info(opts) {
if (typeof opts === "string") {
opts = {id: opts};
}
opts = utils.normalizeKeys(opts);
opts = utils.defaults(opts, this.consul._defaults);
const req = {
name: "acl.legacy.info",
path: "/acl/info/{id}",
params: {id: opts.id},
query: {},
};
if (!opts.id) {
throw this.consul._err(errors.Validation("id required"), req);
}
utils.options(req, opts);
return await this.consul._get(req, utils.bodyItem);
}
get(...args) {
return this.info(...args);
}
/**
* Creates a new token by cloning an existing token
*/
async clone(opts) {
if (typeof opts === "string") {
opts = {id: opts};
}
opts = utils.normalizeKeys(opts);
opts = utils.defaults(opts, this.consul._defaults);
const req = {
name: "acl.legacy.clone",
path: "/acl/clone/{id}",
params: {id: opts.id},
query: {},
};
if (!opts.id) {
throw this.consul._err(errors.Validation("id required"), req);
}
utils.options(req, opts);
return await this.consul._put(req, utils.body);
}
/**
* Lists all the active tokens
*/
async list(opts) {
opts = utils.normalizeKeys(opts);
opts = utils.defaults(opts, this.consul._defaults);
const req = {
name: "acl.legacy.list",
path: "/acl/list",
query: {},
};
utils.options(req, opts);
return await this.consul._get(req, utils.body);
}
}
exports.AclLegacy = AclLegacy;
|
/**
* jTemplates 0.8.4 (http://jtemplates.tpython.com)
* Copyright (c) 2007-2013 Tomasz Gloc (http://www.tpython.com)
*
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and/or GPL (GPL-LICENSE.txt) licenses.
*
* Id: $Id: jquery-jtemplates_uncompressed.js 203 2013-02-03 13:28:34Z tom $
*/
/**
* @fileOverview Template engine in JavaScript.
* @name jTemplates
* @author Tomasz Gloc
* @date $Date: 2013-02-03 14:28:34 +0100 (N, 03 lut 2013) $
*/
if (window.jQuery && !window.jQuery.createTemplate) {(function (jQuery) {
/**
* [abstract]
* @name BaseNode
* @class Abstract node. [abstract]
*/
/**
* Process node and get the html string. [abstract]
* @name get
* @function
* @param {object} d data
* @param {object} param parameters
* @param {Element} element a HTML element
* @param {Number} deep
* @return {String}
* @memberOf BaseNode
*/
/**
* [abstract]
* @name BaseArray
* @augments BaseNode
* @class Abstract array/collection. [abstract]
*/
/**
* Add node 'e' to array.
* @name push
* @function
* @param {BaseNode} e a node
* @memberOf BaseArray
*/
/**
* See (http://jquery.com/).
* @name jQuery
* @class jQuery Library (http://jquery.com/)
*/
/**
* See (http://jquery.com/)
* @name fn
* @class jQuery Library (http://jquery.com/)
* @memberOf jQuery
*/
/**
* Create new template from string s.
* @name Template
* @class A template or multitemplate.
* @param {string} s A template string (like: "Text: {$T.txt}.").
* @param {array} [includes] Array of included templates.
* @param {object} [settings] Settings.
* @config {boolean} [disallow_functions] Do not allow use function in data (default: true).
* @config {boolean} [filter_data] Enable filter data using escapeHTML (default: true).
* @config {boolean} [filter_params] Enable filter parameters using escapeHTML (default: false).
* @config {boolean} [runnable_functions] Automatically run function (from data) inside {} [default: false].
* @config {boolean} [clone_data] Clone input data [default: true]
* @config {boolean} [clone_params] Clone input parameters [default: true]
* @config {Function} [f_cloneData] Function used to data cloning
* @config {Function} [f_escapeString] Function used to escape strings
* @config {Function} [f_parseJSON] Function used to parse JSON
* @augments BaseNode
*/
var Template = function (s, includes, settings) {
this._tree = [];
this._param = {};
this._includes = null;
this._templates = {};
this._templates_code = {};
//default parameters
this.settings = jQuery.extend({
disallow_functions: false,
filter_data: true,
filter_params: false,
runnable_functions: false,
clone_data: true,
clone_params: true
}, settings);
//set handlers
this.f_cloneData = (this.settings.f_cloneData !== undefined) ? (this.settings.f_cloneData) : (TemplateUtils.cloneData);
this.f_escapeString = (this.settings.f_escapeString !== undefined) ? (this.settings.f_escapeString) : (TemplateUtils.escapeHTML);
this.f_parseJSON = (this.settings.f_parseJSON !== undefined) ? (this.settings.f_parseJSON) : ((this.settings.disallow_functions) ? (jQuery.parseJSON) : (TemplateUtils.parseJSON));
if(s == null) {
return;
}
//split multiteplate
this.splitTemplates(s, includes);
if(s) {
//set main template
this.setTemplate(this._templates_code['MAIN'], includes, this.settings);
}
this._templates_code = null;
};
/**
* jTemplates version
* @type string
*/
Template.version = '0.8.4';
/**
* Debug mode (all errors are on), default: off
* @type Boolean
*/
Template.DEBUG_MODE = false;
/**
* Foreach loop limit (enable only when DEBUG_MODE = true)
* @type integer
*/
Template.FOREACH_LOOP_LIMIT = 10000;
/**
* Global guid
* @type integer
*/
Template.guid = 0;
/**
* Split multitemplate into multiple templates.
* @param {string} s A template string (like: "Text: {$T.txt}.").
* @param {array} includes Array of included templates.
*/
Template.prototype.splitTemplates = function (s, includes) {
var reg = /\{#template *(\w+) *(.*?) *\}/g, //split multitemplate into subtemplates
iter, tname, se, lastIndex = null, _template_settings = [], i;
//while find new subtemplate
while((iter = reg.exec(s)) !== null) {
lastIndex = reg.lastIndex;
tname = iter[1];
se = s.indexOf('{#/template ' + tname + '}', lastIndex);
if(se === -1) {
throw new Error('jTemplates: Template "' + tname + '" is not closed.');
}
//save a subtemplate and parse options
this._templates_code[tname] = s.substring(lastIndex, se);
_template_settings[tname] = TemplateUtils.optionToObject(iter[2]);
}
//when no subtemplates, use all as main template
if(lastIndex === null) {
this._templates_code['MAIN'] = s;
return;
}
//create a new object for every subtemplates
for(i in this._templates_code) {
if(i !== 'MAIN') {
this._templates[i] = new Template();
}
}
for(i in this._templates_code) {
if(i !== 'MAIN') {
this._templates[i].setTemplate(this._templates_code[i],
jQuery.extend({}, includes || {}, this._templates || {}),
jQuery.extend({}, this.settings, _template_settings[i]));
this._templates_code[i] = null;
}
}
};
/**
* Parse template. (should be template, not multitemplate).
* @param {string} s A template string (like: "Text: {$T.txt}.").
* @param {array} includes Array of included templates.
* @param {object} [settings] Settings.
*/
Template.prototype.setTemplate = function (s, includes, settings) {
if(s == undefined) {
this._tree.push(new TextNode('', 1, this));
return;
}
s = s.replace(/[\n\r]/g, ''); //remove endlines
s = s.replace(/\{\*.*?\*\}/g, ''); //remove comments
this._includes = jQuery.extend({}, this._templates || {}, includes || {});
this.settings = new Object(settings);
var node = this._tree,
op = s.match(/\{#.*?\}/g), //find operators
ss = 0, se = 0, e, literalMode = 0, i, l;
//loop operators
for(i=0, l=(op)?(op.length):(0); i<l; ++i) {
var this_op = op[i];
//when literal mode is on, treat operator like a text
if(literalMode) {
se = s.indexOf('{#/literal}', ss); //find end of block
if(se === -1) {
throw new Error("jTemplates: No end of literal.");
}
if(se > ss) {
node.push(new TextNode(s.substring(ss, se), 1, this));
}
ss = se + 11; //strlen '{#/literal}'
literalMode = 0;
while(i < l && op[i] !== '{#/literal}') { //skip all operators until literal end
i++;
}
continue;
}
se = s.indexOf(this_op, ss);
if(se > ss) {
node.push(new TextNode(s.substring(ss, se), literalMode, this));
}
this_op.match(/\{#([\w\/]+).*?\}/); //find operator name
var op_ = RegExp.$1;
switch(op_) {
case 'elseif':
node.addCond(this_op);
break;
case 'if':
e = new opIF(node, this);
e.addCond(this_op);
node.push(e);
node = e;
break;
case 'else':
node.switchToElse();
break;
case '/if':
case '/for':
case '/foreach':
node = node.getParent();
break;
case 'foreach':
e = new opFOREACH(this_op, node, this);
node.push(e);
node = e;
break;
case 'for':
e = opFORFactory(this_op, node, this);
node.push(e);
node = e;
break;
case 'continue':
case 'break':
node.push(new JTException(op_));
break;
case 'include':
node.push(new Include(this_op, this._includes, this));
break;
case 'param':
node.push(new UserParam(this_op, this));
break;
case 'var':
node.push(new UserVariable(this_op, this));
break;
case 'cycle':
node.push(new Cycle(this_op));
break;
case 'ldelim':
node.push(new TextNode('{', 1, this));
break;
case 'rdelim':
node.push(new TextNode('}', 1, this));
break;
case 'literal':
literalMode = 1;
break;
case '/literal':
if(Template.DEBUG_MODE) {
throw new Error("jTemplates: Missing begin of literal.");
}
break;
default:
if(Template.DEBUG_MODE) {
throw new Error('jTemplates: unknown tag: ' + op_ + '.');
}
}
ss = se + this_op.length;
}
if(s.length > ss) {
node.push(new TextNode(s.substr(ss), literalMode, this));
}
};
/**
* Process template and get the html string.
* @param {object} d data
* @param {object} param parameters
* @param {Element} element a HTML element
* @param {Number} deep
* @return {String}
*/
Template.prototype.get = function (d, param, element, deep) {
++deep;
if (deep == 1 && element != undefined) {
jQuery.removeData(element, "jTemplatesRef");
}
var $T = d, $P, ret = '';
//create clone of data
if(this.settings.clone_data) {
$T = this.f_cloneData(d, {escapeData: (this.settings.filter_data && deep == 1), noFunc: this.settings.disallow_functions}, this.f_escapeString);
}
//create clone of parameters
if(!this.settings.clone_params) {
$P = jQuery.extend({}, this._param, param);
} else {
$P = jQuery.extend({},
this.f_cloneData(this._param, {escapeData: (this.settings.filter_params), noFunc: false}, this.f_escapeString),
this.f_cloneData(param, {escapeData: (this.settings.filter_params && deep == 1), noFunc: false}, this.f_escapeString));
}
for(var i=0, l=this._tree.length; i<l; ++i) {
ret += this._tree[i].get($T, $P, element, deep);
}
this.EvalObj = null;
--deep;
return ret;
};
/**
* Create and return EvalClass object
* @return {EvalClass}
*/
Template.prototype.getBin = function () {
if(this.EvalObj == null) {
this.EvalObj = new EvalClass(this);
}
return this.EvalObj;
};
/**
* Set to parameter 'name' value 'value'.
* @param {string} name
* @param {object} value
*/
Template.prototype.setParam = function (name, value) {
this._param[name] = value;
};
/**
* Template utilities.
* @namespace Template utilities.
*/
TemplateUtils = function () {
};
/**
* Replace chars &, >, <, ", ' with html entities.
* To disable function set settings: filter_data=false, filter_params=false
* @param {string} string
* @return {string}
* @static
* @memberOf TemplateUtils
*/
TemplateUtils.escapeHTML = function (txt) {
return txt.replace(/&/g,'&').replace(/>/g,'>').replace(/</g,'<').replace(/"/g,'"').replace(/'/g,''');
};
/**
* Make a copy od data 'd'. It also filters data (depend on 'filter').
* @param {object} d input data
* @param {object} filter a filters
* @config {boolean} [escapeData] Use escapeHTML on every string.
* @config {boolean} [noFunc] Do not allow to use function (throws exception).
* @param {Function} f_escapeString function using to filter string (usually: TemplateUtils.escapeHTML)
* @return {object} output data (filtered)
* @static
* @memberOf TemplateUtils
*/
TemplateUtils.cloneData = function (d, filter, f_escapeString) {
if(d == null) {
return d;
}
switch(d.constructor) {
case Object:
var o = {};
for(var i in d) {
o[i] = TemplateUtils.cloneData(d[i], filter, f_escapeString);
}
if(!filter.noFunc) {
if(d.hasOwnProperty("toString")) {
o.toString = d.toString;
}
}
return o;
case Array:
var a = [];
for(var i=0,l=d.length; i<l; ++i) {
a[i] = TemplateUtils.cloneData(d[i], filter, f_escapeString);
}
return a;
case String:
return (filter.escapeData) ? (f_escapeString(d)) : (d);
case Function:
if(filter.noFunc) {
if(Template.DEBUG_MODE) {
throw new Error("jTemplates: Functions are not allowed.");
}
else {
return undefined;
}
}
}
return d;
};
/**
* Convert text-based option string to Object
* @param {string} optionText text-based option string
* @return {Object}
* @static
* @memberOf TemplateUtils
*/
TemplateUtils.optionToObject = function (optionText) {
if(optionText === null || optionText === undefined) {
return {};
}
var o = optionText.split(/[= ]/);
if(o[0] === '') {
o.shift();
}
var obj = {};
for(var i=0, l=o.length; i<l; i+=2) {
obj[o[i]] = o[i+1];
}
return obj;
};
/**
* Parse JSON string into object
* @param {string} data Text JSON
* @return {Object}
* @static
*/
TemplateUtils.parseJSON = function (data) {
if ( typeof data !== "string" || !data ) {
return null;
}
try {
return (new Function("return " + jQuery.trim(data)))();
} catch(e) {
if(Template.DEBUG_MODE) {
throw new Error("jTemplates: Invalid JSON");
}
return {};
}
};
/**
* Find parents nodes for a reference value and return it
* @param {Element} el html element
* @param {int} guid template process unique identificator
* @param {int} id index
* @return {object}
* @static
*/
TemplateUtils.ReturnRefValue = function (el, guid, id) {
//search element with stored data
while(el != null) {
var d = jQuery.data(el, 'jTemplatesRef');
if(d != undefined && d.guid == guid && d.d[id] != undefined) {
return d.d[id];
}
el = el.parentNode;
}
return null;
};
/**
* Create a new text node.
* @name TextNode
* @class All text (block {..}) between control's block "{#..}".
* @param {string} val text string
* @param {boolean} literalMode When enable (true) template does not process blocks {..}.
* @param {Template} Template object
* @augments BaseNode
*/
var TextNode = function (val, literalMode, template) {
this._value = val;
this._literalMode = literalMode;
this._template = template;
};
/**
* Get the html string for a text node.
* @param {object} d data
* @param {object} param parameters
* @param {Element} element a HTML element
* @param {Number} deep
* @return {String}
*/
TextNode.prototype.get = function (d, param, element, deep) {
if(this._literalMode) {
return this._value;
}
var s = this._value;
var result = "";
var i = -1;
var nested = 0;
var sText = -1;
var sExpr = 0;
while(true) {
var lm = s.indexOf("{", i+1);
var rm = s.indexOf("}", i+1);
if(lm < 0 && rm < 0) {
break;
}
if((lm != -1 && lm < rm) || (rm == -1)) {
i = lm;
if(++nested == 1) {
sText = lm;
result += s.substring(sExpr, i);
sExpr = -1;
}
} else {
i = rm;
if(--nested === 0) {
if(sText >= 0) {
result += this._template.getBin().evaluateContent(d, param, element, s.substring(sText, rm+1));
sText = -1;
sExpr = i+1;
}
} else if(nested < 0) {
nested = 0;
}
}
}
if(sExpr > -1) {
result += s.substr(sExpr);
}
return result;
};
/**
* Virtual context for eval() (internal class)
* @name EvalClass
* @class Virtual bin for eval() evaluation
* @param {Template} t template
* @private
*/
EvalClass = function (t) {
this.__templ = t;
};
/**
* Evaluate expression (template content)
* @param {object} $T data
* @param {object} $P parameters
* @param {object} $Q element
* @param {String} __value Template content
* @return {String}
*/
EvalClass.prototype.evaluateContent = function ($T, $P, $Q, __value) {
try {
var result = eval(__value);
if(jQuery.isFunction(result)) {
if(this.__templ.settings.disallow_functions || !this.__templ.settings.runnable_functions) {
return '';
}
result = result($T, $P, $Q);
}
return (result === undefined) ? ("") : (String(result));
} catch(e) {
if(Template.DEBUG_MODE) {
if(e instanceof JTException) {
e.type = "subtemplate";
}
throw e;
}
return "";
}
};
/**
* Evaluate expression (simple eval)
* @param {object} $T data
* @param {object} $P parameters
* @param {object} $Q element
* @param {String} __value content to evaluate
* @return {String}
*/
EvalClass.prototype.evaluate = function ($T, $P, $Q, __value) {
return eval(__value);
};
/**
* Create a new conditional node.
* @name opIF
* @class A class represent: {#if}.
* @param {object} par parent node
* @param {Template} templ template
* @augments BaseArray
*/
var opIF = function (par, templ) {
this._parent = par;
this._templ = templ;
this._cond = []; //conditions
this._tree = []; //conditions subtree
this._curr = null; //current subtree
};
/**
* Add node 'e' to array.
* @param {BaseNode} e a node
*/
opIF.prototype.push = function (e) {
this._curr.push(e);
};
/**
* Get a parent node.
* @return {BaseNode}
*/
opIF.prototype.getParent = function () {
return this._parent;
};
/**
* Add condition
* @param {string} oper content of operator {#..}
*/
opIF.prototype.addCond = function (oper) {
oper.match(/\{#(?:else)*if (.*?)\}/);
this._cond.push(RegExp.$1);
this._curr = [];
this._tree.push(this._curr);
};
/**
* Switch to else
*/
opIF.prototype.switchToElse = function () {
this._cond.push(true); //else is the last condition and its always true
this._curr = [];
this._tree.push(this._curr);
};
/**
* Process node depend on conditional and get the html string.
* @param {object} d data
* @param {object} param parameters
* @param {Element} element a HTML element
* @param {Number} deep
* @return {String}
*/
opIF.prototype.get = function (d, param, element, deep) {
var ret = ''; //result
try {
//foreach condition
for(var ci=0, cl=this._cond.length; ci<cl; ++ci) {
//if condition is true
if(this._templ.getBin().evaluate(d, param, element, this._cond[ci])) {
//execute and exit
var t = this._tree[ci];
for(var i=0, l=t.length; i<l; ++i) {
ret += t[i].get(d, param, element, deep);
}
return ret;
}
}
} catch(e) {
if(Template.DEBUG_MODE || (e instanceof JTException)) {
throw e;
}
}
return ret;
};
/**
* Handler for a tag 'FOR'. Create new and return relative opFOREACH object.
* @name opFORFactory
* @class Handler for a tag 'FOR'. Create new and return relative opFOREACH object.
* @param {string} oper content of operator {#..}
* @param {object} par parent node
* @param {Template} template a pointer to Template object
* @return {opFOREACH}
*/
opFORFactory = function (oper, par, template) {
//create operator FOREACH with function as iterator
if(oper.match(/\{#for (\w+?) *= *(\S+?) +to +(\S+?) *(?:step=(\S+?))*\}/)) {
var f = new opFOREACH(null, par, template);
f._name = RegExp.$1;
f._option = {'begin': (RegExp.$2 || 0), 'end': (RegExp.$3 || -1), 'step': (RegExp.$4 || 1), 'extData': '$T'};
f._runFunc = (function (i){return i;});
return f;
} else {
throw new Error('jTemplates: Operator failed "find": ' + oper);
}
};
/**
* Create a new loop node.
* @name opFOREACH
* @class A class represent: {#foreach}.
* @param {string} oper content of operator {#..}
* @param {object} par parent node
* @param {Template} template a pointer to Template object
* @augments BaseArray
*/
var opFOREACH = function (oper, par, template) {
this._parent = par;
this._template = template;
if(oper != null) {
oper.match(/\{#foreach +(.+?) +as +(\w+?)( .+)*\}/);
this._arg = RegExp.$1;
this._name = RegExp.$2;
this._option = RegExp.$3 || null;
this._option = TemplateUtils.optionToObject(this._option);
}
this._onTrue = [];
this._onFalse = [];
this._currentState = this._onTrue;
//this._runFunc = null;
};
/**
* Add node 'e' to array.
* @param {BaseNode} e
*/
opFOREACH.prototype.push = function (e) {
this._currentState.push(e);
};
/**
* Get a parent node.
* @return {BaseNode}
*/
opFOREACH.prototype.getParent = function () {
return this._parent;
};
/**
* Switch from collection onTrue to onFalse.
*/
opFOREACH.prototype.switchToElse = function () {
this._currentState = this._onFalse;
};
/**
* Process loop and get the html string.
* @param {object} d data
* @param {object} param parameters
* @param {Element} element a HTML element
* @param {Number} deep
* @return {String}
*/
opFOREACH.prototype.get = function (d, param, element, deep) {
try {
//array of elements in foreach (or function)
var fcount = (this._runFunc === undefined) ? (this._template.getBin().evaluate(d, param, element, this._arg)) : (this._runFunc);
if(fcount === $) {
throw new Error("jTemplate: Variable '$' cannot be used as loop-function");
}
var key = []; //only for objects
var mode = typeof fcount;
if(mode == 'object') {
//transform object to array
var arr = [];
jQuery.each(fcount, function (k, v) {
key.push(k);
arr.push(v);
});
fcount = arr;
}
//setup primary iterator, iterator can get data from options (using by operator FOR) or from data "$T"
var extData = (this._option.extData !== undefined) ? (this._template.getBin().evaluate(d, param, element, this._option.extData)) : ((d != null) ? (d) : ({}));
if(extData == null) {
extData = {};
}
//start, end and step
var s = Number(this._template.getBin().evaluate(d, param, element, this._option.begin) || 0), e; //start, end
var step = Number(this._template.getBin().evaluate(d, param, element, this._option.step) || 1);
if(mode != 'function') {
e = fcount.length;
} else {
if(this._option.end === undefined || this._option.end === null) {
e = Number.MAX_VALUE;
} else {
e = Number(this._template.getBin().evaluate(d, param, element, this._option.end)) + ((step>0) ? (1) : (-1));
}
}
var ret = ''; //result string
var i,l; //local iterators
if(this._option.count) {
//limit number of loops
var tmp = s + Number(this._template.getBin().evaluate(d, param, element, this._option.count));
e = (tmp > e) ? (e) : (tmp);
}
if((e>s && step>0) || (e<s && step<0)) {
var iteration = 0;
var _total = (mode != 'function') ? (Math.ceil((e-s)/step)) : undefined;
var ckey, cval; //current key, current value
var loopCounter = 0;
for(; ((step>0) ? (s<e) : (s>e)); s+=step, ++iteration, ++loopCounter) {
if(Template.DEBUG_MODE && loopCounter > Template.FOREACH_LOOP_LIMIT) {
throw new Error("jTemplate: Foreach loop limit was exceed");
}
ckey = key[s];
if(mode != 'function') {
cval = fcount[s]; //get value from array
} else {
cval = fcount(s); //calc function
//if no result from function then stop foreach
if(cval === undefined || cval === null) {
break;
}
}
if((typeof cval == 'function') && (this._template.settings.disallow_functions || !this._template.settings.runnable_functions)) {
continue;
}
if((mode == 'object') && (ckey in Object) && (cval === Object[ckey])) {
continue;
}
//backup on value
var prevValue = extData[this._name];
//set iterator properties
extData[this._name] = cval;
extData[this._name + '$index'] = s;
extData[this._name + '$iteration'] = iteration;
extData[this._name + '$first'] = (iteration === 0);
extData[this._name + '$last'] = (s+step >= e);
extData[this._name + '$total'] = _total;
extData[this._name + '$key'] = (ckey !== undefined && ckey.constructor == String) ? (this._template.f_escapeString(ckey)) : (ckey);
extData[this._name + '$typeof'] = typeof cval;
for(i=0, l=this._onTrue.length; i<l; ++i) {
try {
ret += this._onTrue[i].get(extData, param, element, deep);
} catch(ex) {
if(ex instanceof JTException) {
switch(ex.type) {
case 'continue':
i = l; //force skip to next node
break;
case 'break':
i = l; //force skip to next node
s = e; //force skip outsite foreach
break;
default:
throw ex;
}
} else {
throw ex;
}
}
}
//restore values
delete extData[this._name + '$index'];
delete extData[this._name + '$iteration'];
delete extData[this._name + '$first'];
delete extData[this._name + '$last'];
delete extData[this._name + '$total'];
delete extData[this._name + '$key'];
delete extData[this._name + '$typeof'];
delete extData[this._name];
extData[this._name] = prevValue;
}
} else {
//no items to loop ("foreach->else")
for(i=0, l=this._onFalse.length; i<l; ++i) {
ret += this._onFalse[i].get(d, param, element, deep);
}
}
return ret;
} catch(e) {
if(Template.DEBUG_MODE || (e instanceof JTException)) {
throw e;
}
return "";
}
};
/**
* Template-control exceptions
* @name JTException
* @class A class used internals for a template-control exceptions
* @param type {string} Type of exception
* @augments Error
* @augments BaseNode
*/
var JTException = function (type) {
this.type = type;
};
JTException.prototype = Error;
/**
* Throw a template-control exception
* @throws It throws itself
*/
JTException.prototype.get = function (d) {
throw this;
};
/**
* Create a new entry for included template.
* @name Include
* @class A class represent: {#include}.
* @param {string} oper content of operator {#..}
* @param {array} includes
* @param {Template} templ template
* @augments BaseNode
*/
var Include = function (oper, includes, templ) {
oper.match(/\{#include (.*?)(?: root=(.*?))?\}/);
this._template = includes[RegExp.$1];
if(this._template == undefined) {
if(Template.DEBUG_MODE) {
throw new Error('jTemplates: Cannot find include: ' + RegExp.$1);
}
}
this._root = RegExp.$2;
this._mainTempl = templ;
};
/**
* Run method get on included template.
* @param {object} d data
* @param {object} param parameters
* @param {Element} element a HTML element
* @param {Number} deep
* @return {String}
*/
Include.prototype.get = function (d, param, element, deep) {
try {
//run a subtemplates with a new root node
return this._template.get(this._mainTempl.getBin().evaluate(d, param, element, this._root), param, element, deep);
} catch(e) {
if(Template.DEBUG_MODE || (e instanceof JTException)) {
throw e;
}
}
return '';
};
/**
* Create new node for {#param}.
* @name UserParam
* @class A class represent: {#param}.
* @param {string} oper content of operator {#..}
* @param {Template} templ template
* @augments BaseNode
*/
var UserParam = function (oper, templ) {
oper.match(/\{#param name=(\w*?) value=(.*?)\}/);
this._name = RegExp.$1;
this._value = RegExp.$2;
this._templ = templ;
};
/**
* Return value of selected parameter.
* @param {object} d data
* @param {object} param parameters
* @param {Element} element a HTML element
* @param {Number} deep
* @return {String} empty string
*/
UserParam.prototype.get = function (d, param, element, deep) {
try {
param[this._name] = this._templ.getBin().evaluate(d, param, element, this._value);
} catch(e) {
if(Template.DEBUG_MODE || (e instanceof JTException)) {
throw e;
}
param[this._name] = undefined;
}
return '';
};
/**
* Create new node for {#var}.
* @name UserVariable
* @class A class represent: {#var}.
* @param {string} oper content of operator {#..}
* @param {Template} templ template
* @augments BaseNode
*/
var UserVariable = function (oper, templ) {
oper.match(/\{#var (.*?)\}/);
this._id = RegExp.$1;
this._templ = templ;
};
/**
* Return value of selected variable.
* @param {object} d data
* @param {object} param parameters
* @param {Element} element a HTML element
* @param {Number} deep
* @return {String} calling of function ReturnRefValue (as text string)
*/
UserVariable.prototype.get = function (d, param, element, deep) {
try {
if(element == undefined) {
return "";
}
var obj = this._templ.getBin().evaluate(d, param, element, this._id);
var refobj = jQuery.data(element, "jTemplatesRef");
if(refobj == undefined) {
refobj = {guid:(++Template.guid), d:[]};
}
var i = refobj.d.push(obj);
jQuery.data(element, "jTemplatesRef", refobj);
return "(TemplateUtils.ReturnRefValue(this," + refobj.guid + "," + (i-1) + "))";
} catch(e) {
if(Template.DEBUG_MODE || (e instanceof JTException)) {
throw e;
}
return '';
}
};
/**
* Create a new cycle node.
* @name Cycle
* @class A class represent: {#cycle}.
* @param {string} oper content of operator {#..}
* @augments BaseNode
*/
var Cycle = function (oper) {
oper.match(/\{#cycle values=(.*?)\}/);
this._values = eval(RegExp.$1);
this._length = this._values.length;
if(this._length <= 0) {
throw new Error('jTemplates: no elements for cycle');
}
this._index = 0;
this._lastSessionID = -1;
};
/**
* Do a step on cycle and return value.
* @param {object} d data
* @param {object} param parameters
* @param {Element} element a HTML element
* @param {Number} deep
* @return {String}
*/
Cycle.prototype.get = function (d, param, element, deep) {
var sid = jQuery.data(element, 'jTemplateSID');
if(sid != this._lastSessionID) {
this._lastSessionID = sid;
this._index = 0;
}
var i = this._index++ % this._length;
return this._values[i];
};
/**
* Add a Template to HTML Elements.
* @param {Template/string} s a Template or a template string
* @param {array} [includes] Array of included templates.
* @param {object} [settings] Settings (see Template)
* @return {jQuery} chainable jQuery class
* @memberOf jQuery.fn
*/
jQuery.fn.setTemplate = function (s, includes, settings) {
return jQuery(this).each(function () {
var t = (s && s.constructor == Template) ? s : new Template(s, includes, settings);
jQuery.data(this, 'jTemplate', t);
jQuery.data(this, 'jTemplateSID', 0);
});
};
/**
* Add a Template (from URL) to HTML Elements.
* @param {string} url_ URL to template
* @param {array} [includes] Array of included templates.
* @param {object} [settings] Settings (see Template)
* @return {jQuery} chainable jQuery class
* @memberOf jQuery.fn
*/
jQuery.fn.setTemplateURL = function (url_, includes, settings) {
var s = jQuery.ajax({
url: url_,
dataType: 'text',
async: false,
type: 'GET'
}).responseText;
return jQuery(this).setTemplate(s, includes, settings);
};
/**
* Create a Template from element's content.
* @param {string} elementName an ID of element
* @param {array} [includes] Array of included templates.
* @param {object} [settings] Settings (see Template)
* @return {jQuery} chainable jQuery class
* @memberOf jQuery.fn
*/
jQuery.fn.setTemplateElement = function (elementName, includes, settings) {
var s = jQuery('#' + elementName).val();
if(s == null) {
s = jQuery('#' + elementName).html();
s = s.replace(/</g, "<").replace(/>/g, ">");
}
s = jQuery.trim(s);
s = s.replace(/^<\!\[CDATA\[([\s\S]*)\]\]>$/im, '$1');
s = s.replace(/^<\!--([\s\S]*)-->$/im, '$1');
return jQuery(this).setTemplate(s, includes, settings);
};
/**
* Check it HTML Elements have a template. Return count of templates.
* @return {number} Number of templates.
* @memberOf jQuery.fn
*/
jQuery.fn.hasTemplate = function () {
var count = 0;
jQuery(this).each(function () {
if(jQuery.getTemplate(this)) {
++count;
}
});
return count;
};
/**
* Remote Template from HTML Element(s)
* @return {jQuery} chainable jQuery class
*/
jQuery.fn.removeTemplate = function () {
jQuery(this).processTemplateStop();
return jQuery(this).each(function () {
jQuery.removeData(this, 'jTemplate');
});
};
/**
* Set to parameter 'name' value 'value'.
* @param {string} name
* @param {object} value
* @return {jQuery} chainable jQuery class
* @memberOf jQuery.fn
*/
jQuery.fn.setParam = function (name, value) {
return jQuery(this).each(function () {
var t = jQuery.getTemplate(this);
if(t != null) {
t.setParam(name, value);
} else if(Template.DEBUG_MODE) {
throw new Error('jTemplates: Template is not defined.');
}
});
};
/**
* Process template using data 'd' and parameters 'param'. Update HTML code.
* @param {object} d data
* @param {object} [param] parameters
* @option {object} [options] internal use only
* @return {jQuery} chainable jQuery class
* @memberOf jQuery.fn
*/
jQuery.fn.processTemplate = function (d, param, options) {
return jQuery(this).each(function () {
var t = jQuery.getTemplate(this);
if(t != null) {
if(options != undefined && options.StrToJSON) {
d = t.f_parseJSON(d);
}
jQuery.data(this, 'jTemplateSID', jQuery.data(this, 'jTemplateSID') + 1);
jQuery(this).html(t.get(d, param, this, 0));
} else if(Template.DEBUG_MODE) {
throw new Error('jTemplates: Template is not defined.');
}
});
};
/**
* Process template using data from URL 'url_' (only format JSON) and parameters 'param'. Update HTML code.
* @param {string} url_ URL to data (in JSON)
* @param {object} [param] parameters
* @param {object} options options (over ajaxSettings) and callbacks
* @return {jQuery} chainable jQuery class
* @memberOf jQuery.fn
*/
jQuery.fn.processTemplateURL = function (url_, param, options) {
var that = this;
var o = jQuery.extend({cache: false}, jQuery.ajaxSettings);
o = jQuery.extend(o, options);
jQuery.ajax({
url: url_,
type: o.type,
data: o.data,
dataFilter: o.dataFilter,
async: o.async,
headers: o.headers,
cache: o.cache,
timeout: o.timeout,
dataType: 'text',
success: function (d) {
var r = jQuery(that).processTemplate(d, param, {StrToJSON:true});
if(o.on_success) {
o.on_success(r);
}
},
error: o.on_error,
complete: o.on_complete
});
return this;
};
/**
* Create new Updater.
* @name Updater
* @class This class is used for 'Live Refresh!'.
* @param {string} url A destination URL
* @param {object} param Parameters (for template)
* @param {number} interval Time refresh interval
* @param {object} args Additional URL parameters (in URL alter ?) as assoc array.
* @param {array} objs An array of HTMLElement which will be modified by Updater.
* @param {object} options options and callbacks
*/
var Updater = function (url, param, interval, args, objs, options) {
this._url = url;
this._param = param;
this._interval = interval;
this._args = args;
this.objs = objs;
this.timer = null;
this._options = options || {};
var that = this;
jQuery(objs).each(function () {
jQuery.data(this, 'jTemplateUpdater', that);
});
this.run();
};
/**
* Create new HTTP request to server, get data (as JSON) and send it to templates. Also check does HTMLElements still exists in Document.
*/
Updater.prototype.run = function () {
//remove deleted node
this.objs = jQuery.grep(this.objs, function (elem) {
return (jQuery.contains(document.body, elem.jquery ? elem[0] : elem));
});
//if no node then do nothing
if(this.objs.length === 0) {
return;
}
//ajax call
var that = this;
jQuery.ajax({
url: this._url,
dataType: 'text',
data: this._args,
cache: false,
headers: that._options.headers,
success: function (d) {
try {
var r = jQuery(that.objs).processTemplate(d, that._param, {StrToJSON:true});
if(that._options.on_success) {
that._options.on_success(r); //callback
}
} catch(ex) {}
}
});
//schedule next run
this.timer = setTimeout(function (){that.run();}, this._interval);
};
/**
* Start 'Live Refresh!'.
* @param {string} url A destination URL
* @param {object} param Parameters (for template)
* @param {number} interval Time refresh interval
* @param {object} args Additional URL parameters (in URL alter ?) as assoc array.
* @param {object} options options and callbacks
* @return {Updater} an Updater object
* @memberOf jQuery.fn
*/
jQuery.fn.processTemplateStart = function (url, param, interval, args, options) {
return new Updater(url, param, interval, args, this, options);
};
/**
* Stop 'Live Refresh!'.
* @return {jQuery} chainable jQuery class
* @memberOf jQuery.fn
*/
jQuery.fn.processTemplateStop = function () {
return jQuery(this).each(function () {
var updater = jQuery.data(this, 'jTemplateUpdater');
if(updater == null) {
return;
}
var that = this;
updater.objs = jQuery.grep(updater.objs, function (o) {
return o != that;
});
jQuery.removeData(this, 'jTemplateUpdater');
});
};
jQuery.extend(/** @scope jQuery.prototype */{
/**
* Create new Template.
* @param {string} s A template string (like: "Text: {$T.txt}.").
* @param {array} includes Array of included templates.
* @param {object} settings Settings. (see Template)
* @return {Template}
*/
createTemplate: function (s, includes, settings) {
return new Template(s, includes, settings);
},
/**
* Create new Template from URL.
* @param {string} url_ URL to template
* @param {array} includes Array of included templates.
* @param {object} settings Settings. (see Template)
* @return {Template}
*/
createTemplateURL: function (url_, includes, settings) {
var s = jQuery.ajax({
url: url_,
dataType: 'text',
async: false,
type: 'GET'
}).responseText;
return new Template(s, includes, settings);
},
/**
* Get a Template for HTML node
* @param {Element} HTML node
* @return {Template} a Template or "undefined"
*/
getTemplate: function (element) {
return jQuery.data(element, 'jTemplate');
},
/**
* Process template and return text content.
* @param {Template} template A Template
* @param {object} data data
* @param {object} param parameters
* @return {string} Content of template
*/
processTemplateToText: function (template, data, parameter) {
return template.get(data, parameter, undefined, 0);
},
/**
* Set Debug Mode
* @param {Boolean} value
*/
jTemplatesDebugMode: function (value) {
Template.DEBUG_MODE = value;
}
});
})(jQuery);};
|
"use strict";
window.sys_func = {
setLoader: function(aElement, aIsLoading) {
aIsLoading
? aElement.addClass('sys_disabled')
: aElement.removeClass('sys_disabled');
},
isLoading: function(aElement) {
return aElement.hasClass('sys_disabled');
},
submitAndSend: function(aForm, aButton, aUrl, aCompleteFunc) //for this funct need include file check form.ls
{
var self = $(aButton),
lFormData = new FormData();
if (this.isLoading(self))
return;
if (!sys_func.formGetter.formCheckProcess($(aForm), lFormData))
{
alert(page.get_i18n('alert_msg_1'));
return;
}
sys_func.setLoader(self, true);
$.ajax({
url: aUrl,
data: lFormData,
processData: false,
contentType: false,
cache: false,
type: 'POST',
dataType: 'json',
success: function(data)
{
sys_func.setLoader(self, false);
aCompleteFunc(data);
}
});
},
simpleSend: function (aParams, aOnSuccess)
{
if (!aParams.button || !aParams.data || !aParams.url)
{
alert('invalid params');
return;
}
var lButton = $(aParams.button);
if (sys_func.isLoading(lButton))
return;
sys_func.setLoader(lButton, true);
$.ajax({
url: aParams.url,
data: aParams.data,
type: 'POST',
dataType: 'json',
success: function(data)
{
sys_func.setLoader(lButton, false);
if (aOnSuccess)
aOnSuccess(data);
}
});
}
} |
(function() {
var Widlib, ecstatic, http, server, wls;
http = require('http');
Widlib = require('../../js/widlib');
ecstatic = require('ecstatic')(__dirname + '/');
server = http.createServer(ecstatic);
server.listen(3000);
wls = new Widlib.Server({
pages: {
first: {
body: '<div id="first">first page</div>',
proxyExtender: {
methods: {},
signatures: [],
attributes: {
name: "first",
body: "first"
}
}
}
}
});
wls.listen(server, '/server');
}).call(this);
|
var cards;
var points = 0;
var playerCount = 0;
function Player(cards) {
this.cards = cards;
this.points = points;
this.berechneValue = function() {
if(this.cards[0].name == "ASS" && this.cards[1].name == "ASS" && this.cards[2].name == "ASS") {
this.points = 33;
} else if(this.cards[0].name == this.cards[1].name && this.cards[1].name == this.cards[2].name && this.cards[2].name == this.cards[0].name) {
this.points = 30.5;
} else if(this.cards[0].symbol == this.cards[1].symbol && this.cards[1].symbol == this.cards[2].symbol && this.cards[2].symbol == this.cards[0].symbol) {
this.points = this.cards[0].value + this.cards[1].value + this.cards[2].value;
} else if(this.cards[0].symbol == this.cards[1].symbol) {
this.points = this.cards[0].value + this.cards[1].value;
} else if(this.cards[0].symbol == this.cards[2].symbol) {
this.points = this.cards[0].value + this.cards[2].value;
} else if(this.cards[1].symbol == this.cards[2].symbol) {
this.points = this.cards[1].value + this.cards[2].value;
} else {
if(this.cards[0].value >= this.cards[1].value && this.cards[0].value >= this.cards[2].value) {
this.points = this.cards[0].value;
} else if(this.cards[1].value >= this.cards[0].value && this.cards[1].value >= this.cards[2].value) {
this.points = this.cards[1].value;
} else if(this.cards[2].value >= this.cards[0].value && this.cards[2].value >= this.cards[1].value) {
this.points = this.cards[2].value;
}
}
return this.points;
}
playerCount++;
imageMode(CENTER);
} |
import PerformanceBarApp from '~/performance_bar/components/performance_bar_app.vue';
import PerformanceBarStore from '~/performance_bar/stores/performance_bar_store';
import { shallowMount } from '@vue/test-utils';
describe('performance bar app', () => {
const store = new PerformanceBarStore();
const wrapper = shallowMount(PerformanceBarApp, {
propsData: {
store,
env: 'development',
requestId: '123',
peekUrl: '/-/peek/results',
profileUrl: '?lineprofiler=true',
},
});
it('sets the class to match the environment', () => {
expect(wrapper.element.getAttribute('class')).toContain('development');
});
});
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* 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';
var _ = require('lodash');
var helpers = require('../helpers');
var defaultOptions = {
controllers: {},
useStubs: false // Should we set this automatically based on process.env.NODE_ENV?
};
/**
* Middleware for using Swagger information to route requests to handlers.
*
* This middleware also requires that you use the swagger-metadata middleware before this middleware. This middleware
* also makes no attempt to work around invalid Swagger documents. If you would like to validate your requests using
* the swagger-validator middleware, you must use it prior to using this middleware. If you would like to apply the
* SecurityDefinitions in your Swagger document, you must include a properly configured swagger-security middleware
* before including this middleware.
*
* The routing works such that any Swagger operation is expected to have an "x-swagger-router-controller" that contains
* the controller name and the "operationId" will contain the method to invoke within that controller. (If you do not
* supply an "operationId" for your operation, we will default to the method associated with the operation.) We will
* then identify the controller by name from the controllers path (configurable) and identify the route handler within
* the controller by name.
*
* @param {object} [options] - The middleware options
* @param {(string|object|string[]) [options.controllers=./controllers] - If this is a string or string array, this is
* the path, or paths, to find the controllers
* in. If it's an object, the keys are the
* controller "name" (as described above) and the
* value is a function.
* @param {boolean} [options.useStubs=false] - Whether or not to stub missing controllers and methods
*
* @returns the middleware function
*/
exports = module.exports = function swaggerRouterMiddleware (options) {
var handlerCache = {};
// Set the defaults
options = _.defaults(options || {}, defaultOptions);
if (_.isPlainObject(options.controllers)) {
// Create the handler cache from the passed in controllers object
_.each(options.controllers, function (func) {
if (!_.isFunction(func)) {
throw new Error('options.controllers values must be functions');
}
});
handlerCache = options.controllers;
} else {
// Create the handler cache from the modules in the controllers directory
handlerCache = helpers.handlerCacheFromDir(options.controllers);
}
return function swaggerRouter (req, res, next) {
var handler;
var handlerName;
var operation;
var rErr;
if (req.swagger) {
operation = req.swagger.operation;
req.swagger.useStubs = options.useStubs;
if (_.isUndefined(operation)) {
return helpers.send405('2.0', req, res, next);
} else {
handlerName = helpers.getHandlerName('2.0', req);
handler = handlerCache[handlerName];
if (_.isUndefined(handler) && options.useStubs === true) {
handler = handlerCache[handlerName] = helpers.createStubHandler('2.0', req, res, next, handlerName);
}
if (!_.isUndefined(handler)) {
try {
return handler(req, res, next);
} catch (err) {
rErr = err;
}
}
}
}
return next(rErr);
};
};
|
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
export const styles = {
/* Styles applied to the root element. */
root: {
width: '100%',
overflowX: 'auto',
},
};
const TableContainer = React.forwardRef(function TableContainer(props, ref) {
const { classes, className, component: Component = 'div', ...other } = props;
return <Component ref={ref} className={clsx(classes.root, className)} {...other} />;
});
TableContainer.propTypes = {
/**
* The table itself, normally `<Table />`
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: PropTypes /* @typescript-to-proptypes-ignore */.elementType,
};
export default withStyles(styles, { name: 'MuiTableContainer' })(TableContainer);
|
/* test-code */
"Bad Language";
/* end-test-code */
"Good Language"; |
var group__CMSIS__DACR__Dn =
[
[ "DACR_Dn_CLIENT", "group__CMSIS__DACR__Dn.html#gac76e6128758cd64a9fa92487ec49441b", null ],
[ "DACR_Dn_MANAGER", "group__CMSIS__DACR__Dn.html#gabbf27724d67055138bf7abdb651e9732", null ],
[ "DACR_Dn_NOACCESS", "group__CMSIS__DACR__Dn.html#ga281ebf97decb4ef4f7b1e5c4285c45ab", null ]
]; |
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Famous Industries Inc.
*
* 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';
import { Vec3 } from '../math/Vec3';
import { Mat33 } from '../math/Mat33';
import { ObjectManager } from '../utilities/ObjectManager';
var TRIPLE_REGISTER = new Vec3();
/**
* The so called triple product. Used to find a vector perpendicular to (v2 - v1) in the direction of v3.
* (v1 x v2) x v3.
*
* @method
* @private
* @param {Vec3} v1 The first Vec3.
* @param {Vec3} v2 The second Vec3.
* @param {Vec3} v3 The third Vec3.
* @return {Vec3} The result of the triple product.
*/
function tripleProduct(v1, v2, v3) {
var v = TRIPLE_REGISTER;
Vec3.cross(v1, v2, v);
Vec3.cross(v, v3, v);
return v;
}
/**
* Of a set of vertices, retrieves the vertex furthest in the given direction.
*
* @method
* @private
* @param {Vec3[]} vertices The reference set of Vec3's.
* @param {Vec3} direction The direction to compare against.
* @return {Object} The vertex and its index in the vertex array.
*/
function _hullSupport(vertices, direction) {
var furthest;
var max = -Infinity;
var dot;
var vertex;
var index;
for (var i = 0; i < vertices.length; i++) {
vertex = vertices[i];
dot = Vec3.dot(vertex, direction);
if (dot > max) {
furthest = vertex;
max = dot;
index = i;
}
}
return {
vertex: furthest,
index: index
};
}
var VEC_REGISTER = new Vec3();
var POINTCHECK_REGISTER = new Vec3();
var AO_REGISTER = new Vec3();
var AB_REGISTER = new Vec3();
var AC_REGISTER = new Vec3();
var AD_REGISTER = new Vec3();
var BC_REGISTER = new Vec3();
var BD_REGISTER = new Vec3();
/**
* Used internally to represent polyhedral facet information.
*
* @class DynamicGeometryFeature
* @param {Number} distance The distance of the feature from the origin.
* @param {Vec3} normal The Vec3 orthogonal to the feature, pointing out of the geometry.
* @param {Number[]} vertexIndices The indices of the vertices which compose the feature.
*/
class DynamicGeometryFeature {
constructor(distance, normal, vertexIndices) {
this.distance = distance;
this.normal = normal;
this.vertexIndices = vertexIndices;
}
/**
* Used by ObjectManager to reset objects.
*
* @method
* @param {Number} distance Distance from the origin.
* @param {Vec3} normal Vec3 normal to the feature.
* @param {Number[]} vertexIndices Indices of the vertices which compose the feature.
* @return {DynamicGeometryFeature} this
*/
reset(distance, normal, vertexIndices) {
this.distance = distance;
this.normal = normal;
this.vertexIndices = vertexIndices;
return this;
};
}
ObjectManager.register('DynamicGeometryFeature', DynamicGeometryFeature);
var oMRequestDynamicGeometryFeature = ObjectManager.requestDynamicGeometryFeature;
var oMFreeDynamicGeometryFeature = ObjectManager.freeDynamicGeometryFeature;
/**
* Abstract object representing a growing polyhedron. Used in ConvexHull and in GJK+EPA collision detection.
*
* @class DynamicGeometry
*/
class DynamicGeometry {
constructor() {
this.vertices = [];
this.numVertices = 0;
this.features = [];
this.numFeatures = 0;
this.lastVertexIndex = 0;
this._IDPool = {
vertices: [],
features: []
};
}
/**
* Used by ObjectManager to reset objects.
*
* @method
* @return {DynamicGeometry} this
*/
reset() {
this.vertices = [];
this.numVertices = 0;
this.features = [];
this.numFeatures = 0;
this.lastVertexIndex = 0;
this._IDPool = {
vertices: [],
features: []
};
return this;
};
/**
* Add a vertex to the polyhedron.
*
* @method
* @param {Object} vertexObj Object returned by the support function.
* @return {undefined} undefined
*/
addVertex(vertexObj) {
var index = this._IDPool.vertices.length ? this._IDPool.vertices.pop() : this.vertices.length;
this.vertices[index] = vertexObj;
this.lastVertexIndex = index;
this.numVertices++;
};
/**
* Remove a vertex and push its location in the vertex array to the IDPool for later use.
*
* @method
* @param {Number} index Index of the vertex to remove.
* @return {Object} vertex The vertex object.
*/
removeVertex(index) {
var vertex = this.vertices[index];
this.vertices[index] = null;
this._IDPool.vertices.push(index);
this.numVertices--;
return vertex;
};
/**
* Add a feature (facet) to the polyhedron. Used internally in the reshaping process.
*
* @method
* @param {Number} distance The distance of the feature from the origin.
* @param {Vec3} normal The facet normal.
* @param {Number[]} vertexIndices The indices of the vertices which compose the feature.
* @return {undefined} undefined
*/
addFeature(distance, normal, vertexIndices) {
var index = this._IDPool.features.length ? this._IDPool.features.pop() : this.features.length;
this.features[index] = oMRequestDynamicGeometryFeature().reset(distance, normal, vertexIndices);
this.numFeatures++;
};
/**
* Remove a feature and push its location in the feature array to the IDPool for later use.
*
* @method
* @param {Number} index Index of the feature to remove.
* @return {undefined} undefined
*/
removeFeature(index) {
var feature = this.features[index];
this.features[index] = null;
this._IDPool.features.push(index);
this.numFeatures--;
oMFreeDynamicGeometryFeature(feature);
};
/**
* Retrieve the last vertex object added to the geometry.
*
* @method
* @return {Object} The last vertex added.
*/
getLastVertex() {
return this.vertices[this.lastVertexIndex];
};
/**
* Return the feature closest to the origin.
*
* @method
* @return {DynamicGeometryFeature} The closest feature.
*/
getFeatureClosestToOrigin() {
var min = Infinity;
var closest = null;
var features = this.features;
for (var i = 0, len = features.length; i < len; i++) {
var feature = features[i];
if (!feature) continue;
if (feature.distance < min) {
min = feature.distance;
closest = feature;
}
}
return closest;
};
/**
* Based on the last (exterior) point added to the polyhedron, removes features as necessary and redetermines
* its (convex) shape to include the new point by adding triangle features. Uses referencePoint, a point on the shape's
* interior, to ensure feature normals point outward, else takes referencePoint to be the origin.
*
* @method
* @param {Vec3} referencePoint Point known to be in the interior, used to orient feature normals.
* @return {undefined} undefined
*/
reshape(referencePoint) {
var vertices = this.vertices;
var point = this.getLastVertex().vertex;
var features = this.features;
var vertexOnFeature;
var featureVertices;
var i, j, len;
// The removal of features creates a hole in the polyhedron -- frontierEdges maintains the edges
// of this hole, each of which will form one edge of a new feature to be created
var frontierEdges = [];
for (i = 0, len = features.length; i < len; i++) {
if (!features[i]) continue;
featureVertices = features[i].vertexIndices;
vertexOnFeature = vertices[featureVertices[0]].vertex;
// If point is 'above' the feature, remove that feature, and check to add its edges to the frontier.
if (Vec3.dot(features[i].normal, Vec3.subtract(point, vertexOnFeature, POINTCHECK_REGISTER)) > -0.001) {
_validateEdge(vertices, frontierEdges, featureVertices[0], featureVertices[1]);
_validateEdge(vertices, frontierEdges, featureVertices[1], featureVertices[2]);
_validateEdge(vertices, frontierEdges, featureVertices[2], featureVertices[0]);
this.removeFeature(i);
}
}
var A = point;
var a = this.lastVertexIndex;
for (j = 0, len = frontierEdges.length; j < len; j++) {
if (!frontierEdges[j]) continue;
var b = frontierEdges[j][0];
var c = frontierEdges[j][1];
var B = vertices[b].vertex;
var C = vertices[c].vertex;
var AB = Vec3.subtract(B, A, AB_REGISTER);
var AC = Vec3.subtract(C, A, AC_REGISTER);
var ABC = Vec3.cross(AB, AC, new Vec3());
ABC.normalize();
if (!referencePoint) {
var distance = Vec3.dot(ABC, A);
if (distance < 0) {
ABC.invert();
distance *= -1;
}
this.addFeature(distance, ABC, [a, b, c]);
} else {
var reference = Vec3.subtract(referencePoint, A, VEC_REGISTER);
if (Vec3.dot(ABC, reference) > -0.001) ABC.invert();
this.addFeature(null, ABC, [a, b, c]);
}
}
};
/**
* Checks if the Simplex instance contains the origin, returns true or false.
* If false, removes a point and, as a side effect, changes input direction to be both
* orthogonal to the current working simplex and point toward the origin.
* Calls callback on the removed point.
*
* @method
* @param {Vec3} direction Vector used to store the new search direction.
* @param {Function} callback Function invoked with the removed vertex, used e.g. to free the vertex object
* in the object manager.
* @return {Boolean} The result of the containment check.
*/
simplexContainsOrigin(direction, callback) {
var numVertices = this.vertices.length;
var a = this.lastVertexIndex;
var b = a - 1;
var c = a - 2;
var d = a - 3;
b = b < 0 ? b + numVertices : b;
c = c < 0 ? c + numVertices : c;
d = d < 0 ? d + numVertices : d;
var A = this.vertices[a].vertex;
var B = this.vertices[b].vertex;
var C = this.vertices[c].vertex;
var D = this.vertices[d].vertex;
var AO = Vec3.scale(A, -1, AO_REGISTER);
var AB = Vec3.subtract(B, A, AB_REGISTER);
var AC, AD, BC, BD;
var ABC, ACD, ABD, BCD;
var distanceABC, distanceACD, distanceABD, distanceBCD;
var vertexToRemove;
if (numVertices === 4) {
// Tetrahedron
AC = Vec3.subtract(C, A, AC_REGISTER);
AD = Vec3.subtract(D, A, AD_REGISTER);
ABC = Vec3.cross(AB, AC, new Vec3());
ACD = Vec3.cross(AC, AD, new Vec3());
ABD = Vec3.cross(AB, AD, new Vec3());
ABC.normalize();
ACD.normalize();
ABD.normalize();
if (Vec3.dot(ABC, AD) > 0) ABC.invert();
if (Vec3.dot(ACD, AB) > 0) ACD.invert();
if (Vec3.dot(ABD, AC) > 0) ABD.invert();
// Don't need to check BCD because we would have just checked that in the previous iteration
// -- we added A to the BCD triangle because A was in the direction of the origin.
distanceABC = Vec3.dot(ABC, AO);
distanceACD = Vec3.dot(ACD, AO);
distanceABD = Vec3.dot(ABD, AO);
// Norms point away from origin -> origin is inside tetrahedron
if (distanceABC < 0.001 && distanceABD < 0.001 && distanceACD < 0.001) {
BC = Vec3.subtract(C, B, BC_REGISTER);
BD = Vec3.subtract(D, B, BD_REGISTER);
BCD = Vec3.cross(BC, BD, new Vec3());
BCD.normalize();
if (Vec3.dot(BCD, AB) <= 0) BCD.invert();
distanceBCD = -1 * Vec3.dot(BCD, B);
// Prep features for EPA
this.addFeature(-distanceABC, ABC, [a, b, c]);
this.addFeature(-distanceACD, ACD, [a, c, d]);
this.addFeature(-distanceABD, ABD, [a, d, b]);
this.addFeature(-distanceBCD, BCD, [b, c, d]);
return true;
} else if (distanceABC >= 0.001) {
vertexToRemove = this.removeVertex(d);
direction.copy(ABC);
} else if (distanceACD >= 0.001) {
vertexToRemove = this.removeVertex(b);
direction.copy(ACD);
} else {
vertexToRemove = this.removeVertex(c);
direction.copy(ABD);
}
} else if (numVertices === 3) {
// Triangle
AC = Vec3.subtract(C, A, AC_REGISTER);
Vec3.cross(AB, AC, direction);
if (Vec3.dot(direction, AO) <= 0) direction.invert();
} else {
// Line
direction.copy(tripleProduct(AB, AO, AB));
}
if (vertexToRemove && callback) callback(vertexToRemove);
return false;
};
}
/**
* Adds edge if not already on the frontier, removes if the edge or its reverse are on the frontier.
* Used when reshaping DynamicGeometry's.
*
* @method
* @private
* @param {Object[]} vertices Vec3 reference array.
* @param {Array.<Number[]>} frontier Current edges potentially separating the features to remove from the persistant shape.
* @param {Number} start The index of the starting Vec3 on the edge.
* @param {Number} end The index of the culminating Vec3.
* @return {undefined} undefined
*/
function _validateEdge(vertices, frontier, start, end) {
var e0 = vertices[start].vertex;
var e1 = vertices[end].vertex;
for (var i = 0, len = frontier.length; i < len; i++) {
var edge = frontier[i];
if (!edge) continue;
var v0 = vertices[edge[0]].vertex;
var v1 = vertices[edge[1]].vertex;
if ((e0 === v0 && (e1 === v1)) || (e0 === v1 && (e1 === v0))) {
frontier[i] = null;
return;
}
}
frontier.push([start, end]);
}
/**
* Given an array of Vec3's, computes the convex hull. Used in constructing bodies in the physics system and to
* create custom GL meshes.
*
* @class ConvexHull
* @param {Vec3[]} vertices Cloud of vertices of which the enclosing convex hull is desired.
* @param {Number} iterations Maximum number of vertices to compose the convex hull.
*/
function ConvexHull(vertices, iterations) {
iterations = iterations || 1e3;
var hull = _computeConvexHull(vertices, iterations);
var i, len;
var indices = [];
for (i = 0, len = hull.features.length; i < len; i++) {
var f = hull.features[i];
if (f) indices.push(f.vertexIndices);
}
var polyhedralProperties = _computePolyhedralProperties(hull.vertices, indices);
var centroid = polyhedralProperties.centroid;
var worldVertices = [];
for (i = 0, len = hull.vertices.length; i < len; i++) {
worldVertices.push(Vec3.subtract(hull.vertices[i].vertex, centroid, new Vec3()));
}
var normals = [];
for (i = 0, len = worldVertices.length; i < len; i++) {
normals.push(Vec3.normalize(worldVertices[i], new Vec3()));
}
var graph = {};
var _neighborMatrix = {};
for (i = 0; i < indices.length; i++) {
var a = indices[i][0];
var b = indices[i][1];
var c = indices[i][2];
_neighborMatrix[a] = _neighborMatrix[a] || {};
_neighborMatrix[b] = _neighborMatrix[b] || {};
_neighborMatrix[c] = _neighborMatrix[c] || {};
graph[a] = graph[a] || [];
graph[b] = graph[b] || [];
graph[c] = graph[c] || [];
if (!_neighborMatrix[a][b]) {
_neighborMatrix[a][b] = 1;
graph[a].push(b);
}
if (!_neighborMatrix[a][c]) {
_neighborMatrix[a][c] = 1;
graph[a].push(c);
}
if (!_neighborMatrix[b][a]) {
_neighborMatrix[b][a] = 1;
graph[b].push(a);
}
if (!_neighborMatrix[b][c]) {
_neighborMatrix[b][c] = 1;
graph[b].push(c);
}
if (!_neighborMatrix[c][a]) {
_neighborMatrix[c][a] = 1;
graph[c].push(a);
}
if (!_neighborMatrix[c][b]) {
_neighborMatrix[c][b] = 1;
graph[c].push(b);
}
}
this.indices = indices;
this.vertices = worldVertices;
this.normals = normals;
this.polyhedralProperties = polyhedralProperties;
this.graph = graph;
}
/**
* Performs the actual computation of the convex hull.
*
* @method
* @private
* @param {Vec3[]} vertices Cloud of vertices of which the enclosing convex hull is desired.
* @param {Number} maxIterations Maximum number of vertices to compose the convex hull.
* @return {DynamicGeometry} The computed hull.
*/
function _computeConvexHull(vertices, maxIterations) {
var hull = new DynamicGeometry();
hull.addVertex(_hullSupport(vertices, new Vec3(1, 0, 0)));
hull.addVertex(_hullSupport(vertices, new Vec3(-1, 0, 0)));
var A = hull.vertices[0].vertex;
var B = hull.vertices[1].vertex;
var AB = Vec3.subtract(B, A, AB_REGISTER);
var dot;
var vertex;
var furthest;
var index;
var i, len;
var max = -Infinity;
for (i = 0; i < vertices.length; i++) {
vertex = vertices[i];
if (vertex === A || vertex === B) continue;
var AV = Vec3.subtract(vertex, A, VEC_REGISTER);
dot = Vec3.dot(AV, tripleProduct(AB, AV, AB));
dot = dot < 0 ? dot * -1 : dot;
if (dot > max) {
max = dot;
furthest = vertex;
index = i;
}
}
hull.addVertex({
vertex: furthest,
index: index
});
var C = furthest;
var AC = Vec3.subtract(C, A, AC_REGISTER);
var ABC = Vec3.cross(AB, AC, new Vec3());
ABC.normalize();
max = -Infinity;
for (i = 0; i < vertices.length; i++) {
vertex = vertices[i];
if (vertex === A || vertex === B || vertex === C) continue;
dot = Vec3.dot(Vec3.subtract(vertex, A, VEC_REGISTER), ABC);
dot = dot < 0 ? dot * -1 : dot;
if (dot > max) {
max = dot;
furthest = vertex;
index = i;
}
}
hull.addVertex({
vertex: furthest,
index: index
});
var D = furthest;
var AD = Vec3.subtract(D, A, AD_REGISTER);
var BC = Vec3.subtract(C, B, BC_REGISTER);
var BD = Vec3.subtract(D, B, BD_REGISTER);
var ACD = Vec3.cross(AC, AD, new Vec3());
var ABD = Vec3.cross(AB, AD, new Vec3());
var BCD = Vec3.cross(BC, BD, new Vec3());
ACD.normalize();
ABD.normalize();
BCD.normalize();
if (Vec3.dot(ABC, AD) > 0) ABC.invert();
if (Vec3.dot(ACD, AB) > 0) ACD.invert();
if (Vec3.dot(ABD, AC) > 0) ABD.invert();
if (Vec3.dot(BCD, AB) < 0) BCD.invert();
var a = 0;
var b = 1;
var c = 2;
var d = 3;
hull.addFeature(null, ABC, [a, b, c]);
hull.addFeature(null, ACD, [a, c, d]);
hull.addFeature(null, ABD, [a, b, d]);
hull.addFeature(null, BCD, [b, c, d]);
var assigned = {};
for (i = 0, len = hull.vertices.length; i < len; i++) {
assigned[hull.vertices[i].index] = true;
}
var cx = A.x + B.x + C.x + D.x;
var cy = A.y + B.y + C.y + D.y;
var cz = A.z + B.z + C.z + D.z;
var referencePoint = new Vec3(cx, cy, cz);
referencePoint.scale(0.25);
var features = hull.features;
var iteration = 0;
while (iteration++ < maxIterations) {
var currentFeature = null;
for (i = 0, len = features.length; i < len; i++) {
if (!features[i] || features[i].done) continue;
currentFeature = features[i];
furthest = null;
index = null;
A = hull.vertices[currentFeature.vertexIndices[0]].vertex;
var s = _hullSupport(vertices, currentFeature.normal);
furthest = s.vertex;
index = s.index;
var dist = Vec3.dot(Vec3.subtract(furthest, A, VEC_REGISTER), currentFeature.normal);
if (dist < 0.001 || assigned[index]) {
currentFeature.done = true;
continue;
}
assigned[index] = true;
hull.addVertex(s);
hull.reshape(referencePoint);
}
// No feature has points 'above' it -> finished
if (currentFeature === null) break;
}
return hull;
}
/**
* Helper function used in _computePolyhedralProperties.
* Sets f0 - f2 and g0 - g2 depending on w0 - w2.
*
* @method
* @private
* @param {Number} w0 Reference x coordinate.
* @param {Number} w1 Reference y coordinate.
* @param {Number} w2 Reference z coordinate.
* @param {Number[]} f One of two output registers to contain the result of the calculation.
* @param {Number[]} g One of two output registers to contain the result of the calculation.
* @return {undefined} undefined
*/
function _subexpressions(w0, w1, w2, f, g) {
var t0 = w0 + w1;
f[0] = t0 + w2;
var t1 = w0 * w0;
var t2 = t1 + w1 * t0;
f[1] = t2 + w2 * f[0];
f[2] = w0 * t1 + w1 * t2 + w2 * f[1];
g[0] = f[1] + w0 * (f[0] + w0);
g[1] = f[1] + w1 * (f[0] + w1);
g[2] = f[1] + w2 * (f[0] + w2);
}
/**
* Determines various properties of the volume.
*
* @method
* @private
* @param {Vec3[]} vertices The vertices of the polyhedron.
* @param {Array.<Number[]>} indices Array of arrays of indices of vertices composing the triangular features of the polyhedron,
* one array for each feature.
* @return {Object} Object holding the calculated span, volume, center, and euler tensor.
*/
function _computePolyhedralProperties(vertices, indices) {
// Order: 1, x, y, z, x^2, y^2, z^2, xy, yz, zx
var integrals = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var fx = [];
var fy = [];
var fz = [];
var gx = [];
var gy = [];
var gz = [];
var i, len;
for (i = 0, len = indices.length; i < len; i++) {
var A = vertices[indices[i][0]].vertex;
var B = vertices[indices[i][1]].vertex;
var C = vertices[indices[i][2]].vertex;
var AB = Vec3.subtract(B, A, AB_REGISTER);
var AC = Vec3.subtract(C, A, AC_REGISTER);
var ABC = AB.cross(AC);
if (Vec3.dot(A, ABC) < 0) ABC.invert();
var d0 = ABC.x;
var d1 = ABC.y;
var d2 = ABC.z;
var x0 = A.x;
var y0 = A.y;
var z0 = A.z;
var x1 = B.x;
var y1 = B.y;
var z1 = B.z;
var x2 = C.x;
var y2 = C.y;
var z2 = C.z;
_subexpressions(x0, x1, x2, fx, gx);
_subexpressions(y0, y1, y2, fy, gy);
_subexpressions(z0, z1, z2, fz, gz);
integrals[0] += d0 * fx[0];
integrals[1] += d0 * fx[1];
integrals[2] += d1 * fy[1];
integrals[3] += d2 * fz[1];
integrals[4] += d0 * fx[2];
integrals[5] += d1 * fy[2];
integrals[6] += d2 * fz[2];
integrals[7] += d0 * (y0 * gx[0] + y1 * gx[1] + y2 * gx[2]);
integrals[8] += d1 * (z0 * gy[0] + z1 * gy[1] + z2 * gy[2]);
integrals[9] += d2 * (x0 * gz[0] + x1 * gz[1] + x2 * gz[2]);
}
integrals[0] /= 6;
integrals[1] /= 24;
integrals[2] /= 24;
integrals[3] /= 24;
integrals[4] /= 60;
integrals[5] /= 60;
integrals[6] /= 60;
integrals[7] /= 120;
integrals[8] /= 120;
integrals[9] /= 120;
var minX = Infinity,
maxX = -Infinity;
var minY = Infinity,
maxY = -Infinity;
var minZ = Infinity,
maxZ = -Infinity;
for (i = 0, len = vertices.length; i < len; i++) {
var vertex = vertices[i].vertex;
if (vertex.x < minX)
minX = vertex.x;
if (vertex.x > maxX)
maxX = vertex.x;
if (vertex.y < minY)
minY = vertex.y;
if (vertex.y > maxY)
maxY = vertex.y;
if (vertex.z < minZ)
minZ = vertex.z;
if (vertex.z > maxZ)
maxZ = vertex.z;
}
var size = [maxX - minX, maxY - minY, maxZ - minZ];
var volume = integrals[0];
var centroid = new Vec3(integrals[1], integrals[2], integrals[3]);
centroid.scale(1 / volume);
var eulerTensor = new Mat33([
integrals[4], integrals[7], integrals[9],
integrals[7], integrals[5], integrals[8],
integrals[9], integrals[8], integrals[6]]);
return {
size: size,
volume: volume,
centroid: centroid,
eulerTensor: eulerTensor
};
}
ObjectManager.register('DynamicGeometry', DynamicGeometry);
export { DynamicGeometry };
export { ConvexHull };
|
import React from 'react';
import Header from 'js/components/elements/Header';
import List from '../elements/List';
class Home extends React.Component {
constructor(props) {
super(props);
}
render(){
return (
<div>
<Header user={this.props.user || {} } />
<div className="container gutter" >
<button className="btn btn-primary toggle-view pull-right" type="button" onClick={this.props.onChangeView}>Toggle</button>
<h2>List/Grid View</h2>
<List type={this.props.view} data={this.props.posts || []} />
</div>
</div>
);
}
}
export default Home
|
describe("sc.lang.compiler.Parser", function() {
"use strict";
var Syntax = sc.lang.compiler.Syntax;
var Token = sc.lang.compiler.Token;
var Message = sc.lang.compiler.Message;
var strlib = sc.libs.strlib;
describe("parseAssignmentExpression", function() {
sc.test.compile(this.title).each({
"a = 10": sc.test.OK,
"a.b = 10": sc.test.OK,
"a[0] = 10": sc.test.OK,
"#a, b = c": sc.test.OK,
"#a ... b = c": sc.test.OK,
"#[]": sc.test.OK,
"[ 0 ] = 10": strlib.format(Message.InvalidLHSInAssignment),
"a.b() = 10": strlib.format(Message.UnexpectedToken, "="),
"-a = 10": strlib.format(Message.UnexpectedToken, "="),
});
sc.test.parse(this.title).each({
"a = 10": {
type: Syntax.AssignmentExpression,
operator: "=",
left: {
type: Syntax.Identifier,
name: "a",
range: [ 0, 1 ],
loc: {
start: { line: 1, column: 0 },
end: { line: 1, column: 1 }
}
},
right: {
type: Syntax.Literal,
value: "10",
valueType: Token.IntegerLiteral,
range: [ 4, 6 ],
loc: {
start: { line: 1, column: 4 },
end: { line: 1, column: 6 }
}
},
range: [ 0, 6 ],
loc: {
start: { line: 1, column: 0 },
end: { line: 1, column: 6 }
}
},
"a.b = 10": { // a.b_(10)
type: Syntax.CallExpression,
stamp: "=",
callee: {
type: Syntax.Identifier,
name: "a",
range: [ 0, 1 ],
loc: {
start: { line: 1, column: 0 },
end: { line: 1, column: 1 }
}
},
method: {
type: Syntax.Identifier,
name: "b_",
range: [ 2, 3 ],
loc: {
start: { line: 1, column: 2 },
end: { line: 1, column: 3 }
}
},
args: {
list: [
{
type: Syntax.Literal,
value: "10",
valueType: Token.IntegerLiteral,
range: [ 6, 8 ],
loc: {
start: { line: 1, column: 6 },
end: { line: 1, column: 8 }
}
}
]
},
range: [ 0, 8 ],
loc: {
start: { line: 1, column: 0 },
end: { line: 1, column: 8 }
}
},
"a[0] = 10": { // a.put(0, 10)
type: Syntax.CallExpression,
stamp: "[",
callee: {
type: Syntax.Identifier,
name: "a",
range: [ 0, 1 ],
loc: {
start: { line: 1, column: 0 },
end: { line: 1, column: 1 }
}
},
method: {
type: Syntax.Identifier,
name: "put",
},
args: {
list: [
{
type: Syntax.Literal,
value: "0",
valueType: Token.IntegerLiteral,
range: [ 2, 3 ],
loc: {
start: { line: 1, column: 2 },
end: { line: 1, column: 3 }
}
},
{
type: Syntax.Literal,
value: "10",
valueType: Token.IntegerLiteral,
range: [ 7, 9 ],
loc: {
start: { line: 1, column: 7 },
end: { line: 1, column: 9 }
}
}
]
},
range: [ 0, 9 ],
loc: {
start: { line: 1, column: 0 },
end: { line: 1, column: 9 }
}
},
"a[..] = 10": { // a.putSeries(nil, nil, nil, 10)
type: Syntax.CallExpression,
stamp: "[",
callee: {
type: Syntax.Identifier,
name: "a",
range: [ 0, 1 ],
loc: {
start: { line: 1, column: 0 },
end: { line: 1, column: 1 }
}
},
method: {
type: Syntax.Identifier,
name: "putSeries",
},
args: {
list: [
null,
null,
null,
{
type: Syntax.Literal,
value: "10",
valueType: Token.IntegerLiteral,
range: [ 8, 10 ],
loc: {
start: { line: 1, column: 8 },
end: { line: 1, column: 10 }
}
}
]
},
range: [ 0, 10 ],
loc: {
start: { line: 1, column: 0 },
end: { line: 1, column: 10 }
}
},
"#a, b = c": {
type: Syntax.AssignmentExpression,
operator: "=",
left: [
{
type: Syntax.Identifier,
name: "a",
range: [ 1, 2 ],
loc: {
start: { line: 1, column: 1 },
end: { line: 1, column: 2 }
}
},
{
type: Syntax.Identifier,
name: "b",
range: [ 4, 5 ],
loc: {
start: { line: 1, column: 4 },
end: { line: 1, column: 5 }
}
}
],
right: {
type: Syntax.Identifier,
name: "c",
range: [ 8, 9 ],
loc: {
start: { line: 1, column: 8 },
end: { line: 1, column: 9 }
}
},
range: [ 0, 9 ],
loc: {
start: { line: 1, column: 0 },
end: { line: 1, column: 9 }
}
},
"#[]": {
type: Syntax.ListExpression,
immutable: true,
elements: [],
range: [ 0, 3 ],
loc: {
start: { line: 1, column: 0 },
end: { line: 1, column: 3 }
}
},
"#a ... b = c": {
type: Syntax.AssignmentExpression,
operator: "=",
left: [
{
type: Syntax.Identifier,
name: "a",
range: [ 1, 2 ],
loc: {
start: { line: 1, column: 1 },
end: { line: 1, column: 2 }
}
}
],
remain: {
type: Syntax.Identifier,
name: "b",
range: [ 7, 8 ],
loc: {
start: { line: 1, column: 7 },
end: { line: 1, column: 8 }
}
},
right: {
type: Syntax.Identifier,
name: "c",
range: [ 11, 12 ],
loc: {
start: { line: 1, column: 11 },
end: { line: 1, column: 12 }
}
},
range: [ 0, 12 ],
loc: {
start: { line: 1, column: 0 },
end: { line: 1, column: 12 }
}
}
});
});
});
|
(function() {
'use strict';
angular
.module('webApp')
.directive('blurOnEnter', blurOnEnter);
function blurOnEnter() {
return function(scope, elem, attrs) {
elem.bind('keydown keypress', function(e) {
if (e.which === 13) {
e.preventDefault();
elem.blur();
scope.$apply(attrs.ngBlur);
}
});
};
}
})();
// Credits http://jsfiddle.net/nq6fgse1/
|
export default function distance(x1, y1, x2, y2) {
const dx = x1 - x2;
const dy = y1 - y2;
return Math.sqrt(dx * dx + dy * dy);
}
|
var assert = require('assert');
var helper = require('./helper');
describe('robot', function() {
before(function() {
return helper.ready;
});
after(function() {
helper.reset();
});
it('should have correct number of listeners', function() {
assert.equal(4, helper.listeners.text.length);
assert.equal(1, helper.listeners.respond.length);
assert.equal(0, helper.sent.length);
});
it('should receive "test"', function() {
return helper.adapter.receive('test').then(function() {
assert.equal(1, helper.sent.length);
assert.equal('OK', helper.sent[0]);
});
});
it('should receive "reply"', function() {
return helper.adapter.receive('reply').then(function() {
assert.equal(2, helper.sent.length);
assert.equal('helper: OK', helper.sent[1]);
});
});
it('should receive "random"', function() {
return helper.adapter.receive('random').then(function() {
assert.equal(3, helper.sent.length);
assert.ok(helper.sent[2].match(/^(1|2)$/));
});
});
it('should send to room', function() {
//Test that when we message a room, the 'recipient' is the robot user and the room attribute is set properly
helper.messageRoom("chat@example.com", "Hello room");
assert.equal(4, helper.sent.length);
assert.equal("chat@example.com", helper.recipients[3].room);
assert.equal("Hello room", helper.sent[3]);
});
it('should send to room again', function() {
helper.messageRoom("chat2@example.com", "Hello to another room");
assert.equal(5, helper.sent.length);
assert.equal("chat2@example.com", helper.recipients[4].room);
assert.equal("Hello to another room", helper.sent[4]);
});
it('should receive "foobar" as catch-all', function() {
return helper.adapter.receive('foobar').then(function() {
assert.equal(6, helper.sent.length);
assert.equal('catch-all', helper.sent[5]);
});
});
// Testing replies
it('should reply to "rsvp"', function() {
return helper.adapter.receive(helper.name + " rsvp").then(function() {
assert.equal(7, helper.sent.length);
assert.equal("responding", helper.sent[6]);
});
});
it('should reply to "rsvp" with @', function() {
// Using name with @ form
return helper.adapter.receive("@" + helper.name + " rsvp").then(function() {
assert.equal(8, helper.sent.length);
assert.equal("responding", helper.sent[7]);
});
});
it('should reply to "rsvp" with alias', function() {
// Using just the alias
return helper.adapter.receive(helper.alias + " rsvp").then(function() {
assert.equal(9, helper.sent.length);
assert.equal("responding", helper.sent[8]);
});
});
it('should reply to "rsvp" with @alias', function() {
// Using alias with @ form
return helper.adapter.receive("@" + helper.alias + " rsvp").then(function() {
assert.equal(10, helper.sent.length);
assert.equal("responding", helper.sent[9]);
});
});
});
|
var morgan = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
path = require('path'),
express = require('express'),
public = path.join(__dirname + '../public/')
module.exports = function(options) {
var app = options.app;
app.use(express.static('public'));
app.get('/', function(req, res) {
res.sendFile(public + 'index.html');
});
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
// development error handler with stacktrace print.
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
} else {
// production error handler.
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
}
}; |
/* eslint-env mocha */
const {expect} = require('chai')
const React = require('react')
const Search = require('../js/Search')
const ShowCard = require('../js/ShowCard')
const {shallow, mount} = require('enzyme')
const {shows} = require('../public/data')
const {rootReducer} = require('../js/store')
xdescribe('First Test!', () => {
it('should pass', () => {
expect(1 + 1 === 2).to.be.true
expect(1 + 1).to.equal(5)
})
})
xdescribe('<Search />', () => {
it('should render the brand', () => {
const wrapper = shallow(<Search />)
console.log(wrapper.debug())
expect(wrapper.contains(<h1 className='brand'>React Fake App</h1>)).to.be.true
})
it('should render as many shows as there are data for', () => {
const wrapper = shallow(<Search />)
expect(wrapper.find(ShowCard).length).to.equal(shows.length)
})
it('should filter correctly given new state', () => {
const wrapper = mount(<Search />)
const input = wrapper.find('.search-input')
input.node.value = 'house'
input.simulate('change')
expect(wrapper.state('searchTerm')).to.equal('house')
expect(wrapper.find('.show-card').length).to.equal(2)
})
})
describe('Store', () => {
it('should bootstrap', () => {
const state = rootReducer(undefined, {type: '@@redux/INIT'})
expect(state).to.deep.equal({searchTerm: ''})
})
it('should handle setSearchTerm actions', () => {
const state = rootReducer({searchTerm: 'xyzzy'}, {type: 'setSearchTerm', value: 'plugh'})
expect(state).to.deep.equal({searchTerm: 'plugh'})
})
})
|
// All symbols in the `SignWriting` script as per Unicode v8.0.0:
[
'\uD836\uDC00',
'\uD836\uDC01',
'\uD836\uDC02',
'\uD836\uDC03',
'\uD836\uDC04',
'\uD836\uDC05',
'\uD836\uDC06',
'\uD836\uDC07',
'\uD836\uDC08',
'\uD836\uDC09',
'\uD836\uDC0A',
'\uD836\uDC0B',
'\uD836\uDC0C',
'\uD836\uDC0D',
'\uD836\uDC0E',
'\uD836\uDC0F',
'\uD836\uDC10',
'\uD836\uDC11',
'\uD836\uDC12',
'\uD836\uDC13',
'\uD836\uDC14',
'\uD836\uDC15',
'\uD836\uDC16',
'\uD836\uDC17',
'\uD836\uDC18',
'\uD836\uDC19',
'\uD836\uDC1A',
'\uD836\uDC1B',
'\uD836\uDC1C',
'\uD836\uDC1D',
'\uD836\uDC1E',
'\uD836\uDC1F',
'\uD836\uDC20',
'\uD836\uDC21',
'\uD836\uDC22',
'\uD836\uDC23',
'\uD836\uDC24',
'\uD836\uDC25',
'\uD836\uDC26',
'\uD836\uDC27',
'\uD836\uDC28',
'\uD836\uDC29',
'\uD836\uDC2A',
'\uD836\uDC2B',
'\uD836\uDC2C',
'\uD836\uDC2D',
'\uD836\uDC2E',
'\uD836\uDC2F',
'\uD836\uDC30',
'\uD836\uDC31',
'\uD836\uDC32',
'\uD836\uDC33',
'\uD836\uDC34',
'\uD836\uDC35',
'\uD836\uDC36',
'\uD836\uDC37',
'\uD836\uDC38',
'\uD836\uDC39',
'\uD836\uDC3A',
'\uD836\uDC3B',
'\uD836\uDC3C',
'\uD836\uDC3D',
'\uD836\uDC3E',
'\uD836\uDC3F',
'\uD836\uDC40',
'\uD836\uDC41',
'\uD836\uDC42',
'\uD836\uDC43',
'\uD836\uDC44',
'\uD836\uDC45',
'\uD836\uDC46',
'\uD836\uDC47',
'\uD836\uDC48',
'\uD836\uDC49',
'\uD836\uDC4A',
'\uD836\uDC4B',
'\uD836\uDC4C',
'\uD836\uDC4D',
'\uD836\uDC4E',
'\uD836\uDC4F',
'\uD836\uDC50',
'\uD836\uDC51',
'\uD836\uDC52',
'\uD836\uDC53',
'\uD836\uDC54',
'\uD836\uDC55',
'\uD836\uDC56',
'\uD836\uDC57',
'\uD836\uDC58',
'\uD836\uDC59',
'\uD836\uDC5A',
'\uD836\uDC5B',
'\uD836\uDC5C',
'\uD836\uDC5D',
'\uD836\uDC5E',
'\uD836\uDC5F',
'\uD836\uDC60',
'\uD836\uDC61',
'\uD836\uDC62',
'\uD836\uDC63',
'\uD836\uDC64',
'\uD836\uDC65',
'\uD836\uDC66',
'\uD836\uDC67',
'\uD836\uDC68',
'\uD836\uDC69',
'\uD836\uDC6A',
'\uD836\uDC6B',
'\uD836\uDC6C',
'\uD836\uDC6D',
'\uD836\uDC6E',
'\uD836\uDC6F',
'\uD836\uDC70',
'\uD836\uDC71',
'\uD836\uDC72',
'\uD836\uDC73',
'\uD836\uDC74',
'\uD836\uDC75',
'\uD836\uDC76',
'\uD836\uDC77',
'\uD836\uDC78',
'\uD836\uDC79',
'\uD836\uDC7A',
'\uD836\uDC7B',
'\uD836\uDC7C',
'\uD836\uDC7D',
'\uD836\uDC7E',
'\uD836\uDC7F',
'\uD836\uDC80',
'\uD836\uDC81',
'\uD836\uDC82',
'\uD836\uDC83',
'\uD836\uDC84',
'\uD836\uDC85',
'\uD836\uDC86',
'\uD836\uDC87',
'\uD836\uDC88',
'\uD836\uDC89',
'\uD836\uDC8A',
'\uD836\uDC8B',
'\uD836\uDC8C',
'\uD836\uDC8D',
'\uD836\uDC8E',
'\uD836\uDC8F',
'\uD836\uDC90',
'\uD836\uDC91',
'\uD836\uDC92',
'\uD836\uDC93',
'\uD836\uDC94',
'\uD836\uDC95',
'\uD836\uDC96',
'\uD836\uDC97',
'\uD836\uDC98',
'\uD836\uDC99',
'\uD836\uDC9A',
'\uD836\uDC9B',
'\uD836\uDC9C',
'\uD836\uDC9D',
'\uD836\uDC9E',
'\uD836\uDC9F',
'\uD836\uDCA0',
'\uD836\uDCA1',
'\uD836\uDCA2',
'\uD836\uDCA3',
'\uD836\uDCA4',
'\uD836\uDCA5',
'\uD836\uDCA6',
'\uD836\uDCA7',
'\uD836\uDCA8',
'\uD836\uDCA9',
'\uD836\uDCAA',
'\uD836\uDCAB',
'\uD836\uDCAC',
'\uD836\uDCAD',
'\uD836\uDCAE',
'\uD836\uDCAF',
'\uD836\uDCB0',
'\uD836\uDCB1',
'\uD836\uDCB2',
'\uD836\uDCB3',
'\uD836\uDCB4',
'\uD836\uDCB5',
'\uD836\uDCB6',
'\uD836\uDCB7',
'\uD836\uDCB8',
'\uD836\uDCB9',
'\uD836\uDCBA',
'\uD836\uDCBB',
'\uD836\uDCBC',
'\uD836\uDCBD',
'\uD836\uDCBE',
'\uD836\uDCBF',
'\uD836\uDCC0',
'\uD836\uDCC1',
'\uD836\uDCC2',
'\uD836\uDCC3',
'\uD836\uDCC4',
'\uD836\uDCC5',
'\uD836\uDCC6',
'\uD836\uDCC7',
'\uD836\uDCC8',
'\uD836\uDCC9',
'\uD836\uDCCA',
'\uD836\uDCCB',
'\uD836\uDCCC',
'\uD836\uDCCD',
'\uD836\uDCCE',
'\uD836\uDCCF',
'\uD836\uDCD0',
'\uD836\uDCD1',
'\uD836\uDCD2',
'\uD836\uDCD3',
'\uD836\uDCD4',
'\uD836\uDCD5',
'\uD836\uDCD6',
'\uD836\uDCD7',
'\uD836\uDCD8',
'\uD836\uDCD9',
'\uD836\uDCDA',
'\uD836\uDCDB',
'\uD836\uDCDC',
'\uD836\uDCDD',
'\uD836\uDCDE',
'\uD836\uDCDF',
'\uD836\uDCE0',
'\uD836\uDCE1',
'\uD836\uDCE2',
'\uD836\uDCE3',
'\uD836\uDCE4',
'\uD836\uDCE5',
'\uD836\uDCE6',
'\uD836\uDCE7',
'\uD836\uDCE8',
'\uD836\uDCE9',
'\uD836\uDCEA',
'\uD836\uDCEB',
'\uD836\uDCEC',
'\uD836\uDCED',
'\uD836\uDCEE',
'\uD836\uDCEF',
'\uD836\uDCF0',
'\uD836\uDCF1',
'\uD836\uDCF2',
'\uD836\uDCF3',
'\uD836\uDCF4',
'\uD836\uDCF5',
'\uD836\uDCF6',
'\uD836\uDCF7',
'\uD836\uDCF8',
'\uD836\uDCF9',
'\uD836\uDCFA',
'\uD836\uDCFB',
'\uD836\uDCFC',
'\uD836\uDCFD',
'\uD836\uDCFE',
'\uD836\uDCFF',
'\uD836\uDD00',
'\uD836\uDD01',
'\uD836\uDD02',
'\uD836\uDD03',
'\uD836\uDD04',
'\uD836\uDD05',
'\uD836\uDD06',
'\uD836\uDD07',
'\uD836\uDD08',
'\uD836\uDD09',
'\uD836\uDD0A',
'\uD836\uDD0B',
'\uD836\uDD0C',
'\uD836\uDD0D',
'\uD836\uDD0E',
'\uD836\uDD0F',
'\uD836\uDD10',
'\uD836\uDD11',
'\uD836\uDD12',
'\uD836\uDD13',
'\uD836\uDD14',
'\uD836\uDD15',
'\uD836\uDD16',
'\uD836\uDD17',
'\uD836\uDD18',
'\uD836\uDD19',
'\uD836\uDD1A',
'\uD836\uDD1B',
'\uD836\uDD1C',
'\uD836\uDD1D',
'\uD836\uDD1E',
'\uD836\uDD1F',
'\uD836\uDD20',
'\uD836\uDD21',
'\uD836\uDD22',
'\uD836\uDD23',
'\uD836\uDD24',
'\uD836\uDD25',
'\uD836\uDD26',
'\uD836\uDD27',
'\uD836\uDD28',
'\uD836\uDD29',
'\uD836\uDD2A',
'\uD836\uDD2B',
'\uD836\uDD2C',
'\uD836\uDD2D',
'\uD836\uDD2E',
'\uD836\uDD2F',
'\uD836\uDD30',
'\uD836\uDD31',
'\uD836\uDD32',
'\uD836\uDD33',
'\uD836\uDD34',
'\uD836\uDD35',
'\uD836\uDD36',
'\uD836\uDD37',
'\uD836\uDD38',
'\uD836\uDD39',
'\uD836\uDD3A',
'\uD836\uDD3B',
'\uD836\uDD3C',
'\uD836\uDD3D',
'\uD836\uDD3E',
'\uD836\uDD3F',
'\uD836\uDD40',
'\uD836\uDD41',
'\uD836\uDD42',
'\uD836\uDD43',
'\uD836\uDD44',
'\uD836\uDD45',
'\uD836\uDD46',
'\uD836\uDD47',
'\uD836\uDD48',
'\uD836\uDD49',
'\uD836\uDD4A',
'\uD836\uDD4B',
'\uD836\uDD4C',
'\uD836\uDD4D',
'\uD836\uDD4E',
'\uD836\uDD4F',
'\uD836\uDD50',
'\uD836\uDD51',
'\uD836\uDD52',
'\uD836\uDD53',
'\uD836\uDD54',
'\uD836\uDD55',
'\uD836\uDD56',
'\uD836\uDD57',
'\uD836\uDD58',
'\uD836\uDD59',
'\uD836\uDD5A',
'\uD836\uDD5B',
'\uD836\uDD5C',
'\uD836\uDD5D',
'\uD836\uDD5E',
'\uD836\uDD5F',
'\uD836\uDD60',
'\uD836\uDD61',
'\uD836\uDD62',
'\uD836\uDD63',
'\uD836\uDD64',
'\uD836\uDD65',
'\uD836\uDD66',
'\uD836\uDD67',
'\uD836\uDD68',
'\uD836\uDD69',
'\uD836\uDD6A',
'\uD836\uDD6B',
'\uD836\uDD6C',
'\uD836\uDD6D',
'\uD836\uDD6E',
'\uD836\uDD6F',
'\uD836\uDD70',
'\uD836\uDD71',
'\uD836\uDD72',
'\uD836\uDD73',
'\uD836\uDD74',
'\uD836\uDD75',
'\uD836\uDD76',
'\uD836\uDD77',
'\uD836\uDD78',
'\uD836\uDD79',
'\uD836\uDD7A',
'\uD836\uDD7B',
'\uD836\uDD7C',
'\uD836\uDD7D',
'\uD836\uDD7E',
'\uD836\uDD7F',
'\uD836\uDD80',
'\uD836\uDD81',
'\uD836\uDD82',
'\uD836\uDD83',
'\uD836\uDD84',
'\uD836\uDD85',
'\uD836\uDD86',
'\uD836\uDD87',
'\uD836\uDD88',
'\uD836\uDD89',
'\uD836\uDD8A',
'\uD836\uDD8B',
'\uD836\uDD8C',
'\uD836\uDD8D',
'\uD836\uDD8E',
'\uD836\uDD8F',
'\uD836\uDD90',
'\uD836\uDD91',
'\uD836\uDD92',
'\uD836\uDD93',
'\uD836\uDD94',
'\uD836\uDD95',
'\uD836\uDD96',
'\uD836\uDD97',
'\uD836\uDD98',
'\uD836\uDD99',
'\uD836\uDD9A',
'\uD836\uDD9B',
'\uD836\uDD9C',
'\uD836\uDD9D',
'\uD836\uDD9E',
'\uD836\uDD9F',
'\uD836\uDDA0',
'\uD836\uDDA1',
'\uD836\uDDA2',
'\uD836\uDDA3',
'\uD836\uDDA4',
'\uD836\uDDA5',
'\uD836\uDDA6',
'\uD836\uDDA7',
'\uD836\uDDA8',
'\uD836\uDDA9',
'\uD836\uDDAA',
'\uD836\uDDAB',
'\uD836\uDDAC',
'\uD836\uDDAD',
'\uD836\uDDAE',
'\uD836\uDDAF',
'\uD836\uDDB0',
'\uD836\uDDB1',
'\uD836\uDDB2',
'\uD836\uDDB3',
'\uD836\uDDB4',
'\uD836\uDDB5',
'\uD836\uDDB6',
'\uD836\uDDB7',
'\uD836\uDDB8',
'\uD836\uDDB9',
'\uD836\uDDBA',
'\uD836\uDDBB',
'\uD836\uDDBC',
'\uD836\uDDBD',
'\uD836\uDDBE',
'\uD836\uDDBF',
'\uD836\uDDC0',
'\uD836\uDDC1',
'\uD836\uDDC2',
'\uD836\uDDC3',
'\uD836\uDDC4',
'\uD836\uDDC5',
'\uD836\uDDC6',
'\uD836\uDDC7',
'\uD836\uDDC8',
'\uD836\uDDC9',
'\uD836\uDDCA',
'\uD836\uDDCB',
'\uD836\uDDCC',
'\uD836\uDDCD',
'\uD836\uDDCE',
'\uD836\uDDCF',
'\uD836\uDDD0',
'\uD836\uDDD1',
'\uD836\uDDD2',
'\uD836\uDDD3',
'\uD836\uDDD4',
'\uD836\uDDD5',
'\uD836\uDDD6',
'\uD836\uDDD7',
'\uD836\uDDD8',
'\uD836\uDDD9',
'\uD836\uDDDA',
'\uD836\uDDDB',
'\uD836\uDDDC',
'\uD836\uDDDD',
'\uD836\uDDDE',
'\uD836\uDDDF',
'\uD836\uDDE0',
'\uD836\uDDE1',
'\uD836\uDDE2',
'\uD836\uDDE3',
'\uD836\uDDE4',
'\uD836\uDDE5',
'\uD836\uDDE6',
'\uD836\uDDE7',
'\uD836\uDDE8',
'\uD836\uDDE9',
'\uD836\uDDEA',
'\uD836\uDDEB',
'\uD836\uDDEC',
'\uD836\uDDED',
'\uD836\uDDEE',
'\uD836\uDDEF',
'\uD836\uDDF0',
'\uD836\uDDF1',
'\uD836\uDDF2',
'\uD836\uDDF3',
'\uD836\uDDF4',
'\uD836\uDDF5',
'\uD836\uDDF6',
'\uD836\uDDF7',
'\uD836\uDDF8',
'\uD836\uDDF9',
'\uD836\uDDFA',
'\uD836\uDDFB',
'\uD836\uDDFC',
'\uD836\uDDFD',
'\uD836\uDDFE',
'\uD836\uDDFF',
'\uD836\uDE00',
'\uD836\uDE01',
'\uD836\uDE02',
'\uD836\uDE03',
'\uD836\uDE04',
'\uD836\uDE05',
'\uD836\uDE06',
'\uD836\uDE07',
'\uD836\uDE08',
'\uD836\uDE09',
'\uD836\uDE0A',
'\uD836\uDE0B',
'\uD836\uDE0C',
'\uD836\uDE0D',
'\uD836\uDE0E',
'\uD836\uDE0F',
'\uD836\uDE10',
'\uD836\uDE11',
'\uD836\uDE12',
'\uD836\uDE13',
'\uD836\uDE14',
'\uD836\uDE15',
'\uD836\uDE16',
'\uD836\uDE17',
'\uD836\uDE18',
'\uD836\uDE19',
'\uD836\uDE1A',
'\uD836\uDE1B',
'\uD836\uDE1C',
'\uD836\uDE1D',
'\uD836\uDE1E',
'\uD836\uDE1F',
'\uD836\uDE20',
'\uD836\uDE21',
'\uD836\uDE22',
'\uD836\uDE23',
'\uD836\uDE24',
'\uD836\uDE25',
'\uD836\uDE26',
'\uD836\uDE27',
'\uD836\uDE28',
'\uD836\uDE29',
'\uD836\uDE2A',
'\uD836\uDE2B',
'\uD836\uDE2C',
'\uD836\uDE2D',
'\uD836\uDE2E',
'\uD836\uDE2F',
'\uD836\uDE30',
'\uD836\uDE31',
'\uD836\uDE32',
'\uD836\uDE33',
'\uD836\uDE34',
'\uD836\uDE35',
'\uD836\uDE36',
'\uD836\uDE37',
'\uD836\uDE38',
'\uD836\uDE39',
'\uD836\uDE3A',
'\uD836\uDE3B',
'\uD836\uDE3C',
'\uD836\uDE3D',
'\uD836\uDE3E',
'\uD836\uDE3F',
'\uD836\uDE40',
'\uD836\uDE41',
'\uD836\uDE42',
'\uD836\uDE43',
'\uD836\uDE44',
'\uD836\uDE45',
'\uD836\uDE46',
'\uD836\uDE47',
'\uD836\uDE48',
'\uD836\uDE49',
'\uD836\uDE4A',
'\uD836\uDE4B',
'\uD836\uDE4C',
'\uD836\uDE4D',
'\uD836\uDE4E',
'\uD836\uDE4F',
'\uD836\uDE50',
'\uD836\uDE51',
'\uD836\uDE52',
'\uD836\uDE53',
'\uD836\uDE54',
'\uD836\uDE55',
'\uD836\uDE56',
'\uD836\uDE57',
'\uD836\uDE58',
'\uD836\uDE59',
'\uD836\uDE5A',
'\uD836\uDE5B',
'\uD836\uDE5C',
'\uD836\uDE5D',
'\uD836\uDE5E',
'\uD836\uDE5F',
'\uD836\uDE60',
'\uD836\uDE61',
'\uD836\uDE62',
'\uD836\uDE63',
'\uD836\uDE64',
'\uD836\uDE65',
'\uD836\uDE66',
'\uD836\uDE67',
'\uD836\uDE68',
'\uD836\uDE69',
'\uD836\uDE6A',
'\uD836\uDE6B',
'\uD836\uDE6C',
'\uD836\uDE6D',
'\uD836\uDE6E',
'\uD836\uDE6F',
'\uD836\uDE70',
'\uD836\uDE71',
'\uD836\uDE72',
'\uD836\uDE73',
'\uD836\uDE74',
'\uD836\uDE75',
'\uD836\uDE76',
'\uD836\uDE77',
'\uD836\uDE78',
'\uD836\uDE79',
'\uD836\uDE7A',
'\uD836\uDE7B',
'\uD836\uDE7C',
'\uD836\uDE7D',
'\uD836\uDE7E',
'\uD836\uDE7F',
'\uD836\uDE80',
'\uD836\uDE81',
'\uD836\uDE82',
'\uD836\uDE83',
'\uD836\uDE84',
'\uD836\uDE85',
'\uD836\uDE86',
'\uD836\uDE87',
'\uD836\uDE88',
'\uD836\uDE89',
'\uD836\uDE8A',
'\uD836\uDE8B',
'\uD836\uDE9B',
'\uD836\uDE9C',
'\uD836\uDE9D',
'\uD836\uDE9E',
'\uD836\uDE9F',
'\uD836\uDEA1',
'\uD836\uDEA2',
'\uD836\uDEA3',
'\uD836\uDEA4',
'\uD836\uDEA5',
'\uD836\uDEA6',
'\uD836\uDEA7',
'\uD836\uDEA8',
'\uD836\uDEA9',
'\uD836\uDEAA',
'\uD836\uDEAB',
'\uD836\uDEAC',
'\uD836\uDEAD',
'\uD836\uDEAE',
'\uD836\uDEAF'
]; |
if (a) { // Some comment
b(); } |
var testData = {
videoSrc: "http://www.youtube.com/watch/?v=nfGV32RNkhw",
expectedDuration: 151,
createMedia: function( id ) {
return Popcorn.HTMLYouTubeVideoElement( id );
},
// We need to test YouTube's URL params, which not all
// wrappers mimic. Do it as a set of tests specific
// to YouTube.
playerSpecificAsyncTests: function() {
asyncTest( "YouTube 01 - autoplay, loop params", 4, function() {
var video = testData.createMedia( "#video" );
video.addEventListener( "loadedmetadata", function onLoadedMetadata() {
video.removeEventListener( "loadedmetadata", onLoadedMetadata, false );
equal( video.autoplay, true, "autoplay is set via param" );
equal( video.loop, true, "loop is set via param" );
start();
}, false);
equal( video.autoplay, false, "autoplay is initially false" );
equal( video.loop, false, "loop is initially false" );
video.src = testData.videoSrc + "&autoplay=1&loop=1";
});
},
playerSpecificSyncTests: function() {
// Testing the id property inherited from MediaElementProto
test( "YouTube 01 - id property accessible on wrapper object", 1, function() {
var video = testData.createMedia( "#video" );
ok( video.id, "id property on wrapper object isn't null" );
});
// Testing the style property inherited from MediaElementProto
test( "YouTube 02 - style property accessible on wrapper object", 1, function() {
var video = testData.createMedia( "#video" );
ok( video.style, "Style property on wrapper object isn't null" );
});
test( "YouTube 03 - _canPlaySrc", 6, function() {
ok( Popcorn.HTMLYouTubeVideoElement._canPlaySrc( "http://youtube.com/watch/v/6v3jsVivU6U?format=json" ), "youtube can play url in this format: http://youtube.com/watch/v/6v3jsVivU6U?format=json" );
ok( Popcorn.HTMLYouTubeVideoElement._canPlaySrc( "http://www.youtube.com/v/M3r2XDceM6A&fs=1" ), "youtube can play url in this format: http://www.youtube.com/v/M3r2XDceM6A&fs=1" );
ok( Popcorn.HTMLYouTubeVideoElement._canPlaySrc( "youtube.com/v/M3r2XDceM6A&fs=1" ), "youtube can play url in this format: youtube.com/v/M3r2XDceM6A&fs=1" );
ok( Popcorn.HTMLYouTubeVideoElement._canPlaySrc( "www.youtube.com/v/M3r2XDceM6A&fs=1" ), "youtube can play url in this format: www.youtube.com/v/M3r2XDceM6A&fs=1" );
ok( !Popcorn.HTMLYouTubeVideoElement._canPlaySrc( "http://www.youtube.com" ), "Youtube can't play http://www.youtube.com without a video id" );
ok( !Popcorn.HTMLYouTubeVideoElement._canPlaySrc( "www.youtube.com" ), "Youtube can't play www.youtube.com without a video id" );
start();
});
test( "YouTube 04 - property getters for parent style height/width", 2, function() {
var video = testData.createMedia( "#video" );
equal( video.width, 360, "Returned expected parent element width" );
equal( video.height, 300, "Returned expected parent element height" );
});
asyncTest( "YouTube 05 - buffered", function() {
var video = testData.createMedia( "#video" ),
buffered = video.buffered;
video.addEventListener( "progress", function onProgress() {
var end = buffered.end( 0 );
equal( buffered.start( 0 ), 0, "video.buffered range start is always 0" );
if ( end > 0 ) {
ok( true, "buffered.end( 0 ) " + end + " > 0 on progress" );
video.removeEventListener( "progress", onProgress, false );
start();
} else {
ok( end >= 0, "buffered.end( 0 ): " + end + " >= 0 on progress" );
}
}, false);
video.src = testData.videoSrc + "&autoplay=1&loop=1";
ok( buffered && typeof buffered === "object", "video.buffered exists" );
equal( buffered.length, 1, "video.buffered.length === 1" );
equal( buffered.start( 0 ), 0, "video.buffered range start is always 0" );
equal( buffered.end( 0 ), 0, "video.buffered range end is 0" );
try {
buffered.start( 1 );
ok( false, "selecting a time range > 0 should throw an error" );
} catch ( e ) {
ok( e, "selecting a time range > 0 throws an error" );
}
});
asyncTest( "YouTube 06 - source changes", 2, function() {
var video = testData.createMedia( "#video" );
video.addEventListener( "loadedmetadata", function loadedmetadata() {
ok( true, "first source ready event is fired" );
video.removeEventListener( "loadedmetadata", loadedmetadata, false );
video.addEventListener( "loadedmetadata", function() {
ok( true, "second source ready event is fired" );
start();
}, false );
video.src = "http://www.youtube.com/watch?v=HMnyrTe-j6U&autoplay=1&loop=1";
}, false );
video.src = testData.videoSrc + "&autoplay=1&loop=1";
});
}
};
// YouTube tends to fail when the iframes live in the qunit-fixture
// div. Simulate the same effect by deleting all iframes under #video
// after each test ends.
var qunitStart = start;
start = function() {
// Give the video time to finish loading so callbacks don't throw
setTimeout( function() {
qunitStart();
var video = document.querySelector( "#video" );
while( video.hasChildNodes() ) {
video.removeChild( video.lastChild );
}
}, 500 );
};
|
const path = require('path');
const apiSpecAliases = require('../lib/apiSpecExportTools').coreAliases();
const babelConfig = require('../.babelrc.js');
const moduleNameMapper = {
'^testUtils$': path.resolve(__dirname, './testUtils'),
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': path.resolve(
__dirname,
'./fileMock.js'
),
};
Object.keys(apiSpecAliases).forEach(key => {
moduleNameMapper['^' + key.replace(/\\./g, '\\.') + '$'] = apiSpecAliases[key];
});
module.exports = {
globals: {
__kolibriModuleName: 'testmodule',
__version: 'testversion',
__copyrightYear: '2018',
'vue-jest': {
babelConfig,
},
},
rootDir: path.resolve(process.cwd()),
moduleFileExtensions: ['js', 'json', 'vue'],
moduleNameMapper,
testURL: 'http://kolibri.time',
transform: {
'^.+\\.js$': path.resolve(__dirname, './babel-jest-transform'),
'^.+\\.vue$': 'vue-jest',
},
transformIgnorePatterns: ['/node_modules/(?!(kolibri-tools|kolibri)/).*/'],
snapshotSerializers: ['jest-serializer-vue'],
setupFilesAfterEnv: [path.resolve(__dirname, './setup')],
coverageDirectory: '<rootDir>/coverage',
verbose: false,
};
|
angular
.module('climAngularApp', []);
angular
.module('climAngularApp')
.controller("ClimAngularCtrl", ClimAngularCtrl);
// La función controladora se crea con nombre de maner independiente
// En lugar de programarla inline dentro del constructor del controlador
function ClimAngularCtrl($http) {
// Esta función necesita una dependencia y la declara como un parametro
// AngularJS se encarga de instaciar y proveer los parámetros necesarios
// En este caso es $http que es un servicio includo en el paquete básico
var vm = this;
vm.city_list = [];
// El array de valores que se enlaza al desplegable generado con ng-options
vm.countries = [
{
name: 'Argentina',
code: 'AR'
},
{
name: 'Brasil',
code: 'BR'
},
{
name: 'España',
code: 'ES'
},
{
name: 'Portugal',
code: 'PT'
}];
// Las funciones pueden, y deben, definirse con su nombre, y publicarlas a través del viewmodel
vm.add_city = addCity;
function addCity() {
var city = {
city_name: vm.city_name,
country_code: vm.country_code
}
var baseurl = "http://api.openweathermap.org/data/2.5/weather?q=";
var jsonp = "&units=metric&callback=JSON_CALLBACK";
var url = baseurl + city.city_name + ',' + city.country_code + jsonp
// Uso del servicio de $http para hacer una llamada, en este caso JSONP
// $http devuleve promesas y debemos proveerle de callbacks para cuando se resuelvan
$http
.jsonp(url)
.success(fillWeatherAndPushCity);
// funcion callback que se ejcuta cuando responda openweathermap
function fillWeatherAndPushCity(weatherData) {
city.weather = weatherData
// AngularJS usando el ng-repeat agregará una ciudad y su clima a la interfaz
vm.city_list.push(city);
}
};
} |
import Route from '@ember/routing/route';
export default Route.extend({
model() {
return this.store.createRecord('fake-model');
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.