text
stringlengths 2
6.14k
|
|---|
module.exports = {
entry: __dirname + "/src/videocontext.js",
devtool: "source-map",
output: {
path: __dirname+'/dist',
filename: "videocontext.commonjs2.js",
libraryTarget: "commonjs2",
library: "VideoContext"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" },
{ test: /\.js$/, exclude: /node_modules/, loaders: ["babel-loader", "eslint-loader"]}
]
}
};
|
var jsface = require('jsface');
var packageVersion = require('../../package.json').version;
/**
* @name Globals
* @namespace
* @classdesc Globals to be used throught Newman.
*/
var Globals = jsface.Class({
$singleton: true,
newmanVersion: packageVersion,
/**
* Used to add the Globals used through out the app
* @param {Object} requestJSON Request JSON.
* @param {Object} options Newman Options.
*/
addEnvironmentGlobals: function (requestJSON, options) {
this.requestJSON = requestJSON;
this.envJson = options.envJson || {};
this.iterationNumber = 1;
this.outputFile = options.outputFile || '';
this.outputFileVerbose = options.outputFileVerbose || '';
this.testReportFile = options.testReportFile || '';
this.globalJson = options.globalJSON || [];
this.dataJson = [];
this.stopOnError = options.stopOnError;
this.noColor = options.noColor;
this.asLibrary = options.asLibrary;
this.strictSSL = options.strictSSL || true;
this.exitCode = 0;
this.updateMessage = "";
this.folder = options.folderName || false;
this.iterationCount = options.iterationCount || 1;
this.html = options.html || false;
this.responseEncoding = options.responseEncoding;
this.avoidRedirects = options.avoidRedirects;
this.whiteScreen = options.whiteScreen;
this.recurseLimit = 10;
if (typeof options.recurseLimit !== "undefined") {
this.recurseLimit = options.recurseLimit;
}
}
});
module.exports = Globals;
|
'use strict';
/**
* Module dependencies.
*/
const path = require('path');
const extend = require('util')._extend;
const development = require('./env/development');
const test = require('./env/test');
const production = require('./env/production');
const notifier = {
service: 'postmark',
APN: false,
email: true, // true
actions: ['comment'],
tplPath: path.join(__dirname, '..', 'app/mailer/templates'),
key: 'POSTMARK_KEY'
};
const defaults = {
root: path.join(__dirname, '..'),
notifier: notifier
};
/**
* Expose
*/
module.exports = {
development: extend(development, defaults),
test: extend(test, defaults),
production: extend(production, defaults)
}[process.env.NODE_ENV || 'development'];
|
/*
All functions related to creating a Slider item.
*/
var slideCount = 1;
// SETTER
function addSlide() {
slideCount++;
}
// GETTER
function getSlide() {
return(slideCount);
}
// Adds the Slider as well as the 'Edit' and 'delete' buttons.
function slider() {
var node = document.createElement("LI");
node.setAttribute('class', 'base');
var x = document.createElement("DIV");
x.setAttribute('class', 'slideStuff');
var slideName = "slider_" + String(getSlide());
addSlide();
x.setAttribute('id', slideName);
var y = document.createElement('button');
y.setAttribute('content', 'test content');
y.setAttribute('class', 'properties');
y.innerHTML = 'Edit';
var z = document.createElement('button');
z.setAttribute('class', 'delete');
z.innerHTML = 'x';
node.appendChild(x);
node.appendChild(y);
node.appendChild(z);
var tabID = String(getSelectedTabId());
var tabContID = document.getElementById(tabID).children[0].id;
document.getElementById(tabContID).appendChild(node);
$(function() {
$( ".slideStuff" ).slider();
});
var active = $("#tabs .ui-tabs-panel:visible").attr("id");
var test = document.getElementById(active).getElementsByClassName("fieldClass");
if(test.length > 0) {
remake();
}
}
//Is called when the Edit button is clicked. Creates the appropriate Properties.
function slideProps(myValue) {
document.getElementById("list_3").innerHTML = "";
var linebreak = document.createElement('br');
//Properties Title
var node = document.createElement("LI");
var x = document.createTextNode("Slider");
var el_span = document.createElement('span');
el_span.setAttribute('class', 'propLabel');
el_span.appendChild(x);
node.appendChild(el_span);
document.getElementById("list_3").appendChild(node);
//Textbox for Label change.
var node2 = document.createElement("LI");
var label = document.createTextNode("Label: ");
var y = document.createElement('input');
y.setAttribute('type', 'text');
y.setAttribute('id', 'selector');
var elem = document.getElementById(myValue).parentNode;
var name = "";
var node = elem.childNodes[3];
if (typeof node !== 'undefined') {
if(node.nodeType == 3) {
name = String(node.data);
}
}
if(name != "") {
y.setAttribute('value', name);
}
y.addEventListener("change", function() {
setValues(myValue, y);
});
function setValues(myVal, y) {
var sturf = document.createTextNode(String(y.value));
var searching = document.getElementById(myVal).parentNode;
if(searching.lastChild.nodeType == 3) {
searching.lastChild.remove();
}
document.getElementById(myVal).parentNode.appendChild(sturf);
}
node2.appendChild(label);
node2.appendChild(y);
document.getElementById("list_3").appendChild(node2);
}
|
/*************************************************************
*
* MathJax/fonts/HTML-CSS/TeX/png/Main/Regular/SuppMathOperators.js
*
* Defines the image size data needed for the HTML-CSS OutputJax
* to display mathematics using fallback images when the fonts
* are not available to the client browser.
*
* ---------------------------------------------------------------------
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.OutputJax["HTML-CSS"].defineImageData({
MathJax_Main: {
0x2a3f: [
// AMALGAMATION OR COPRODUCT
[5, 5, 0],
[6, 6, 0],
[8, 7, 0],
[9, 9, 0],
[10, 10, 0],
[12, 12, 0],
[15, 14, 0],
[17, 16, 0],
[20, 19, 0],
[24, 23, 0],
[29, 27, 0],
[34, 32, 0],
[40, 38, 0],
[48, 45, 0]
],
0x2aaf: [
// PRECEDES ABOVE SINGLE-LINE EQUALS SIGN
[5, 6, 1],
[6, 7, 1],
[7, 9, 2],
[9, 10, 2],
[10, 11, 2],
[12, 14, 3],
[14, 16, 3],
[17, 18, 3],
[20, 22, 4],
[23, 26, 5],
[28, 31, 6],
[33, 37, 7],
[39, 44, 8],
[46, 52, 10]
],
0x2ab0: [
// SUCCEEDS ABOVE SINGLE-LINE EQUALS SIGN
[5, 6, 1],
[6, 7, 1],
[7, 9, 2],
[9, 10, 2],
[10, 11, 2],
[12, 14, 3],
[14, 16, 3],
[17, 19, 4],
[20, 22, 4],
[23, 26, 5],
[28, 31, 6],
[33, 37, 7],
[39, 44, 8],
[46, 52, 10]
]
}
});
MathJax.Ajax.loadComplete(
MathJax.OutputJax["HTML-CSS"].imgDir +
"/Main/Regular" +
MathJax.OutputJax["HTML-CSS"].imgPacked +
"/SuppMathOperators.js"
);
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var randu = require( '@stdlib/random/base/randu' );
var cdf = require( './../lib' );
var alpha;
var beta;
var x;
var y;
var i;
for ( i = 0; i < 10; i++ ) {
x = randu() * 3.0;
alpha = randu() * 5.0;
beta = randu() * 5.0;
y = cdf( x, alpha, beta );
console.log( 'x: %d, α: %d, β: %d, F(x;α,β): %d', x.toFixed( 4 ), alpha.toFixed( 4 ), beta.toFixed( 4 ), y.toFixed( 4 ) );
}
|
//src: test/specs/fixtures/whitespace.tag
riot.tag2('my-tag', '<div style=" top:0; left:0" a=" " expr="{{ foo:\'bar\', bar:⁗\'⁗ }}"> Foo\' </div> <p></p>', 'p { display: none; }', 'style=" top:0; left:0" a=" " expr="{{ foo:⁗bar⁗ }}"', function(opts) {
this.click = function(e)
{}.bind(this)
});
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import './styles/ColumnView.scss';
import prefixClass from './utils/prefixClass';
import icBEM from './utils/icBEM';
export const COMPONENT_NAME = prefixClass('column-view');
const ROOT_BEM = icBEM(COMPONENT_NAME);
export const BEM = {
root: ROOT_BEM,
header: ROOT_BEM.element('header'),
body: ROOT_BEM.element('body'),
footer: ROOT_BEM.element('footer'),
};
export default function ColumnView({
header,
footer,
flexBody,
bodyPadding,
// React props
className,
headerRef,
bodyRef,
footerRef,
children,
...wrapperProps
}) {
const rootClassName = classNames(`${BEM.root}`, className);
const bodyClassName = BEM.body.modifier('flex', flexBody);
const bodyStyle = {
paddingTop: bodyPadding.top,
paddingBottom: bodyPadding.bottom,
paddingLeft: bodyPadding.left,
paddingRight: bodyPadding.right,
};
return (
<div
className={rootClassName}
{...wrapperProps}
>
{header && (
<div
className={`${BEM.header}`}
ref={headerRef}
>
{header}
</div>
)}
<div
className={`${bodyClassName}`}
style={bodyStyle}
ref={bodyRef}
>
{children}
</div>
{footer && (
<div
className={`${BEM.footer}`}
ref={footerRef}
>
{footer}
</div>
)}
</div>
);
}
ColumnView.propTypes = {
header: PropTypes.node,
footer: PropTypes.node,
flexBody: PropTypes.bool,
bodyPadding: PropTypes.shape({
top: PropTypes.number,
bottom: PropTypes.number,
left: PropTypes.number,
right: PropTypes.number,
}),
// eslint-disable-next-line react/forbid-prop-types
headerRef: PropTypes.any,
// eslint-disable-next-line react/forbid-prop-types
bodyRef: PropTypes.any,
// eslint-disable-next-line react/forbid-prop-types
footerRef: PropTypes.any,
};
ColumnView.defaultProps = {
header: undefined,
footer: undefined,
flexBody: false,
bodyPadding: { bottom: 24 },
headerRef: undefined,
bodyRef: undefined,
footerRef: undefined,
};
|
//= require jquery
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree .
|
import Check from "../../Core/Check.js";
import Cesium3DTilesInspector from "../Cesium3DTilesInspector/Cesium3DTilesInspector.js";
/**
* A mixin which adds the {@link Cesium3DTilesInspector} widget to the {@link Viewer} widget.
* Rather than being called directly, this function is normally passed as
* a parameter to {@link Viewer#extend}, as shown in the example below.
* @exports viewerCesium3DTilesInspectorMixin
*
* @param {Viewer} viewer The viewer instance.
*
* @example
* var viewer = new Cesium.Viewer('cesiumContainer');
* viewer.extend(Cesium.viewerCesium3DTilesInspectorMixin);
*/
function viewerCesium3DTilesInspectorMixin(viewer) {
//>>includeStart('debug', pragmas.debug);
Check.typeOf.object("viewer", viewer);
//>>includeEnd('debug');
var container = document.createElement("div");
container.className = "cesium-viewer-cesium3DTilesInspectorContainer";
viewer.container.appendChild(container);
var cesium3DTilesInspector = new Cesium3DTilesInspector(
container,
viewer.scene
);
Object.defineProperties(viewer, {
cesium3DTilesInspector: {
get: function () {
return cesium3DTilesInspector;
},
},
});
}
export default viewerCesium3DTilesInspectorMixin;
|
// @ts-nocheck
'use strict';
const _ = require('lodash');
const isStandardSyntaxAtRule = require('../../utils/isStandardSyntaxAtRule');
const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const validateOptions = require('../../utils/validateOptions');
const vendor = require('../../utils/vendor');
const ruleName = 'at-rule-whitelist';
const messages = ruleMessages(ruleName, {
rejected: (name) => `Unexpected at-rule "${name}"`,
});
function rule(listInput) {
// To allow for just a string as a parameter (not only arrays of strings)
const list = [].concat(listInput);
return (root, result) => {
const validOptions = validateOptions(result, ruleName, {
actual: list,
possible: [_.isString],
});
if (!validOptions) {
return;
}
result.warn(`'${ruleName}' has been deprecated. Instead use 'at-rule-allowed-list'.`, {
stylelintType: 'deprecation',
stylelintReference: `https://github.com/stylelint/stylelint/blob/13.7.0/lib/rules/${ruleName}/README.md`,
});
root.walkAtRules((atRule) => {
const name = atRule.name;
if (!isStandardSyntaxAtRule(atRule)) {
return;
}
if (list.includes(vendor.unprefixed(name).toLowerCase())) {
return;
}
report({
message: messages.rejected(name),
node: atRule,
result,
ruleName,
});
});
};
}
rule.primaryOptionArray = true;
rule.ruleName = ruleName;
rule.messages = messages;
rule.meta = { deprecated: true };
module.exports = rule;
|
//// [lastPropertyInLiteralWins.ts]
interface Thing {
thunk: (str: string) => void;
}
function test(thing: Thing) {
thing.thunk("str");
}
test({ // Should error, as last one wins, and is wrong type
thunk: (str: string) => {},
thunk: (num: number) => {}
});
test({ // Should be OK. Last 'thunk' is of correct type
thunk: (num: number) => {},
thunk: (str: string) => {}
});
//// [lastPropertyInLiteralWins.js]
function test(thing) {
thing.thunk("str");
}
test({
thunk: function (str) { },
thunk: function (num) { }
});
test({
thunk: function (num) { },
thunk: function (str) { }
});
|
import React from 'react';
import { PropTypes } from 'prop-types';
import timezones from '../../data/timezones';
import map from 'lodash/map';
import classnames from 'classnames';
import validateInput from '../../validations/signup';
import TextFieldGroup from '../Form/TextFieldGroup';
import signUp from '../../utils/signupActions';
import flashM from '../../utils/flashMessages';
class SignupForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
email: '',
password: '',
passwordConfirmation: '',
timezone: '',
errors: {},
isLoading: false,
invalid: false
}
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.checkUserExists = this.checkUserExists.bind(this);
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
isValid() {
const { errors, isValid } = validateInput(this.state);
if (!isValid) {
this.setState({ errors });
}
return isValid;
}
checkUserExists(e) {
const field = e.target.name;
const val = e.target.value;
if (val !== '') {
// this.props.isUserExists(val).then(res => {
signUp.isUserExists(val).then(res => {
let errors = this.state.errors;
let invalid;
if (res.data.user) {
errors[field] = 'There is user with such ' + field;
invalid = true;
} else {
errors[field] = '';
invalid = false;
}
this.setState({ errors, invalid });
});
}
}
onSubmit(e) {
e.preventDefault();
if (this.isValid()) {
this.setState({ errors: {}, isLoading: true });
// console.log("Here is this.props.userSignupRequest:");
// console.log(this.props.userSignupRequest);
// console.log(this.state);
// this.props.userSignupRequest(this.state).then(
signUp.userSignupRequest(this.state).then(
() => {
// this.props.addFlashMessage({
flashM.addFlashMessage({
type: 'success',
text: 'You signed up successfully. Welcome!'
});
this.context.router.history.push('/');
},
(err) => this.setState({ errors: err.response.data, isLoading: false })
);
}
}
render() {
const { errors } = this.state;
const options = map(timezones, (val, key) =>
<option key={val} value={val}>{key}</option>
);
return (
<form onSubmit={this.onSubmit}>
<h1>Sign up now and become a pantry raider!</h1>
<TextFieldGroup
error={errors.username}
label="Username"
onChange={this.onChange}
checkUserExists={this.checkUserExists}
value={this.state.username}
field="username"
/>
<TextFieldGroup
error={errors.email}
label="Email"
onChange={this.onChange}
checkUserExists={this.checkUserExists}
value={this.state.email}
field="email"
/>
<TextFieldGroup
error={errors.password}
label="Password"
onChange={this.onChange}
value={this.state.password}
field="password"
type="password"
/>
<TextFieldGroup
error={errors.passwordConfirmation}
label="Password Confirmation"
onChange={this.onChange}
value={this.state.passwordConfirmation}
field="passwordConfirmation"
type="password"
/>
<div className={classnames("form-group", { 'has-error': errors.timezone })}>
<label className="control-label">Timezone</label>
<select
className="form-control"
name="timezone"
onChange={this.onChange}
value={this.state.timezone}
>
<option value="" disabled>Choose Your Timezone</option>
{options}
</select>
{errors.timezone && <span className="help-block">{errors.timezone}</span>}
</div>
<div className="form-group">
<button disabled={this.state.isLoading || this.state.invalid} className="btn btn-primary btn-lg">
Sign up
</button>
</div>
</form>
);
}
}
SignupForm.propTypes = {
userSignupRequest: PropTypes.func.isRequired,
addFlashMessage: PropTypes.func.isRequired,
isUserExists: PropTypes.func.isRequired
}
SignupForm.contextTypes = {
router: PropTypes.object.isRequired
}
export default SignupForm;
|
// Test query stage merge sorting.
t = db.stages_mergesort;
t.drop();
var collname = "stages_mergesort";
var N = 10;
for (var i = 0; i < N; ++i) {
t.insert({foo: 1, bar: N - i - 1});
t.insert({baz: 1, bar: i});
}
t.ensureIndex({foo: 1, bar: 1});
t.ensureIndex({baz: 1, bar: 1});
// foo == 1
// We would (internally) use "": MinKey and "": MaxKey for the bar index bounds.
ixscan1 = {
ixscan: {
args: {
keyPattern: {foo: 1, bar: 1},
startKey: {foo: 1, bar: 0},
endKey: {foo: 1, bar: 100000},
startKeyInclusive: true,
endKeyInclusive: true,
direction: 1
}
}
};
// baz == 1
ixscan2 = {
ixscan: {
args: {
keyPattern: {baz: 1, bar: 1},
startKey: {baz: 1, bar: 0},
endKey: {baz: 1, bar: 100000},
startKeyInclusive: true,
endKeyInclusive: true,
direction: 1
}
}
};
mergesort = {
mergeSort: {args: {nodes: [ixscan1, ixscan2], pattern: {bar: 1}}}
};
res = db.runCommand({stageDebug: {plan: mergesort, collection: collname}});
assert.eq(res.ok, 1);
assert.eq(res.results.length, 2 * N);
assert.eq(res.results[0].bar, 0);
assert.eq(res.results[2 * N - 1].bar, N - 1);
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
/* Test DVS - test driver and function exerciser for Designated Veifier Signature API Functions */
var chai = require('chai');
var CTX = require("../index");
pf_curves = ["BN254", "BN254CX", "BLS383"];
var expect = chai.expect;
for (var i = pf_curves.length - 1; i >= 0; i--) {
var ctx = new CTX(pf_curves[i]);
describe('TEST DVS ' + pf_curves[i], function() {
var rng = new ctx.RAND();
var sha = ctx.MPIN.HASH_TYPE;
before(function(done) {
var RAW = [];
rng.clean();
for (i = 0; i < 100; i++) RAW[i] = i;
rng.seed(100, RAW);
done();
});
it('test Good Signature', function(done) {
this.timeout(0);
var res;
var S = [];
var SST = [];
var TOKEN = [];
var SEC = [];
var xID = [];
var X = [];
var Y1 = [];
var Y2 = [];
var Z = [];
var Pa = [];
var U = [];
/* Trusted Authority set-up */
ctx.MPIN.RANDOM_GENERATE(rng, S);
/* Create Client Identity */
var IDstr = "testuser@miracl.com";
var CLIENT_ID = ctx.MPIN.stringtobytes(IDstr);
/* Generate ctx.RANDom public key and z */
res = ctx.MPIN.GET_DVS_KEYPAIR(rng, Z, Pa);
expect(res).to.be.equal(0);
/* Append Pa to ID */
for (var i = 0; i < Pa.length; i++)
CLIENT_ID.push(Pa[i]);
/* Hash Client ID */
HCID = ctx.MPIN.HASH_ID(sha, CLIENT_ID);
/* Client and Server are issued secrets by DTA */
ctx.MPIN.GET_SERVER_SECRET(S, SST);
ctx.MPIN.GET_CLIENT_SECRET(S, HCID, TOKEN);
/* Compute client secret for key escrow less scheme z.CS */
res = ctx.MPIN.GET_G1_MULTIPLE(null, 0, Z, TOKEN, TOKEN);
expect(res).to.be.equal(0);
/* Client extracts PIN from secret to create Token */
var pin = 1234;
res = ctx.MPIN.EXTRACT_PIN(sha, CLIENT_ID, pin, TOKEN);
expect(res).to.be.equal(0);
var date = 0;
var timeValue = ctx.MPIN.GET_TIME();
var message = "Message to sign";
res = ctx.MPIN.CLIENT(sha, 0, CLIENT_ID, rng, X, pin, TOKEN, SEC, U, null, null, timeValue, Y1, message);
expect(res).to.be.equal(0);
/* Server */
res = ctx.MPIN.SERVER(sha, 0, xID, null, Y2, SST, U, null, SEC, null, null, CLIENT_ID, timeValue, message, Pa);
expect(res).to.be.equal(0);
done();
});
it('test Bad Signature', function(done) {
this.timeout(0);
var res;
var S = [];
var SST = [];
var TOKEN = [];
var SEC = [];
var xID = [];
var X = [];
var Y1 = [];
var Y2 = [];
var Z1 = [];
var Z2 = [];
var Pa1 = [];
var Pa2 = [];
var U = [];
/* Trusted Authority set-up */
ctx.MPIN.RANDOM_GENERATE(rng, S);
/* Create Client Identity */
var IDstr = "testuser@miracl.com";
var CLIENT_ID = ctx.MPIN.stringtobytes(IDstr);
/* Generate ctx.RANDom public key and z */
res = ctx.MPIN.GET_DVS_KEYPAIR(rng, Z1, Pa1);
expect(res).to.be.equal(0);
/* Generate ctx.RANDom public key and z */
res = ctx.MPIN.GET_DVS_KEYPAIR(rng, Z2, Pa2);
expect(res).to.be.equal(0);
/* Append Pa1 to ID */
for (var i = 0; i < Pa1.length; i++)
CLIENT_ID.push(Pa1[i]);
/* Hash Client ID */
HCID = ctx.MPIN.HASH_ID(sha, CLIENT_ID);
/* Client and Server are issued secrets by DTA */
ctx.MPIN.GET_SERVER_SECRET(S, SST);
ctx.MPIN.GET_CLIENT_SECRET(S, HCID, TOKEN);
/* Compute client secret for key escrow less scheme z.CS */
res = ctx.MPIN.GET_G1_MULTIPLE(null, 0, Z1, TOKEN, TOKEN);
expect(res).to.be.equal(0);
/* Client extracts PIN from secret to create Token */
var pin = 1234;
res = ctx.MPIN.EXTRACT_PIN(sha, CLIENT_ID, pin, TOKEN);
expect(res).to.be.equal(0);
var date = 0;
var timeValue = ctx.MPIN.GET_TIME();
var message = "Message to sign";
res = ctx.MPIN.CLIENT(sha, 0, CLIENT_ID, rng, X, pin, TOKEN, SEC, U, null, null, timeValue, Y1, message);
expect(res).to.be.equal(0);
/* Server */
res = ctx.MPIN.SERVER(sha, 0, xID, null, Y2, SST, U, null, SEC, null, null, CLIENT_ID, timeValue, message, Pa2);
expect(res).to.be.equal(ctx.MPIN.BAD_PIN);
done();
});
});
}
|
import React from 'react';
import { connect } from 'react-redux';
import settings from 'settings';
import Rezponsive from 'rezponsive';
import ShareButtons from 'components/ShareButtons';
import openShareWindow from 'helpers/sharing/openShareWindow';
import filterShareButtonsForTouch from 'helpers/sharing/filterShareButtonsForTouch';
import generateShareButtons from 'helpers/sharing/generateShareButtons';
import getPetitionURL from 'helpers/getPetitionURL';
const SharePetitionContainer = ({ openPopup, buttons, isTouch, petitionURL }) => (
<ShareButtons
openPopup={openPopup}
buttons={filterShareButtonsForTouch(buttons, isTouch)}
petitionURL={petitionURL}
/>
);
const mapStateToProps = ({ petition }) => ({
openPopup: (url, event) => openShareWindow(url, event, settings.shareButtons.popupTitle),
buttons: generateShareButtons(petition),
petitionURL: getPetitionURL(petition.id)
});
SharePetitionContainer.propTypes = {
openPopup: React.PropTypes.func,
buttons: React.PropTypes.array
};
export default connect(
mapStateToProps
)(Rezponsive(SharePetitionContainer));
|
'use strict';
var _ = require('underscore');
var inspect = require(global.OSYNC_UTILS + 'inspect');
var logUtil = require(global.OSYNC_UTILS + 'log');
var JdsClient = require(global.OSYNC_SUBSYSTEMS + 'jds/jds-client');
function JobStatusUpdater(setLog, setConfig, jdsClient) {
if (!(this instanceof JobStatusUpdater)) {
return new JobStatusUpdater(setLog, setConfig, jdsClient);
}
this.jdsClient = jdsClient || new JdsClient(setLog, setConfig);
this.log = logUtil.getAsChild('JobStatusUpdater', setLog);
// this.log = require('bunyan').createLogger({
// name: 'JobStatusUpdater',
// level: 'debug'
// });
this.config = setConfig;
}
JobStatusUpdater.prototype.writeStatus = function(jobState, callback) {
var self = this;
jobState.timestamp = Date.now().toString();
if (_.isUndefined(jobState.rootJobId)) {
jobState.rootJobId = jobState.jobId;
}
if (_.isUndefined(jobState.jpid) || _.isUndefined(jobState.rootJobId)) {
self.log.debug('JobStatusUpdater.writeStatus: No jpid or rootJobId');
return callback(null, 'no job state for jobs not started by a user');
}
if (!_.isUndefined(jobState.record) || !_.isUndefined(jobState['event-uid'])) {
self.log.debug('JobStatusUpdater.writeStatus: Job has a record, covered by metastamp, don\'t record job state');
return callback(null, 'record job');
}
return callback();
//self.jdsClient.saveJobState(jobState, function(error, response, result) {
// self.log.debug('JobStatusUpdater.writeStatus: Response from saveJobState: error: %s, response: %j, result: %j', error, response, result);
// if (error) {
// self.log.debug('JobStatusUpdater.writeStatus: An error occurred. error: %s; response: %j; result: %j', error, response, result);
// return callback(error, response, result);
// }
// if ((response) && (response.statusCode !== 200)) {
// self.log.error('JobStatusUpdater.writeStatus: Response status code was not correct. error: %s; response: %j; result: %j', error, response, result);
// }
// return callback(error, response, jobState);
//});
};
JobStatusUpdater.prototype.errorJobStatus = function(job, error, callback) {
var self = this;
job.status = 'error';
job.error = error;
self.log.debug(inspect(job));
this.writeStatus(job, callback);
};
JobStatusUpdater.prototype.createJobStatus = function(job, callback) {
var self = this;
job.status = 'created';
self.log.debug(inspect(job));
this.writeStatus(job, callback);
};
JobStatusUpdater.prototype.startJobStatus = function(job, callback) {
var self = this;
job.status = 'started';
self.log.debug(inspect(job));
this.writeStatus(job, callback);
};
JobStatusUpdater.prototype.completeJobStatus = function(job, callback) {
var self = this;
job.status = 'completed';
self.log.debug('JobStatusUpdater.completeJobStatus: Saving job: %s', inspect(job));
this.writeStatus(job, callback);
};
module.exports = JobStatusUpdater;
JobStatusUpdater._tests = {
'_writeStatus': JobStatusUpdater.prototype.writeStatus,
'_errorJobStatus': JobStatusUpdater.prototype.errorJobStatus,
'_createJobStatus': JobStatusUpdater.prototype.createJobStatus,
'_startJobStatus': JobStatusUpdater.prototype.startJobStatus,
'_completeJobStatus': JobStatusUpdater.prototype.completeJobStatus
};
|
var https = require('https');
//var request = require('request');
var Q = require('q');
var restify = require('restify');
var moment = require('moment');
var request = require('request');
var client;
var connectionConf;
exports.configure = function(conf) {
connectionConf = conf;
client = restify.createJsonClient({
url: 'https://'+conf.site+'.flightwatching.com'
});
client.basicAuth(conf.login,conf.password);
};
exports.get = function(path) {
var def = Q.defer();
client.get('/fleet/apiv3/'+path, function(err, req, res, obj) {
if (err) {
def.reject(err);
} else {
def.resolve(obj);
}
});
return def.promise;
};
exports.getSamples = function(fwot, oldestDate, format) {
var url = 'fwots/'+fwot+'/samples?count=1500&nested=true&pretty=true';
if (format) {
url+="&format="+format;
}
if (oldestDate) {
url+="&to="+moment.utc(oldestDate).add(1,'second').format();
}
console.log(url);
return this.getApiV3(url);
};
exports.getCsv = function(fwot, oldestDate) {
var def = Q.defer();
var url = 'https://'+connectionConf.site+'.flightwatching.com/fleet/apiv3/fwots/'+fwot+'/samples?count=2000&format=csv';
if (oldestDate) {
url+="&to="+moment.utc(oldestDate).add(1,'second').format();
}
console.log(url);
var auth = new Buffer(connectionConf.login + ':' + connectionConf.password).toString('base64');
var req = {
url: url,
method: 'GET',
headers: {
Authorization: 'Basic ' + auth,
'Content-Type': 'application/json'
}
};
request(req,function (error, response, body) {
if (error) {
def.reject(error);
} else {
def.resolve(body);
}
});
return def.promise;
};
|
/*
Copyright 2012 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Author: Landry DEFO KUATE (defolandry@yahoo.fr)
*/
function onError(e) {
console.log(e);
}
// Support du système de fichier ----------------------------------------------------------
var fs = null;
var FOLDERNAME = 'test';
function writeFile(blob) {
if (!fs) {
return;
}
fs.root.getDirectory(FOLDERNAME, {create: true}, function(dirEntry) {
dirEntry.getFile(blob.name, {create: true, exclusive: false}, function(fileEntry) {
// Créer un objet FileWriter pour notre FileEntry, et écrire le blob
fileEntry.createWriter(function(fileWriter) {
fileWriter.onerror = onError;
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
};
fileWriter.write(blob);
}, onError);
}, onError);
}, onError);
}
// -----------------------------------------------------------------------------
var gContactApp = angular.module('gContactApp', []);
gContactApp.factory('gcontacts', function() {
var gcontacts = {items: []};
var dnd = new DnDFileController('body', function(files) {
var chosenEntry = null;
var $scope = angular.element(this).scope();
for (var i = 0; i < files.items.length; i++) {
var item = files.items[i];
if (item.kind == 'file' &&
item.type.match('text/*') &&
item.webkitGetAsEntry()) {
chosenEntry = item.webkitGetAsEntry();
break;
}
};
Util.readAsText(chosenEntry, function(result) {
var data = angular.fromJson(result);
$scope.fetchContacts(data);
});
});
return gcontacts;
});
//Controller principal de l'application
function ContactsController($scope, $http, gcontacts) {
$scope.contacts = [];
$scope.fetchContacts = function(resp) {
var docs = [];
var totalEntries = resp.items.length;
resp.items.forEach(function(entry, i) {
var doc = {
title: entry.title,
firstname: entry.firstname,
lastname: entry.lastname,
email: entry.email,
tel: entry.tel,
updatedDate: Util.formatDate(entry.modifiedDate),
updatedDateFull: entry.modifiedDate,
icon: entry.iconLink,
alternateLink: entry.alternateLink,
size: entry.fileSize ? '( ' + entry.fileSize + ' bytes)' : null
};
// 'http://gstatic.google.com/doc_icon_128.png' -> 'doc_icon_128.png'
doc.iconFilename = doc.icon.substring(doc.icon.lastIndexOf('/') + 1);
// Si le fichier existe, il retourne un FileEntry pour l'URL du système de fichier
// Sinon, nous allons avoir un callback d'erreur qui nous permettra de recupérer le fichier
// et le stocker dans le système de fichier
var fsURL = fs.root.toURL() + FOLDERNAME + '/' + doc.iconFilename;
window.webkitResolveLocalFileSystemURL(fsURL, function(entry) {
console.log('Recuperation du fichier du systeme de fichier');
doc.icon = entry.toURL();
$scope.contacts.push(doc);
// On souhaite effectuer le tri seulement si on a toutes les données
if (totalEntries - 1 == i) {
$scope.contacts.sort(Util.sortByDate);
$scope.$apply(function($scope) {}); // Informer angular que nous avons effectué les changements
}
}, function(e) {
$http.get(doc.icon, {responseType: 'blob'}).success(function(blob) {
console.log('Fetched icon via XHR');
blob.name = doc.iconFilename; // Ajouter la photo dans le blob
writeFile(blob); // L'écriture est asynchrone, mais c'est OK
doc.icon = window.URL.createObjectURL(blob);
$scope.contacts.push(doc);
if (totalEntries - 1 == i) {
$scope.contacts.sort(Util.sortByDate);
}
});
});
});
};
$scope.clearContacts = function() {
$scope.contacts = []; // Vider les anciens résultats
};
}
ContactsController.$inject = ['$scope', '$http', 'gcontacts']; // Pour la minification du code source.
//Initialisation et attachement des Listeners
document.addEventListener('DOMContentLoaded', function(e) {
var closeButton = document.querySelector('#close-button');
closeButton.addEventListener('click', function(e) {
window.close();
});
// SUPPORT FILESYSTEM --------------------------------------------------------
window.webkitRequestFileSystem(TEMPORARY, 1024 * 1024, function(localFs) {
fs = localFs;
}, onError);
// ---------------------------------------------------------------------------
});
|
module.exports = function(req, res, log, next) {
res.json({keyWithParamPOST: 'value'});
};
|
/**
* @widgetClass Structure class
* @package wof.bizWidget
* @copyright author
* @Time: 13-9-21 下午08:46
*/
wof.bizWidget.ObjectInspector = function (root) {
this.getDomInstance().mousedown(function (event) {
event.stopPropagation();
});
};
wof.bizWidget.ObjectInspector.prototype = {
_initFlag: null,
_getCurrentStructureJson: function (root) {
var convertInstanceToJson = function (instances) {
var jsonArray = '[',
index = 0;
if (instances) {
for (var i = 0; i < instances.length; i++) {
var instance = instances[i],
className = instance.getClassName(),
id = instance.getId();
if (!id || !className || className.indexOf('Spanner') >= 0) {
continue;
}
if (index > 0) {
jsonArray += ',';
}
index++;
var children = instance.childNodes();
if (children.length) {
jsonArray += '{"name" : "' + className + '","oid" : "' + id + '"';
var childrenJson = convertInstanceToJson(children);
if (childrenJson) {
jsonArray += ',"children" : ' + childrenJson;
}
jsonArray += '}';
} else {
jsonArray += '{"name" : "' + className + '","oid" : "' + id + '"}';
}
}
}
if (index == 0) {
return null;
}
return jsonArray += ']';
},
jsonStr = '';
if (root) {
var instances = [];
root.children().each(function () {
var oid = jQuery(this).attr('oid'),
instance = wof.util.ObjectManager.get(oid);
if (instance) {
instances.push(instance);
}
});
jsonStr = convertInstanceToJson(instances);
return JSON.parse(jsonStr);
}
return [];
},
//选择实现
beforeRender: function () {
if (!this._initFlag) {
var that = this,
tree = new wof.widget.Tree();
tree.setIsInside(true);
tree.setNodes(this._getCurrentStructureJson(jQuery('#content')));
tree.onClick = function (e, treeId, treeNode) {
if (treeNode.oid) {
var prevSelect = this.getZTreeObj().setting._prevSelect;
if (prevSelect) {
prevSelect.node.css('border', prevSelect.border);
}
var node = $('*[oid="' + treeNode.oid + '"]');
var oldBorder = node.css('border');
node.css('border', '1px solid red');
this.getZTreeObj().setting._prevSelect = {node: node, border: oldBorder};
}
};
tree.appendTo(this);
this._initFlag = true;
}
},
//----------必须实现----------
render: function () {
},
//选择实现
afterRender: function () {
},
/**
* getData/setData 方法定义
*/
//----------必须实现----------
getData: function () {
return {
};
},
//----------必须实现----------
setData: function (data) {
}
};
|
// ERRORS_KEY = 'signinErrors'
Template.signin.onCreated(function() {
// Session.set(ERRORS_KEY, {})
});
Template.signin.helpers({
userName: function() {
// if (!$('input[name="name"]').val()) {
// return ;
// } else {
return "guest";
// }
},
avator: function() {
return "/images/avator.png";
}
// errorMessages: function() {
// return _.values(Session.get(ERRORS_KEY));
// },
// errorClass: function(key) {
// Session.get(ERRORS_KEY)[key] && 'error';
// }
});
Template.signin.events({
'click .fa-google-plus-square': function() {
return Meteor.loginWithGoogle({
requestPermissions: ['email']
}, function(error) {
if (error) {
console.log(error);
swal("验证失败!");
return ;
} else {
Meteor.call("updateGooleAccount", Meteor.userId(), function(err, res) {
if (err || !res) {
console.log(err);
console.log("google account create err");
} else {
console.log(res);
}
});
if (Session.get("SESSION_URL_HREF")) {
Router.go(Session.get("SESSION_URL_HREF"));
} else {
Router.go("home");
}
}
});
},
'click .fa-weixin': function() {
Meteor.loginWithWechat(function(err, res) {
if (!err) {
if (Session.get("SESSION_URL_HREF")) {
Router.go(Session.get("SESSION_URL_HREF"));
} else {
Router.go("home");
}
} else{
console.log('login failed ' + err);
}
});
},
'click .fa-weibo': function() {
Meteor.loginWithWeibo(function(err, res) {
if (!err) {
if (Session.get("SESSION_URL_HREF")) {
Router.go(Session.get("SESSION_URL_HREF"));
} else {
Router.go("home");
}
console.log('sucess ' + res)
} else {
console.log('login failed ' + err)
}
});
},
'submit': function(event, template) {
event.preventDefault();
userName = template.$('input[name="name"]').val();
password = template.$('input[name="password"]').val();
errors = {}
if (!userName) {
errors.userName = '用户名不能为空!';
swal(errors.userName);
}
if (!password) {
errors.password = '密码能为空!';
swal(errors.userName);
}
// Session.set(ERRORS_KEY, errors);
if (errors.userName) {
return;
}
template.$('.submit').val("logining...");
Meteor.loginWithPassword(userName, password, function(error) {
if (error) {
// var phoneAccount = PhonesColl.findOne({phoneNum: userName});
// if (phoneAccount) {
/*** need hack ***/
// Meteor.call("isExistUser", userName, function(error, result) {
// if (error || !result) {
swal("登录失败,账号不存在");
// } else {
// Meteor.loginWithPassword(result, password, function(error) {
// if (error) {
// swal(error.reason);
// return;
// } else {
// Router.go('home');
// }
// });
// }
// });
// } else {
// swal(error.reason);
// }
// console.log(error);
// Session.set(ERRORS_KEY, {
// 'none': error.reason
// });
} else {
Router.go('home');
}
});
template.$('.submit').val("LOGIN");
}
});
Template.signin.onRendered(function() {
// $('.ui.sidebar').sidebar('attach events', '.sidebar.icon');
})
|
const passport = require('passport');
const request = require('request');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models').User;
const INVALID_CREDENTIALS_MESSAGE = 'Invalid email and/or password.';
const UNAUTHORIZED_MESSAGE = 'You are not authorized.';
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id)
.then(user => done(null, user))
.catch(err => done(err));
});
/**
* Sign in using email and password.
*/
passport.use(new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
User.findOne({ where: { email: email.toLowerCase() } })
.then(user => {
if (!user) {
return done(null, false, { msg: INVALID_CREDENTIALS_MESSAGE });
}
user.comparePassword(password, (err, isMatch) => {
if (err) { return done(err); }
if (isMatch) {
return done(null, user);
}
return done(null, false, { msg: INVALID_CREDENTIALS_MESSAGE });
});
})
.catch(err => done(err));
}));
/**
* Login Required middleware.
*/
exports.isAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
res.status(401).json({ msg: UNAUTHORIZED_MESSAGE });
};
|
import angular from 'angular';
import gameboardComponent from './gameboard.component';
import Game from '../../common/game/game';
let gameboardModule = angular.module('gameboard', [
Game
])
.component('gameboard', gameboardComponent)
.name;
export default gameboardModule;
|
/*
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
Constants are installed on both the prototype and class.
<pre>
Ex.
constants: {
KEY: 'some value'
}
this.cls_.KEY === this.KEY === 'some value'
</pre>
*/
foam.CLASS({
package: 'foam.core',
name: 'Constant',
// documentation: 'Constant Axiom',
properties: [ 'name', 'value' ],
methods: [
function installInClass(cls) {
Object.defineProperty(
cls,
foam.String.constantize(this.name),
{
value: this.value,
configurable: false
});
},
function installInProto(proto) {
this.installInClass(proto);
}
]
});
foam.CLASS({
refines: 'foam.core.Model',
properties: [
{
class: 'AxiomArray',
of: 'Constant',
name: 'constants',
adapt: function(_, a, prop) {
if ( ! a ) return [];
if ( ! Array.isArray(a) ) {
var cs = [];
for ( var key in a ) {
cs.push(foam.core.Constant.create({name: key, value: a[key]}));
}
return cs;
}
var b = new Array(a.length);
for ( var i = 0 ; i < a.length ; i++ ) {
b[i] = prop.adaptArrayElement.call(this, a[i], prop);
}
return b;
}
}
]
});
|
import { isInteger } from "../utils/native";
const ASCENDING = (a, b) => a - b;
const DESCENDING = (a, b) => b - a;
const isInRange = (value, start, end) => value >= start && value <= end;
const isValidIndex = function (keys, start, end) {
return function (key) {
return !(key in keys)
&& isInteger(key)
&& isInRange(key, start, end);
};
};
export default function SparseIterator (obj, start, end, desc) {
this.object = obj;
this.start = start;
this.end = end;
this.asc = !desc;
this.version = 0;
}
SparseIterator.prototype = {
constructor: SparseIterator,
[Symbol.iterator] () {
return this;
},
reset () {
this.version = 0;
this.prototypes = [];
this.props = Object.create(null);
this.keys = [];
let current = this.object;
while (current) {
this.prototypes.push(current);
this.version += current.version;
current.getOwnPropertyKeys("String")
.filter(isValidIndex(this.props, this.start, this.end))
.forEach(key => {
// wrap in function - avoid calling until iteration
this.props[key] = current.getValue.bind(current, key);
this.keys.push(Number(key));
});
current = current.getPrototype();
}
this.keys.sort(this.asc ? ASCENDING : DESCENDING);
},
next () {
if (!this.version || this.shouldReset()) {
this.reset();
}
if (this.keys.length > 0) {
let key = this.currentIndex = this.keys.shift();
let value = this.props[key]();
return {
value: { key, value },
done: false
};
}
return {
done: true
};
},
shouldReset () {
let currentVersion = this.prototypes.reduce((v, o) => o.version + v, 0);
if (currentVersion !== this.version) {
if (this.asc) {
this.start = this.currentIndex + 1;
} else {
this.end = this.currentIndex - 1;
}
return true;
}
return false;
},
};
SparseIterator.create = function (arr, start, end, desc) {
return new SparseIterator(arr, start, end, desc);
};
|
const path = require('path')
const config = require('config')
const git = require('git-rev-sync')
const CDN = config.get('cdn')
const appVersion = git.short()
const CDN_URI = appVersion
const CDN_URL = CDN ? `${CDN}/${CDN_URI}` : ''
const PUBLIC_PATH = CDN ? `${CDN}/${CDN_URI}/assets/` : '/assets/'
const ROOT_PATH = path.join(__dirname, '../') // 项目根目录
const ASSETS_PATH = path.join(ROOT_PATH, './public')
const MODULES_PATH = path.join(ROOT_PATH, './node_modules') // node包目录
const BUILD_PATH = path.resolve(ASSETS_PATH, './assets') // 最后输出放置公共资源的目录
const DLL_PATH = path.resolve(ASSETS_PATH, './dll')
const SOURCE_PATH = path.join(ROOT_PATH, './frontend')
const ENTRY_PATH = path.join(SOURCE_PATH, './entries') // webpack入口文件
module.exports = {
ROOT_PATH,
BUILD_PATH,
DLL_PATH,
MODULES_PATH,
CDN_URI,
CDN_URL,
PUBLIC_PATH,
ENTRY_PATH,
SOURCE_PATH,
ASSETS_PATH
}
|
import { connect } from 'react-redux';
import ErrorMessageList from '../../components/error_messages/list';
import {
fetchErrorMessagesIfNeeded,
searchErrorMessages,
loadNext
} from '../../actions/error_messages'
export default connect(
(state,ownProps) => {
let errorMessages;
let match = ownProps.match
if (match && match.params && match.params.id) {
errorMessages = state.errorMessages[match.params.id]
}
return {errorMessages}
},
(dispatch,ownProps) => {
let resourceId;
let match = ownProps.match
if (match && match.params && match.params.id) {
resourceId = match.params.id
}
return {
loadErrorMessagesOnce: () => dispatch(fetchErrorMessagesIfNeeded(resourceId)),
loadNext: () => dispatch(loadNext(resourceId)),
searchErrorMessages: (term) => dispatch(searchErrorMessages(resourceId,term))
}
}
)(ErrorMessageList);
|
'use strict';
var common = require('../common');
var assert = require('assert');
var net = require('net');
var expected_bad_connections = 1;
var actual_bad_connections = 0;
var host = '********';
host += host;
host += host;
host += host;
host += host;
host += host;
function do_not_call() {
throw new Error('This function should not have been called.');
}
var socket = net.connect(42, host, do_not_call);
socket.on('error', function(err) {
assert.equal(err.code, 'ENOTFOUND');
actual_bad_connections++;
});
socket.on('lookup', function(err, ip, type) {
assert(err instanceof Error);
assert.equal(err.code, 'ENOTFOUND');
assert.equal(ip, undefined);
assert.equal(type, undefined);
});
process.on('exit', function() {
assert.equal(actual_bad_connections, expected_bad_connections);
});
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import createSolid from '../createSolid';
describe('createSolid', () => {
it('should convert with specifying opacity', () => {
expect(createSolid(255, 0, 0)).toStrictEqual({
color: { r: 255, g: 0, b: 0 },
});
});
it('should convert with full opacity', () => {
expect(createSolid(0, 255, 0, 1)).toStrictEqual({
color: { r: 0, g: 255, b: 0 },
});
});
it('should convert with less than full opacity', () => {
expect(createSolid(0, 0, 255, 0.1)).toStrictEqual({
color: { r: 0, g: 0, b: 255, a: 0.1 },
});
});
});
|
/*
* Copyright 2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/** @module vertx-apex-js/favicon_handler */
var utils = require('vertx-js/util/utils');
var RoutingContext = require('vertx-apex-js/routing_context');
var io = Packages.io;
var JsonObject = io.vertx.core.json.JsonObject;
var JFaviconHandler = io.vertx.ext.apex.handler.FaviconHandler;
/**
A handler that serves favicons.
<p>
If no file system path is specified it will attempt to serve a resource called `favicon.ico` from the classpath.
@class
*/
var FaviconHandler = function(j_val) {
var j_faviconHandler = j_val;
var that = this;
/**
@public
@param arg0 {RoutingContext}
*/
this.handle = function(arg0) {
var __args = arguments;
if (__args.length === 1 && typeof __args[0] === 'object' && __args[0]._jdel) {
j_faviconHandler["handle(io.vertx.ext.apex.RoutingContext)"](arg0._jdel);
} else utils.invalidArgs();
};
// A reference to the underlying Java delegate
// NOTE! This is an internal API and must not be used in user code.
// If you rely on this property your code is likely to break if we change it / remove it without warning.
this._jdel = j_faviconHandler;
};
/**
Create a handler attempting to load favicon file from the specified path, and with the specified max cache time
@memberof module:vertx-apex-js/favicon_handler
@param path {string} the path
@param maxAgeSeconds {number} max how long the file will be cached by browser, in seconds
@return {FaviconHandler} the handler
*/
FaviconHandler.create = function() {
var __args = arguments;
if (__args.length === 0) {
return new FaviconHandler(JFaviconHandler["create()"]());
}else if (__args.length === 1 && typeof __args[0] === 'string') {
return new FaviconHandler(JFaviconHandler["create(java.lang.String)"](__args[0]));
}else if (__args.length === 1 && typeof __args[0] ==='number') {
return new FaviconHandler(JFaviconHandler["create(long)"](__args[0]));
}else if (__args.length === 2 && typeof __args[0] === 'string' && typeof __args[1] ==='number') {
return new FaviconHandler(JFaviconHandler["create(java.lang.String,long)"](__args[0], __args[1]));
} else utils.invalidArgs();
};
// We export the Constructor function
module.exports = FaviconHandler;
|
import Vue from 'vue'
/**
* 递归初始化菜单列表,将menu下的子菜单添加tempList中
* */
function initMenu (menu, level, tempList) {
let childList = menu.childList
if (!childList) {
return
}
for (let i = 0; i < childList.length; i++) {
let childMenu = childList[i]
childMenu.level = level
Vue.set(childMenu, 'isShowInTable', level <= 3) // 是否显示,1,2,3级菜单默认显示
Vue.set(childMenu, 'isExpanded', level <= 2) // 是否展开菜单,1,2,3级菜单默认展开
tempList.push(childMenu)
initMenu(childMenu, level + 1, tempList)
}
}
/**
* 切换下一级菜单的状态,主要用于打开,打开的时候只显示下一级,且只修改本级的显示状态
* @param menu
* @param isShowInTable
*/
function toggleChildMenuList (menu, isShowInTable) {
// 修改子节点的显示状态
let list = menu.childList
if (list == null) {
return
}
for (let i = 0; i < list.length; i++) {
let childMenu = list[i]
childMenu.isShowInTable = isShowInTable
}
}
/**
* 递归切换所有菜单的状态,主要用于关闭,关闭的时候需要修改所有子节点的展开及显示状态
* @param menu
* @param isShowInTable
*/
function toggleChildMenuListRecursion (menu, isShowInTable) {
// 修改子节点的现实状态
let list = menu.childList
if (list == null) {
return
}
for (let i = 0; i < list.length; i++) {
let childMenu = list[i]
childMenu.isShowInTable = isShowInTable
childMenu.isExpanded = isShowInTable
toggleChildMenuListRecursion(childMenu, isShowInTable)
}
}
/**
* 收缩 / 展开 全部菜单
* @param topMenu
* @param isShowInTable
*/
function toggleAllMenu (topMenu, isShowInTable) {
let list = topMenu.childList
for (let i = 0; i < list.length; i++) {
let childMenu = list[i]
childMenu.isExpanded = isShowInTable
toggleChildMenuListRecursion(childMenu, isShowInTable)
}
}
function removeFromTopElement (topElement, element) {
let list = topElement.childList
if (list == null) {
return
}
list.forEach((childMenu, i) => {
if (childMenu.id === element.id) {
childMenu.childList = null
list.splice(i, 1)
}
removeFromTopElement(childMenu, element)
})
}
const TreeTableMiXin = {
data: function () {
return {
/**
* 展开状态
*/
toggleStatus: true
}
},
computed: {
dataList: function () {
let tempList = []
if (this.topElement) {
initMenu(this.topElement, 1, tempList)
}
return tempList
}
},
methods: {
/**
* 展开/收缩 菜单
*/
toggle: function (menu) {
let isExpanded = menu.isExpanded
if (isExpanded) {
toggleChildMenuListRecursion(menu, !isExpanded)
} else {
toggleChildMenuList(menu, !isExpanded)
}
menu.isExpanded = !isExpanded
},
/**
* 全部展开/收缩 菜单
*/
toggleAll: function () {
toggleAllMenu(this.topElement, !this.toggleStatus)
this.toggleStatus = !this.toggleStatus
},
/**
* 移除元素以及该元素的子元素
*/
removeElement (element) {
removeFromTopElement(this.topElement, element)
}
}
}
export default TreeTableMiXin
|
/* @flow */
export const ALIGN_ITEMS = {
start: 'start',
end: 'end',
center: 'center',
stretch: 'stretch'
};
export const GUTTER_WIDTH = {
xxs: 'xxs',
xs: 'xs',
sm: 'sm',
md: 'md',
lg: 'lg',
xl: 'xl',
xxl: 'xxl'
};
|
define(["dojo/_base/declare", "dojo/Deferred", "dojo/promise/all",
"dojo/_base/lang", "dojo/_base/array", "esri/arcgis/utils", "esri/lang",
"esri/tasks/PrintTemplate", "esri/request"
], function(
declare, Deferred, all, lang, array, arcgisUtils, esriLang, PrintTemplate,
esriRequest) {
return declare(null, {
constructor: function(parameters) {
lang.mixin(this.printConfig, parameters);
},
//*********
//Variables
//************
//defaultFormat: "pdf",
printConfig: {
templates: null,
layouts: false,
legendLayers: [],
printi18n: null,
format: "pdf",
printTaskUrl: null,
layoutOptions: {
"titleText": null,
"scalebarUnit": null,
"legendLayers": []
}
},
templates: [],
legendLayers: [],
//optional array of additional search layers to configure from the application config process
createPrintOptions: function() {
var deferred = new Deferred();
all([
this._buildPrintLayouts(), this._createPrintLegend()
]).then(lang.hitch(this, function(results) {
deferred.resolve({
templates: this.templates,
legendLayers: this.legendLayers
});
}));
return deferred.promise;
},
_createPrintLegend: function() {
var deferred = new Deferred();
var layers = arcgisUtils.getLegendLayers(this.printConfig.legendLayers);
this.legendLayers = array.map(layers, function(layer) {
return {
"layerId": layer.layer.id
};
});
deferred.resolve(true);
return deferred.promise;
},
_buildPrintLayouts: function() {
var deferred = new Deferred();
if (this.printConfig.templates) {
this.templates = this.printConfig.templates;
array.forEach(this.templates, lang.hitch(this, function(
template) {
if (template.layout === "MAP_ONLY") {
template.exportOptions = {
width: 670,
height: 500,
dpi: 96
};
}
template.layoutOptions = this.printConfig.layoutOptions;
}));
deferred.resolve(true);
} else if (this.printConfig.layouts) {
esriRequest({
url: this.printConfig.printTaskUrl,
content: {
"f": "json"
},
callbackParamName: "callback"
}).then(lang.hitch(this, function(response) {
var layoutTemplate,
templateNames,
mapOnlyIndex;
layoutTemplate = array.filter(response.parameters,
function(param, idx) {
return param.name === "Layout_Template";
});
if (layoutTemplate.length === 0) {
console.log(
"print service parameters name for templates must be \"Layout_Template\""
);
return;
}
templateNames = layoutTemplate[0].choiceList;
// remove the MAP_ONLY template then add it to the end of the list of templates
mapOnlyIndex = array.indexOf(templateNames,
"MAP_ONLY");
if (mapOnlyIndex > -1) {
var mapOnly = templateNames.splice(mapOnlyIndex,
mapOnlyIndex + 1)[0];
templateNames.push(mapOnly);
}
// create a print template for each choice
this.templates = array.map(templateNames, lang.hitch(
this,
function(name) {
var plate = new PrintTemplate();
plate.layout = plate.label = name;
plate.format = this.printConfig.format;
plate.layoutOptions = this.printConfig.layoutOptions;
return plate;
}));
deferred.resolve(true);
}));
} else {
//var letterAnsiAPlate = new PrintTemplate();
// letterAnsiAPlate.layout = "Letter ANSI A Landscape";
var landscapeFormat = new PrintTemplate();
landscapeFormat.layout = "Letter ANSI A Landscape";
landscapeFormat.layoutOptions = this.printConfig.layoutOptions;
landscapeFormat.format = this.printConfig.format;
landscapeFormat.label = this.printConfig.printi18n.layouts.label1 +
" ( " + this.printConfig.format + " )";
var portraitFormat = new PrintTemplate();
portraitFormat.layout = "Letter ANSI A Portrait";
portraitFormat.layoutOptions = this.printConfig.layoutOptions;
portraitFormat.format = this.printConfig.format;
portraitFormat.label = this.printConfig.printi18n.layouts.label2 +
" ( " + this.printConfig.format + " )";
var landscapeImage = new PrintTemplate();
landscapeImage.layout = "Letter ANSI A Landscape";
landscapeImage.layoutOptions = this.printConfig.layoutOptions;
landscapeImage.format = "png32";
landscapeImage.label = this.printConfig.printi18n.layouts.label3 +
" ( image )";
var portraitImage = new PrintTemplate();
portraitImage.layout = "Letter ANSI A Portrait";
portraitImage.layoutOptions = this.printConfig.layoutOptions;
portraitImage.format = "png32";
portraitImage.label = this.printConfig.printi18n.layouts.label4 +
" ( image )";
this.templates = [landscapeFormat, portraitFormat,
landscapeImage, portraitImage
];
deferred.resolve(true);
}
return deferred.promise;
}
});
});
|
import { Class, Enum } from 'meteor/jagi:astronomy'
import 'jagi:astronomy-timestamp-behavior'
export const ApplicationStatus = Enum.create({
name: 'ApplicationStatus',
identifiers: {
DRAFT: 0,
ACTIVE: 1,
INACTIVE: 2
}
})
export const Application = Class.create({
name: 'Application',
collection: new Mongo.Collection('applications'),
fields: {
name: {
type: String,
validators: [{
type: 'maxLength', param: 50, message: 'application_name_max_length'
}]
},
description: {
type: String,
optional: true,
validators: [{
type: 'maxLength', param: 500, message: 'application_description_max_length'
}]
},
userId: String,
status: {
type: ApplicationStatus,
default: ApplicationStatus.DRAFT
}
},
behaviors: {
softremove: {
removedFieldName: 'removed',
hasRemovedAtField: true,
removedAtFieldName: 'removedAt'
},
timestamp: {
hasCreatedField: true,
createdFieldName: 'createdAt',
hasUpdatedField: true,
updatedFieldName: 'updatedAt'
}
},
indexes: {
unique_application_name: {
fields: {
name: 1
},
options: {
unique: true
}
}
}
})
|
(function() {
window.WallTime || (window.WallTime = {});
window.WallTime.data = {
rules: {},
zones: {"Etc/GMT+10":[{"name":"Etc/GMT+10","_offset":"-10","_rule":"-","format":"GMT+10","_until":""}]}
};
window.WallTime.autoinit = true;
}).call(this);
|
/**
* :copyright: (c) 2014 Building Energy Inc
* :license: see LICENSE for more details.
*/
angular.module('BE.seed.controller.dataset', [])
.controller('dataset_list_controller', [
'$scope',
'datasets_payload',
'$modal',
'urls',
'dataset_service',
'$location',
function ($scope, datasets_payload, $modal, urls, dataset_service, $location) {
$scope.datasets = datasets_payload.datasets;
$scope.columns = [
{
title: "Data Set Name"
},
{
title: "# Of Files"
},
{
title: "Last Changed"
},
{
title: "Changed By"
},
{
title: "Actions"
}
];
/**
* Functions for dealing with editing a dataset's name
*/
$scope.edit_dataset_name = function (dataset) {
dataset.edit_form_showing = true;
dataset.old_name = dataset.name;
};
$scope.cancel_edit_name = function (dataset) {
dataset.name = dataset.old_name;
dataset.edit_form_showing = false;
};
$scope.save_dataset_name = function (dataset) {
if (dataset.name !== dataset.old_name) {
$scope.update_dataset(dataset);
dataset.edit_form_showing = false;
}
};
/**
* open_data_upload_modal: opens the data upload modal to step 4, add energy files
*/
$scope.open_data_upload_modal = function(dataset) {
var step = 2;
if (typeof dataset === "undefined"){
step = 1;
dataset = {};
} else if ($scope.missing_assessor_files(dataset)) {
step = 2;
}
var dataModalInstance = $modal.open({
templateUrl: urls.static_url + 'seed/partials/data_upload_modal.html',
controller: 'data_upload_modal_ctrl',
resolve: {
step: function(){
return step;
},
dataset: function(){
return dataset;
}
}
});
dataModalInstance.result.then(
// modal close() function
function () {
init();
// modal dismiss() function
}, function (message) {
init();
});
};
$scope.confirm_delete = function (dataset) {
var yes = confirm("Are you sure you want to PERMANENTLY delete '" + dataset.name + "'?");
if (yes) {
$scope.delete_dataset(dataset);
}
};
$scope.delete_dataset = function(dataset) {
dataset_service.delete_dataset(dataset.id).then(function(data) {
// resolve promise
init();
});
};
$scope.update_dataset = function(dataset) {
dataset_service.update_dataset(dataset).then(function(data){
// resolve promise
init();
});
};
/**
* goto_mapping: changes browser location to the first assessed file
* mapping page
*/
$scope.goto_mapping = function(dataset) {
for (var i=0; i < dataset.importfiles.length; i++){
var importfile = dataset.importfiles[i];
if (importfile.source_type === "Assessed Raw") {
$location.path('/data/mapping/' + importfile.id);
break;
}
}
};
/**
* goto_mapping: changes browser location to the first portfolio file
* matching page
*/
$scope.goto_matching = function(dataset) {
for (var i=0; i < dataset.importfiles.length; i++){
var importfile = dataset.importfiles[i];
if (importfile.source_type === "Portfolio Raw") {
$location.path('/data/matching/' + importfile.id);
break;
}
}
};
/**
* missing_assessor_files: true if the dataset has no assessed files
*/
$scope.missing_assessor_files = function(dataset) {
for (var i=0; i < dataset.importfiles.length; i++){
var importfile = dataset.importfiles[i];
if (importfile.source_type === "Assessed Raw") {
return false;
}
}
return true;
};
/**
* missing_pm_files: true if the dataset has no Portfolio Manager files
*/
$scope.missing_pm_files = function(dataset) {
for (var i=0; i < dataset.importfiles.length; i++){
var importfile = dataset.importfiles[i];
if (importfile.source_type === "Portfolio Raw") {
return false;
}
}
return true;
};
/**
* event brocasted from menu controller when a new dataset is added
*/
$scope.$on('datasets_updated', function(){
init();
});
/**
* init: refreshes dataset list
*/
var init = function(){
dataset_service.get_datasets().then(function(data){
// resolve promise
$scope.datasets = data.datasets;
});
};
}
]);
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import { useCallback, useEffect, useState } from '@googleforcreators/react';
/**
* This hook creates a handler to use for double click listening
* on a node, where single clicks are also relevant. Default timeout
* is 200 ms. If no subsequent click has been recorded in the given
* time, single click will be assumed.
*
* This hook returns a handler retrieval function, not the handler
* itself. This allows the component to use the same hook for multiple
* children listening for events.
*
* For example:
* ```
* function SomeComponent() {
* const handleSingle = useCallback( ( evt, item ) => {
* // Handle single click on `item`
* }, [] );
* const handleDouble = useCallback( ( evt, item ) => {
* // Handle double click on `item`
* }, [] );
* const getHandler = useDoubleClick( handleSingle, handleDouble );
* const items = [
* // Some objects with `id` and `name` attributes.
* ];
* return items.map( ( item} ) => (
* <button key={ item.id } onClick={ getHandler( item ) }>
* { item.name }
* </button>
* ) );
* }
* ```
*
* @param {Function} onSingleClick Handler to activate on single click.
* @param {Function} onDoubleClick Handler to activate on double click.
* @param {number} ms Timeout in ms to wait - defaults to 200.
* @return {Function} Handler retrieval function to get an onClick listener (invoke with unique value).
*/
const useDoubleClick = (onSingleClick, onDoubleClick, ms = null) => {
const [target, setTarget] = useState(null);
const [lastEvent, setLastEvent] = useState(null);
const getHandler = useCallback(
(newTarget) => (evt) => {
evt.stopPropagation();
if (target !== newTarget) {
if (target) {
onSingleClick(evt, target);
}
setTarget(newTarget);
setLastEvent(evt);
return;
}
onDoubleClick(evt, target);
setTarget(null);
},
[onSingleClick, onDoubleClick, target]
);
useEffect(() => {
if (!target) {
return undefined;
}
const int = setTimeout(() => {
setTarget(null);
onSingleClick(lastEvent, target);
}, ms || DEFAULT_MS);
return () => {
clearTimeout(int);
};
}, [target, lastEvent, onSingleClick, ms]);
return getHandler;
};
export default useDoubleClick;
const DEFAULT_MS = 200;
|
import mx from '../../multiplex';
import * as mocks from './_mocks';
import {
qmodule,
qtest
} from '../../qunit';
qmodule('linq-first');
function simpleNumericPredicate(t) {
return t > 3;
}
qtest('basic "first" test', function (assert) {
assert.equal(mx(mocks.array).first(), 1, 'first of an array of numbers');
assert.equal(mx(mocks.array).first(simpleNumericPredicate), 4, 'first of an array of numbers with predicate');
assert.equal(mx('test').first(), 't', 'first of an string');
});
qtest('collections "first" method tests', function (assert) {
assert.equal(mocks.enumerable.first(), 1, 'Test "first" in an enumerable');
assert.equal(mocks.enumerable.first(simpleNumericPredicate), 4, 'Test "first" in an enumerable with predicate');
assert.equal(mocks.collection.first(), 1, 'Test "first" in a Collection');
assert.equal(mocks.collection.first(simpleNumericPredicate), 4, 'Test "first" in a Collection with predicate');
assert.equal(mocks.list.first(), 1, 'Test "first" in a List');
assert.equal(mocks.list.first(simpleNumericPredicate), 4, 'Test "first" in a List with predicate');
assert.equal(mocks.readOnlyCollection.first(), 1, 'Test "first" in a ReadOnlyCollection');
assert.equal(mocks.readOnlyCollection.first(simpleNumericPredicate), 4, 'Test "first" in a ReadOnlyCollection with predicate');
assert.equal(mocks.linkedList.first(), 1, 'Test "first" in a LinkedList');
assert.equal(mocks.linkedList.first(simpleNumericPredicate), 4, 'Test "first" in a LinkedList with predicate');
assert.equal(mocks.hashSet.first(), 1, 'Test "first" in a HashSet');
assert.equal(mocks.hashSet.first(simpleNumericPredicate), 4, 'Test "first" in a HashSet with predicate');
assert.equal(mocks.stack.first(), 1, 'Test "first" in a Stack');
assert.equal(mocks.stack.first(simpleNumericPredicate), 4, 'Test "first" in a Stack with predicate');
assert.equal(mocks.queue.first(), 1, 'Test "first" in a Queue');
assert.equal(mocks.queue.first(simpleNumericPredicate), 4, 'Test "first" in a Queue with predicate');
assert.equal(mocks.set.first(), 1, 'Test "first" in a Set');
assert.equal(mocks.set.first(simpleNumericPredicate), 4, 'Test "first" in a Set with predicate');
assert.equal(mocks.map.first()[0], 1, 'Test "first" in a Map');
assert.equal(mocks.map.first(function (t) {
return t[0] > 3;
})[0], 4, 'Test "first" in a Map with predicate');
assert.equal(mocks.dictionary.first().key, 1, 'Test "first" in a Dictionary');
assert.equal(mocks.dictionary.first(function (t) {
return t.key > 3;
}).key, 4, 'Test "first" in a Dictionary with predicate');
assert.equal(mocks.lookup.first().key, 1, 'Test "first" in a Lookup');
assert.equal(mocks.lookup.first(function (t) {
return t.key > 3;
}).key, 4, 'Test "first" in a Lookup with predicate');
assert.equal(mocks.sortedList.first().key, 1, 'Test "first" in a SortedList');
assert.equal(mocks.sortedList.first(function (t) {
return t.key > 3;
}).key, 4, 'Test "first" in a SortedList with predicate');
});
qtest('first method validations', function (assert) {
assert.throws(function () {
mx([]).first();
}, 'empty collection');
assert.throws(function () {
mx([1]).first(1);
}, 'non-function predicate');
assert.throws(function () {
mx([1]).first(simpleNumericPredicate);
}, 'no match');
});
|
sap.ui.define(["sap/ui/core/UIComponent", "sap/ui/core/mvc/XMLView"],
function(UIComponent, XMLView) {
'use strict';
var Component = UIComponent.extend("sap.tnt.sample.InfoLabelInTable.Component", {
metadata : {
publicMethods : [
"getTable"
],
dependencies : {
libs : [
"sap.tnt",
"sap.m",
"sap.ui.layout"
]
},
config : {
sample : {
files : [
"V.view.xml",
"V.controller.js",
"Formatter.js"
]
}
}
},
getTable : function () {
return this._rootView.getContent()[0];
}
});
Component.prototype.createContent = function () {
this._rootView = sap.ui.xmlview({ viewName : "sap.tnt.sample.InfoLabelInTable.V" });
return this._rootView;
};
return Component;
});
|
'use strict';
const Q = require("q");
const util = require("util");
const https = require("https");
const http = require("http");
const fs = require("fs");
const xml2js = require("xml2js");
const paths = {
"inchikey" : "inchikey",
"name" : "name/startswith",
"rn" : "rn"
};
function ChemIDDB () {
var database = {};
}
module.exports.DB = ChemIDDB;
ChemIDDB.prototype.load = function( filename ) {
var parser = new xml2js.Parser();
if (verbose) console.log("loading: ", filename);
fs.readFile(filename, function( err, data ){
parser.parseString(data, function(err, results) {
if(err) {
console.log("error", err);
process.exit();
}
if (verbose) console.log("results:", util.inspect(results[0], false, null));
// database = results;
}).then(function(){
console.log("db loaded");
})
})
}
function query( params, verbose, callback ) {
if (!Array.isArray(params)) {
params = [params];
}
var promises = [];
params.forEach(function(param) {
var options = {
query : param.query || null,
type : param.type || 'name',
match : param.match || 'first'
}
promises.push( retrieve( options.query, options.type, options.match, verbose))
});
Q.allSettled(promises).then(
function( values ) {
callback(null, values);
},
function ( err ) {
callback(err);
}
)
}
function retrieve( query, type, match, verbose ) {
var deferred = Q.defer();
var url = [host, paths[type],query].join("/");
if (!query) {
deferred.reject("NA");
}
if (verbose) {
console.log("ChemID url: " + url);
}
var result = "";
var req = https.get(url, function( res ) {
if (verbose) {
console.log("Status: ", res.statusCode);
console.log("Headers: ", res.headers);
}
if (res.statusCode < 200 || res.statusCode > 399) {
deferred.reject( res.statusCode );
}
res.on("data", function( chunk ) {
result += chunk;
});
res.on("end", function( ) {
deferred.resolve( result );
})
});
req.on("error", function(err) {
deferred.reject(err);
})
return deferred.promise;
}
module.exports.query = query;
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2020 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['jquery.sap.global', './ListItemBaseRenderer', 'sap/ui/core/Renderer'],
function(jQuery, ListItemBaseRenderer, Renderer) {
"use strict";
/**
* <code>MenuListItem</code> renderer.
* @namespace
*/
var MenuListItemRenderer = Renderer.extend(ListItemBaseRenderer);
/**
* Renders the HTML starting tag of the <code>MenuListItem</code>.
*
* @param {sap.ui.core.RenderManager} rm The RenderManager that can be used for writing to the Render-Output-Buffer
* @param {sap.ui.core.Control} oLI an object representation of the control that should be rendered
* @protected
*/
MenuListItemRenderer.openItemTag = function(rm, oLI) {
if (oLI.getStartsSection()) {
rm.write("<li ");
rm.write("role=\"separator\" ");
rm.write("class=\"sapUiMnuDiv\"><div class=\"sapUiMnuDivL\"></div><hr><div class=\"sapUiMnuDivR\"></div></li>");
}
ListItemBaseRenderer.openItemTag(rm, oLI);
};
/**
* Renders the HTML for the given control, using the provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager}
* oRenderManager the RenderManager that can be used for writing to the
* Render-Output-Buffer
* @param {sap.ui.core.Control}
* oControl an object representation of the control that should be
* rendered
*/
MenuListItemRenderer.renderLIAttributes = function(rm, oLI) {
rm.addClass("sapMSLI");
if (oLI.getIcon()) {
rm.addClass("sapMSLIIcon");
}
if (oLI.getType() == sap.m.ListType.Detail || oLI.getType() == sap.m.ListType.DetailAndActive) {
rm.addClass("sapMSLIDetail");
}
if (oLI._hasSubItems()) {
rm.addClass("sapMMenuLIHasChildren");
}
};
MenuListItemRenderer.renderLIContent = function(rm, oLI) {
var sTextDir = oLI.getTitleTextDirection();
// image
if (oLI.getIcon()) {
rm.renderControl(oLI._getImage((oLI.getId() + "-img"), "sapMMenuLIImgThumb", oLI.getIcon(), oLI.getIconDensityAware()));
}
rm.write("<div");
rm.addClass("sapMSLIDiv");
rm.addClass("sapMSLITitleDiv");
rm.writeClasses();
rm.write(">");
//noFlex: make an additional div for the contents table
if (oLI._bNoFlex) {
rm.write('<div class="sapMLIBNoFlex">');
}
// List item text (also written when no title for keeping the space)
rm.write("<div");
rm.addClass("sapMSLITitleOnly");
rm.writeClasses();
if (sTextDir !== sap.ui.core.TextDirection.Inherit) {
rm.writeAttribute("dir", sTextDir.toLowerCase());
}
rm.write(">");
rm.writeEscaped(oLI.getTitle());
rm.write("</div>");
//noFlex: make an additional div for the contents table
if (oLI._bNoFlex) {
rm.write('</div>');
}
rm.write("</div>");
// arrow right if there is a sub-menu
if (oLI._hasSubItems()) {
rm.renderControl(oLI._getIconArrowRight());
}
};
return MenuListItemRenderer;
}, /* bExport= */ true);
|
'use strict';
module.exports = {
db: "mongodb://localhost/openqna-test",
port: 3001,
facebook: {
clientID: "APP_ID",
clientSecret: "APP_SECRET",
callbackURL: "http://localhost:3000/auth/facebook/callback"
},
twitter: {
clientID: "CONSUMER_KEY",
clientSecret: "CONSUMER_SECRET",
callbackURL: "http://localhost:3000/auth/twitter/callback"
},
github: {
clientID: "APP_ID",
clientSecret: "APP_SECRET",
callbackURL: "http://localhost:3000/auth/github/callback"
},
google: {
clientID: "APP_ID",
clientSecret: "APP_SECRET",
callbackURL: "http://localhost:3000/auth/google/callback"
}
}
|
/**
* @license
* Visual Blocks Editor
*
* Copyright 2012 Google Inc.
* https://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Object representing a warning.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Warning');
goog.require('Blockly.Bubble');
goog.require('Blockly.Icon');
/**
* Class for a warning.
* @param {!Blockly.Block} block The block associated with this warning.
* @extends {Blockly.Icon}
* @constructor
*/
Blockly.Warning = function(block) {
Blockly.Warning.superClass_.constructor.call(this, block);
this.createIcon_();
};
goog.inherits(Blockly.Warning, Blockly.Icon);
/**
* Create the text for the warning's bubble.
* @param {string} text The text to display.
* @return {!SVGTextElement} The top-level node of the text.
* @private
*/
Blockly.Warning.textToDom_ = function(text) {
var paragraph = /** @type {!SVGTextElement} */ (
Blockly.createSvgElement('text',
{'class': 'blocklyText blocklyBubbleText',
'y': Blockly.Bubble.BORDER_WIDTH},
null));
var lines = text.split('\n');
for (var i = 0; i < lines.length; i++) {
var tspanElement = Blockly.createSvgElement('tspan',
{'dy': '1em', 'x': Blockly.Bubble.BORDER_WIDTH}, paragraph);
var textNode = document.createTextNode(lines[i]);
tspanElement.appendChild(textNode);
}
return paragraph;
};
/**
* Warning text (if bubble is not visible).
* @private
*/
Blockly.Warning.prototype.text_ = '';
/**
* Create the icon on the block.
* @private
*/
Blockly.Warning.prototype.createIcon_ = function() {
Blockly.Icon.prototype.createIcon_.call(this);
/* Here's the markup that will be generated:
<path class="blocklyIconShield" d="..."/>
<text class="blocklyIconMark" x="8" y="13">!</text>
*/
var iconShield = Blockly.createSvgElement('path',
{'class': 'blocklyWarningIconShield', 'fill': "yellow", // Quizly: Add color
'd': 'M 2,15 Q -1,15 0.5,12 L 6.5,1.7 Q 8,-1 9.5,1.7 L 15.5,12 ' +
'Q 17,15 14,15 z'},
this.iconGroup_);
this.iconMark_ = Blockly.createSvgElement('text',
{'class': 'blocklyWarningIconMark',
'x': Blockly.Icon.RADIUS -3, // Quizly: adjust
'y': 2 * Blockly.Icon.RADIUS - 3}, this.iconGroup_);
this.iconMark_.appendChild(document.createTextNode('!'));
};
/**
* Create the text for the warning's bubble.
* @param {string} text The text to display.
* @return {!SVGTextElement} The top-level node of the text.
* @private
*/
Blockly.Warning.prototype.textToDom_ = function(text) {
var paragraph = /** @type {!SVGTextElement} */ (
Blockly.createSvgElement(
'text', {'class': 'blocklyText blocklyErrorWarningText', 'y': Blockly.Bubble.BORDER_WIDTH},
null));
var lines = text.split('\n');
for (var i = 0; i < lines.length; i++) {
var tspanElement = Blockly.createSvgElement('tspan',
{'dy': '1em', 'x': Blockly.Bubble.BORDER_WIDTH}, paragraph);
var textNode = document.createTextNode(lines[i]);
tspanElement.appendChild(textNode);
}
return paragraph;
};
/**
* Show or hide the warning bubble.
* @param {boolean} visible True if the bubble should be visible.
*/
Blockly.Warning.prototype.setVisible = function(visible) {
if (visible == this.isVisible()) {
// No change.
return;
}
if (visible) {
// Create the bubble.
var paragraph = Blockly.Warning.textToDom_(this.text_);
this.bubble_ = new Blockly.Bubble(
/** @type {!Blockly.Workspace} */ (this.block_.workspace),
paragraph, this.block_.svg_.svgPath_,
this.iconX_, this.iconY_, null, null);
if (Blockly.RTL) {
// Right-align the paragraph.
// This cannot be done until the bubble is rendered on screen.
var maxWidth = paragraph.getBBox().width;
for (var x = 0, textElement; textElement = paragraph.childNodes[x]; x++) {
textElement.setAttribute('text-anchor', 'end');
textElement.setAttribute('x', maxWidth + Blockly.Bubble.BORDER_WIDTH);
}
}
this.updateColour();
// Bump the warning into the right location.
var size = this.bubble_.getBubbleSize();
this.bubble_.setBubbleSize(size.width, size.height);
} else {
// Dispose of the bubble.
this.bubble_.dispose();
this.bubble_ = null;
this.body_ = null;
}
};
/**
* Bring the warning to the top of the stack when clicked on.
* @param {!Event} e Mouse up event.
* @private
*/
Blockly.Warning.prototype.bodyFocus_ = function(e) {
this.bubble_.promote_();
};
/**
* Set this warning's text.
* @param {string} text Warning text.
*/
Blockly.Warning.prototype.setText = function(text) {
if (this.text_ == text) {
return;
}
this.text_ = text;
if (this.isVisible()) {
this.setVisible(false);
this.setVisible(true);
}
};
/**
* Dispose of this warning.
*/
Blockly.Warning.prototype.dispose = function() {
this.block_.warning = null;
Blockly.Icon.prototype.dispose.call(this);
};
|
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { useState, useCallback, useEffect } from 'react';
import classnames from 'classnames';
import { settings } from 'carbon-components';
import FileUploaderItem from '../FileUploaderItem';
import FileUploaderDropContainer from '../FileUploaderDropContainer';
import FormItem from '../../FormItem';
import uid from '../../../tools/uniqueId';
import '../FileUploader-story.scss';
const { prefix } = settings;
const ExampleDropContainerApp = (props) => {
const [files, setFiles] = useState([]);
const handleDrop = (e) => {
e.preventDefault();
};
const handleDragover = (e) => {
e.preventDefault();
};
useEffect(() => {
document.addEventListener('drop', handleDrop);
document.addEventListener('dragover', handleDragover);
return () => {
document.removeEventListener('drop', handleDrop);
document.removeEventListener('dragover', handleDragover);
};
}, []);
const uploadFile = async (fileToUpload) => {
// file size validation
if (fileToUpload.filesize > 512000) {
const updatedFile = {
...fileToUpload,
status: 'edit',
iconDescription: 'Delete file',
invalid: true,
errorSubject: 'File size exceeds limit',
errorBody: '500kb max file size. Select a new file and try again.',
};
setFiles((files) =>
files.map((file) =>
file.uuid === fileToUpload.uuid ? updatedFile : file
)
);
return;
}
// file type validation
if (fileToUpload.invalidFileType) {
const updatedFile = {
...fileToUpload,
status: 'edit',
iconDescription: 'Delete file',
invalid: true,
errorSubject: 'Invalid file type',
errorBody: `"${fileToUpload.name}" does not have a valid file type.`,
};
setFiles((files) =>
files.map((file) =>
file.uuid === fileToUpload.uuid ? updatedFile : file
)
);
return;
}
// simulate network request time
const rand = Math.random() * 1000;
setTimeout(() => {
const updatedFile = {
...fileToUpload,
status: 'complete',
iconDescription: 'Upload complete',
};
setFiles((files) =>
files.map((file) =>
file.uuid === fileToUpload.uuid ? updatedFile : file
)
);
}, rand);
// show x icon after 1 second
setTimeout(() => {
const updatedFile = {
...fileToUpload,
status: 'edit',
iconDescription: 'Delete file',
};
setFiles((files) =>
files.map((file) =>
file.uuid === fileToUpload.uuid ? updatedFile : file
)
);
}, rand + 1000);
};
const onAddFiles = useCallback(
(evt, { addedFiles }) => {
evt.stopPropagation();
const newFiles = addedFiles.map((file) => ({
uuid: uid(),
name: file.name,
filesize: file.size,
status: 'uploading',
iconDescription: 'Uploading',
invalidFileType: file.invalidFileType,
}));
// eslint-disable-next-line react/prop-types
if (props.multiple) {
setFiles([...files, ...newFiles]);
newFiles.forEach(uploadFile);
} else if (newFiles[0]) {
setFiles([newFiles[0]]);
uploadFile(newFiles[0]);
}
},
// eslint-disable-next-line react/prop-types
[files, props.multiple]
);
const handleFileUploaderItemClick = useCallback(
(_, { uuid: clickedUuid }) =>
setFiles(files.filter(({ uuid }) => clickedUuid !== uuid)),
[files]
);
const labelClasses = classnames(`${prefix}--file--label`, {
// eslint-disable-next-line react/prop-types
[`${prefix}--file--label--disabled`]: props.disabled,
});
const helperTextClasses = classnames(`${prefix}--label-description`, {
// eslint-disable-next-line react/prop-types
[`${prefix}--label-description--disabled`]: props.disabled,
});
return (
<FormItem>
<p className={labelClasses}>Upload files</p>
<p className={helperTextClasses}>
Max file size is 500kb. Supported file types are .jpg and .png.
</p>
<FileUploaderDropContainer {...props} onAddFiles={onAddFiles} />
<div className={`${prefix}--file-container`} style={{ width: '100%' }}>
{files.map(
({
uuid,
name,
filesize,
status,
iconDescription,
invalid,
...rest
}) => (
<FileUploaderItem
key={uid()}
uuid={uuid}
name={name}
filesize={filesize}
// eslint-disable-next-line react/prop-types
size={props.size}
status={status}
iconDescription={iconDescription}
invalid={invalid}
onDelete={handleFileUploaderItemClick}
{...rest}
/>
)
)}
</div>
</FormItem>
);
};
export default ExampleDropContainerApp;
|
// @flow
import React, { Component } from "react";
import PropTypes from "prop-types";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import * as actions from "./actions";
import { defaultStyles } from "../../styles/default-styles";
import { StyleSheet, View, TouchableOpacity, Text } from "react-native";
import Toggle from "../../components/toggle/toggle";
import circleTurquoise from "../../assets/images/circle-turquoise.png";
import circleBlue from "../../assets/images/circle-blue.png";
import circleRed from "../../assets/images/circle-red.png";
import circleYellow from "../../assets/images/circle-yellow.png";
import circleGreen from "../../assets/images/circle-green.png";
import circleOrange from "../../assets/images/circle-orange.png";
const myStyles = { toggle: { height: 50 } };
const combinedStyles = Object.assign({}, defaultStyles, myStyles);
const styles = StyleSheet.create(combinedStyles);
class TrashToggles extends Component {
static propTypes = {
actions: PropTypes.object,
close: PropTypes.func,
messages: PropTypes.array,
navigation: PropTypes.object,
supplyPickupToggle: PropTypes.bool,
uncollectedTrashToggle: PropTypes.bool,
trashDropOffToggle: PropTypes.bool,
myTrashToggle: PropTypes.bool,
collectedTrashToggle: PropTypes.bool,
cleanAreasToggle: PropTypes.bool
};
constructor(props) {
super(props);
}
render() {
return (
<View style={ [styles.frame, { paddingTop: 30 }] }>
<View style={ [styles.singleButtonHeader, { backgroundColor: "#EEE", marginTop: 10 }] }>
<View style={ styles.buttonBar }>
<View style={ styles.buttonBarButton }>
<TouchableOpacity style={ styles.headerButton } onPress={ this.props.close }>
<Text style={ styles.headerButtonText }>{"Close"}</Text>
</TouchableOpacity>
</View>
</View>
</View>
<View style={ [styles.infoBlockContainer, { height: 300 }] }>
<Toggle
style={ styles.toggle }
icon={ circleYellow }
label="My Trash"
value={ this.props.myTrashToggle }
onValueChange={ () => this.props.actions.toggleTrashData("myTrashToggle", !this.props.myTrashToggle) }/>
<Toggle
style={ styles.toggle }
icon={ circleRed }
label="Uncollected Trash"
value={ this.props.uncollectedTrashToggle }
onValueChange={ () => this.props.actions.toggleTrashData("uncollectedTrashToggle", !this.props.uncollectedTrashToggle) }/>
<Toggle
style={ styles.toggle }
icon={ circleBlue }
label="Trash Drop-Offs"
value={ this.props.trashDropOffToggle }
onValueChange={ () => this.props.actions.toggleTrashData("trashDropOffToggle", !this.props.trashDropOffToggle) }/>
<Toggle
style={ styles.toggle }
icon={ circleGreen }
label="Supply Pickups"
value={ this.props.supplyPickupToggle }
onValueChange={ () => this.props.actions.toggleTrashData("supplyPickupToggle", !this.props.supplyPickupToggle) }/>
<Toggle
style={ styles.toggle }
icon={ circleTurquoise }
label="Collected Trash"
value={ this.props.collectedTrashToggle }
onValueChange={ () => this.props.actions.toggleTrashData("collectedTrashToggle", !this.props.collectedTrashToggle) }/>
<Toggle
style={ styles.toggle }
icon={ circleOrange }
label="Team Cleaning Areas"
value={ this.props.cleanAreasToggle }
onValueChange={ () => this.props.actions.toggleTrashData("cleanAreasToggle", !this.props.cleanAreasToggle) }/>
</View>
</View>
);
}
}
function mapStateToProps(state) {
const collectedTrashToggle = state.trashTracker.collectedTrashToggle;
const supplyPickupToggle = state.trashTracker.supplyPickupToggle;
const uncollectedTrashToggle = state.trashTracker.uncollectedTrashToggle;
const trashDropOffToggle = state.trashTracker.trashDropOffToggle;
const myTrashToggle = state.trashTracker.myTrashToggle;
const cleanAreasToggle = state.trashTracker.cleanAreasToggle;
return { collectedTrashToggle, supplyPickupToggle, uncollectedTrashToggle, trashDropOffToggle, myTrashToggle, cleanAreasToggle };
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(TrashToggles);
|
var searchData=
[
['joystick',['Joystick',['../class_tri_1_1_input_1_1_joystick.html#a2b9df8a7989454ead020526745d49fdb',1,'Tri::Input::Joystick']]]
];
|
// native Promises are supported from Node.js 6.10 on AWS lambdas
module.exports.handler = function (event, context) {
if (event.succeed) {
const delay = event.succeed.delay;
const result = event.succeed.result;
return new Promise((resolve) => setTimeout(resolve,delay))
.then(() => result)
}
if (event.fail) {
const delay = event.fail.delay;
const err = event.fail.err;
return new Promise((resolve) => setTimeout(resolve,delay))
.then(() => {
throw new Error(err)
});
}
};
|
"use strict";
function deprecated(message, helpPage) {
if (typeof console !== "undefined" && typeof console.warn === "function") {
console.warn("[DEPRECATED] " + message + build(helpPage));
}
}
function build(helpPage) {
if (!helpPage) {
return "";
}
return ". Go to " + helpPage + " for full documentation.";
}
module.exports = deprecated;
|
const path = require('path')
const json = require('@rollup/plugin-json')
const alias = require('@rollup/plugin-alias')
const replace = require('@rollup/plugin-replace')
const PLATFORMS = {
'mp-weixin': {
prefix: 'wx',
title: '微信小程序'
},
'mp-qq': {
prefix: 'wx',
title: 'QQ小程序'
},
'mp-alipay': {
prefix: 'my',
title: '支付宝小程序'
},
'mp-baidu': {
prefix: 'swan',
title: '百度小程序'
},
'mp-toutiao': {
prefix: 'tt',
title: '头条小程序'
},
'mp-kuaishou': {
prefix: 'ks',
title: '快手小程序'
},
'mp-lark': {
prefix: 'tt',
title: '飞书小程序'
},
'mp-jd': {
prefix: 'jd',
title: '京东小程序'
},
'quickapp-webview': {
prefix: 'qa',
title: '快应用(Webview)版'
},
'app-plus': {
prefix: 'wx',
title: 'app-plus'
}
}
const platform = PLATFORMS[process.env.UNI_PLATFORM]
let input = 'src/core/runtime/index.js'
const output = {
file: `packages/uni-${process.env.UNI_PLATFORM}/dist/index.js`,
format: 'es'
}
if (process.env.UNI_MP) {
input = 'src/core/runtime/mp/index.js'
output.file = `packages/uni-${process.env.UNI_PLATFORM}/dist/mp.js`
}
module.exports = {
input,
output,
plugins: [
alias({
entries: [{
find: '@dcloudio',
replacement: path.resolve(__dirname, '../packages')
}, {
find: 'uni-shared/query',
replacement: path.resolve(__dirname, '../src/shared/query.js')
}, {
find: 'uni-shared',
replacement: path.resolve(__dirname, '../src/shared/util.js')
}, {
find: 'uni-platform',
replacement: path.resolve(__dirname, '../src/platforms/' + process.env.UNI_PLATFORM)
}, {
find: 'uni-wrapper',
replacement: path.resolve(__dirname, '../src/core/runtime/wrapper')
}, {
find: 'uni-helpers',
replacement: path.resolve(__dirname, '../src/core/helpers')
}]
}),
json(),
replace({
__GLOBAL__: platform.prefix,
__PLATFORM_TITLE__: platform.title,
__PLATFORM_PREFIX__: JSON.stringify(platform.prefix),
__PLATFORM__: JSON.stringify(process.env.UNI_PLATFORM)
})
],
external: ['vue', '@dcloudio/uni-i18n']
}
|
chromeMyAdmin.controller("CreateRoutineDialogController", ["$scope", "Events", "mySQLClientService", "typeService", "sqlExpressionService", "targetObjectService", function($scope, Events, mySQLClientService, typeService, sqlExpressionService, targetObjectService) {
"use strict";
var onShowDialog = function() {
resetErrorMessage();
$scope.routineName = "";
$scope.routineType = "PROCEDURE";
$scope.parameters = [];
$scope.routineBody = "";
$scope.deterministic = "false";
$scope.sqlSecurity = "DEFINER";
$scope.characteristic = "CONTAINS SQL";
$scope.comment = "";
$scope.returnTypeName = "INT";
$scope.returnTypeLength = null;
$scope.returnTypeOption = "";
resetNewPrameterForm();
$("#createRoutineDialog").modal("show");
};
var resetNewPrameterForm = function() {
$scope.newIo = "IN";
$scope.newParamName = "";
$scope.newTypeName = "INT";
$scope.newTypeLength = null;
$scope.newTypeOption = "";
};
var assignEventHandlers = function() {
$scope.$on(Events.SHOW_CREATE_ROUTINE_DIALOG, function(event, data) {
onShowDialog();
});
};
var setupItems = function() {
$scope.ios = ["IN", "OUT", "INOUT"];
$scope.types = typeService.getTypes();
$scope.typeOptions = ["", "UNSIGNED", "ZEROFILL", "UNSIGNED ZEROFILL"];
$scope.characteristics = ["CONTAINS SQL", "NO SQL", "READS SQL DATA", "MODIFIES SQL DATA"];
$scope.routineTypes = ["PROCEDURE", "FUNCTION"];
};
var resetErrorMessage = function() {
$scope.errorMessage = "";
};
$scope.isErrorMessageVisible = function() {
return $scope.errorMessage.length > 0;
};
$scope.initialize = function() {
resetErrorMessage();
assignEventHandlers();
setupItems();
};
$scope.aceLoaded = function(editor) {
$scope.editor = editor;
editor.setHighlightActiveLine(false);
editor.setShowPrintMargin(false);
editor.setShowInvisibles(true);
editor.getSession().setUseWrapMode(true);
};
$scope.createRoutine = function() {
var sql = "CREATE DEFINER=CURRENT_USER ";
sql += $scope.routineType + " `";
sql += $scope.routineName + "` (";
var params = [];
angular.forEach($scope.parameters, function(param) {
var p = [];
if ($scope.isProcedure()) {
p.push(param.io);
}
p.push("`" + param.paramName + "`");
var type = param.typeName;
if (param.typeLength) {
type += "(" + param.typeLength + ")";
}
p.push(type);
if (param.typeOption) {
p.push(param.typeOption);
}
params.push(p.join(" "));
});
sql += params.join(", ") + ") ";
if (!$scope.isProcedure()) {
sql += "RETURNS ";
var type = $scope.returnTypeName;
if ($scope.returnTypeLength) {
type += "(" + $scope.returnTypeLength + ")";
}
sql += type + " ";
sql += $scope.returnTypeOption + " ";
}
if ($scope.deterministic === "true") {
sql += "DETERMINISTIC ";
}
sql += "SQL SECURITY " + $scope.sqlSecurity + " ";
sql += $scope.characteristic + " ";
if ($scope.comment) {
sql += "COMMENT '" + sqlExpressionService.replaceValue($scope.comment) + "' ";
}
sql += $scope.routineBody;
mySQLClientService.query(sql).then(function(result) {
if (result.hasResultsetRows) {
$scope.fatalErrorOccurred("Creating routine failed.");
} else {
$("#createRoutineDialog").modal("hide");
targetObjectService.refreshProceduresFunctions();
}
}, function(reason) {
var errorMessage = "[Error code:" + reason.errorCode;
errorMessage += " SQL state:" + reason.sqlState;
errorMessage += "] ";
errorMessage += reason.errorMessage;
$scope.errorMessage = errorMessage;
});
};
$scope.isProcedure = function() {
return $scope.routineType === "PROCEDURE";
};
$scope.addParameter = function() {
var io = $scope.newIo;
var paramName = $scope.newParamName;
var typeName = $scope.newTypeName;
var typeLength = $scope.newTypeLength;
var typeOption = $scope.newTypeOption;
$scope.parameters.push({
io: io,
paramName: paramName,
typeName: typeName,
typeLength: typeLength ? Number(typeLength) : null,
typeOption: typeOption
});
resetNewPrameterForm();
};
$scope.deleteParameter = function(target) {
var idx = -1;
angular.forEach($scope.parameters, function(parameter, index) {
if (parameter.paramName === target.paramName) {
idx = index;
}
});
if (idx !== -1) {
$scope.parameters.splice(idx, 1);
}
};
}]);
|
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 9000));
app.use(express.static(__dirname + '/dist'));
app.get('/app', function(req, res) {
res.sendFile('./dist/index.html', {"root": __dirname});
});
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
|
//
// Copyright 2016-2018 The Last Pickle Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import jQuery from "jquery";
import React from "react";
import ReactDOM from "react-dom";
import Cookies from "js-cookie";
import snapshotScreen from "jsx/snapshot-screen";
import {
statusObservableTimer,
clusterNames,
logoutSubject, logoutResult
} from "observable";
jQuery(document).ready(function($){
document.documentElement.setAttribute('data-theme', Cookies.get('reaper-theme'));
$.urlParam = function(name){
let results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results) {
return results[1] || 0;
}
else {
return null;
}
}
let currentCluster = $.urlParam('currentCluster');
if (!currentCluster || currentCluster === "null") {
currentCluster = 'all';
}
ReactDOM.render(
React.createElement(snapshotScreen, {clusterNames, currentCluster, logoutSubject: logoutSubject, logoutResult: logoutResult,
statusObservableTimer,
switchTheme: function(theme) {
document.documentElement.setAttribute('data-theme', theme);
Cookies.set('reaper-theme', theme);
}}),
document.getElementById('wrapper')
);
});
|
import { chainMiddleware} from '../src';
import chai from 'chai';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
chai.should();
chai.use(sinonChai);
const store = {dispatch: sinon.spy((data)=>data)}
const defnext = sinon.spy((in_action)=> in_action);
const chainMW = chainMiddleware(store);
describe("Chain middleware", function() {
beforeEach(function() {
store.dispatch.reset();
defnext.reset();
});
it('Chain action was called', function() {
const action = {status: 'done',res: {called:false,linked:'a'}, link:(data) => data.linked};
chainMW(defnext)(action).should.eql(action);
defnext.should.calledOnce;
defnext.alwaysCalledWith(action).should.equal(true);
store.dispatch.should.calledOnce;
store.dispatch.alwaysCalledWith(action.res.linked).should.eql(true);
console.log(store.dispatch.returnValues[0]);
store.dispatch.alwaysReturned('a').should.equal(true);
});
it('Chain action wasn\'t called (status!=done)', function() {
const action = {status: 'inprog',res: {called:false,linked:'b'}, link:(data) => data.linked};
chainMW(defnext)(action).should.eql(action);
defnext.should.calledOnce;
defnext.alwaysCalledWith(action).should.eql(true);
store.dispatch.callCount.should.equal(0);
});
it('Chain action wasn\'t called (status == done, but link is undefined)', function() {
const action = {status: 'done',res: {called:false,linked:'b'}};
chainMW(defnext)(action).should.eql(action);
defnext.should.calledOnce;
defnext.alwaysCalledWith(action).should.eql(true);
store.dispatch.callCount.should.equal(0);
});
});
|
goog.module('grrUi.core.fileDownloadUtils');
goog.module.declareLegacyNamespace();
var AFF4_PREFIXES = {
'OS': 'fs/os', // PathSpec.PathType.OS
'TSK': 'fs/tsk', // PathSpec.PathType.TSK
'REGISTRY': 'registry', // PathSpec.PathType.REGISTRY
'TMPFILE': 'temp', // PathSpec.PathType.TMPFILE
'NTFS': 'fs/ntfs', // PathSpec.PathType.NTFS
};
/**
* @param {Object} pathspec
* @return {!Array}
*/
var splitPathspec = function(pathspec) {
var result = [];
var cur = pathspec['value'];
while (angular.isDefined(cur['pathtype'])) {
result.push(cur);
if (angular.isDefined(cur['nested_path'])) {
cur = cur['nested_path']['value'];
} else {
break;
}
}
return result;
};
/**
* Converts a given pathspec to an AFF4 path pointing to a VFS location on a
* given client.
*
* @param {Object} pathspec Typed pathspec value.
* @param {string} clientId Client id that will be used a base for an AFF4 path.
* @return {string} AFF4 path built.
* @export
*/
exports.pathSpecToAff4Path = function(pathspec, clientId) {
var components = splitPathspec(pathspec);
var firstComponent = components[0];
var result, start;
if (components.length > 1 && firstComponent['pathtype']['value'] == 'OS' &&
(components[1]['pathtype']['value'] == 'TSK' ||
components[1]['pathtype']['value'] == 'NTFS')) {
var dev = firstComponent['path']['value'];
if (angular.isDefined(firstComponent['offset'])) {
dev += ':' + Math.round(firstComponent['offset']['value'] / 512);
}
if (dev.startsWith('/')) {
dev = dev.substring(1);
}
result = [
'aff4:', clientId, AFF4_PREFIXES[components[1]['pathtype']['value']], dev
];
start = 1;
} else {
result = ['aff4:', clientId, AFF4_PREFIXES[firstComponent['pathtype']['value']]];
start = 0;
}
for (var i = start; i < components.length; ++i) {
var p = components[i];
var component = p['path']['value'];
if (component.startsWith('/')) {
component = component.substring(1);
}
if (angular.isDefined(p['offset'])) {
component += ':' + Math.round(p['offset']['value'] / 512);
}
if (angular.isDefined(p['stream_name'])) {
component += ':' + p['stream_name']['value'];
}
result.push(component);
}
return result.join('/');
};
var pathSpecToAff4Path = exports.pathSpecToAff4Path;
/**
* List of VFS roots that are accessible through Browse VFS UI.
*
* @const {Array<string>}
*/
exports.vfsRoots = ['fs', 'registry', 'temp'];
/**
* List of VFS roots that contain files that can be downloaded
* via the API.
*
* @const {Array<string>}
*/
exports.downloadableVfsRoots = ['fs', 'temp'];
/**
* Returns a pathspec of a file that a given value points to.
*
* @param {Object} value Typed value.
* @return {?Object} Pathspec of a file that a given value points to, or null
* if there's none.
* @export
*/
exports.getPathSpecFromValue = function(value) {
if (!value) {
return null;
}
if (value['type'] == 'ApiFlowResult' || value['type'] == 'ApiHuntResult') {
value = value['value']['payload'];
}
switch (value['type']) {
case 'StatEntry':
return value['value']['pathspec'];
case 'FileFinderResult':
var st = value['value']['stat_entry'];
if (angular.isDefined(st) && angular.isDefined(st['value']['pathspec'])) {
return st['value']['pathspec'];
}
return null;
case 'ArtifactFilesDownloaderResult':
return exports.getPathSpecFromValue(value['value']['downloaded_file']);
default:
return null;
}
};
/**
* @param {Object} value
* @param {string} downloadUrl
* @param {Object} downloadParams
*/
const makeStatEntryDownloadable_ = function(
value, downloadUrl, downloadParams) {
var originalValue = angular.copy(value);
for (var prop in value) {
if (value.hasOwnProperty(prop)) {
delete value[prop];
}
}
angular.extend(value, {
type: '__DownloadableStatEntry',
originalValue: originalValue,
downloadUrl: downloadUrl,
downloadParams: downloadParams
});
};
/**
* @param {Object} value
* @param {string} downloadUrl
* @param {Object} downloadParams
*/
const makeFileFinderResultDownloadable_ = function(
value, downloadUrl, downloadParams) {
makeStatEntryDownloadable_(
value['value']['stat_entry'], downloadUrl, downloadParams);
};
/**
* @param {Object} value
* @param {string} downloadUrl
* @param {Object} downloadParams
*/
const makeArtifactFilesDownloaderResultDownloadable_ = function(
value, downloadUrl, downloadParams) {
exports.makeValueDownloadable(
value['value']['downloaded_file'], downloadUrl, downloadParams);
};
/**
* @param {Object} value
* @param {string} downloadUrl
* @param {Object} downloadParams
* @return {boolean}
*/
exports.makeValueDownloadable = function(value, downloadUrl, downloadParams) {
if (!value) {
return false;
}
if (value['type'] === 'ApiFlowResult' || value['type'] === 'ApiHuntResult') {
value = value['value']['payload'];
}
switch (value['type']) {
case 'StatEntry':
makeStatEntryDownloadable_(value, downloadUrl, downloadParams);
return true;
case 'FileFinderResult':
makeFileFinderResultDownloadable_(value, downloadUrl, downloadParams);
return true;
case 'ArtifactFilesDownloaderResult':
makeArtifactFilesDownloaderResultDownloadable_(
value, downloadUrl, downloadParams);
return true;
default:
return false;
}
};
|
;;;;
// Flash callback
function idp_xx_movie_DoFSCommand(cmd, args) {
// alert(cmd);
if ("undefined" != typeof mainWindow) {
mainWindow.onFSCommand(cmd, args);
}else{
alert("no mainwindow");
}
}
// Create movie
var t = '';
t += '<embed name="idp_xx_movie" id="idp_xx_movie" src="' + url + '" ';
t += 'width="100%" height="100%" ';
t += 'type="application/x-shockwave-flash" ';
t += 'flashvars="' + vars + '"></embed>';
document.close();
// document.write will open a new document
document.write(t);
|
(function() {
'use strict';
angular
.module('cribbleApp')
.factory('JhiMetricsService', JhiMetricsService);
JhiMetricsService.$inject = ['$rootScope', '$http'];
function JhiMetricsService ($rootScope, $http) {
var service = {
getMetrics: getMetrics,
threadDump: threadDump
};
return service;
function getMetrics () {
return $http.get('management/metrics').then(function (response) {
return response.data;
});
}
function threadDump () {
return $http.get('management/dump').then(function (response) {
return response.data;
});
}
}
})();
|
var classorg_1_1onosproject_1_1cli_1_1net_1_1HostRemoveCommand =
[
[ "execute", "classorg_1_1onosproject_1_1cli_1_1net_1_1HostRemoveCommand.html#a4960a063b349a69cf44f0b607ce4cabb", null ]
];
|
jQuery(document).ready(function ($) {
var string_locator_search_active = false;
var add_notice = function( title, message, format ) {
$(".notices").append( '<div class="notice notice-' + format + ' is-dismissible"><p><strong>' + title + '</strong><br />' + message + '</p></div>' );
};
var throw_error = function( title, message ) {
string_locator_search_active = false;
$(".string-locator-feedback").hide();
add_notice( title, message, 'error' );
};
var finalize_string_locator_search = function() {
string_locator_search_active = false;
$("#string-locator-feedback-text").text('');
var search_finalized = {
action : 'string-locator-clean',
nonce : string_locator.search_nonce
};
$.post(
string_locator.ajax_url,
search_finalized,
function( response ) {
$(".string-locator-feedback").hide();
if ( $("tbody", ".tools_page_string-locator").is(":empty") ) {
$("tbody", ".tools_page_string-locator").html( '<tr><td colspan="3">' + string_locator.search_no_results + '</td></tr>' );
}
}
).fail(function(xhr, textStatus, errorThrown) {
throw_error( xhr.status + ' ' + errorThrown, string_locator.search_error );
});
};
var clear_string_locator_result_area = function() {
$(".notices").html('');
$("#string-locator-search-progress").removeAttr( 'value' );
$("tbody", ".tools_page_string-locator").html('');
};
var perform_string_locator_single_search = function( maxCount, thisCount ) {
if ( thisCount >= maxCount || ! string_locator_search_active ) {
$("#string-locator-feedback-text").html( string_locator.saving_results_string );
finalize_string_locator_search();
return false;
}
var search_request = {
action : 'string-locator-search',
filenum : thisCount,
nonce : string_locator.search_nonce
};
$.post(
string_locator.ajax_url,
search_request,
function ( response ) {
console.dir( response)
if ( ! response.success ) {
add_notice( string_locator.warning_title, response.data, 'warning' );
}
if ( undefined !== response.data.search ) {
$("#string-locator-search-progress").val( response.data.filenum );
$("#string-locator-feedback-text").html( string_locator.search_current_prefix + response.data.next_file );
string_locator_append_result( response.data.search );
}
var nextCount = response.data.filenum + 1;
perform_string_locator_single_search( maxCount, nextCount );
},
'json'
).fail(function(xhr, textStatus, errorThrown) {
throw_error( xhr.status + ' ' + errorThrown, string_locator.search_error );
});
};
var string_locator_append_result = function( total_entries ) {
if ( $(".no-items", ".tools_page_string-locator").is(':visible') ) {
$(".no-items", ".tools_page_string-locator").hide();
}
if ( Array !== total_entries.constructor ) {
return false;
}
total_entries.forEach( function ( entries ) {
if ( entries ) {
for (var i = 0, amount = entries.length; i < amount; i++) {
var entry = entries[i];
if (undefined !== entry.stringresult) {
var builtHTML = '<tr>' +
'<td>' + entry.stringresult + '<div class="row-actions"><span class="edit"><a href="' + entry.editurl + '" aria-label="Edit">Edit</a></span></div></td>' +
'<td>' + entry.filename + '</td>' +
'<td>' + entry.linenum + '</td>' +
'</tr>';
$("tbody", ".tools_page_string-locator").append(builtHTML);
}
}
}
} );
};
$("#string-locator-search-form").on( 'submit', function (e) {
e.preventDefault();
$("#string-locator-feedback-text").text(string_locator.search_preparing );
$(".string-locator-feedback").show();
string_locator_search_active = true;
clear_string_locator_result_area();
var directory_request = {
action : 'string-locator-get-directory-structure',
directory : $("#string-locator-search").val(),
search : $("#string-locator-string").val(),
regex : $("#string-locator-regex").is(':checked'),
nonce : string_locator.search_nonce
};
$("table.tools_page_string-locator").show();
$.post(
string_locator.ajax_url,
directory_request,
function ( response ) {
if ( ! response.success ) {
add_notice( response.data, 'alert' );
return;
}
$("#string-locator-search-progress").attr( 'max', response.data.total ).val( response.data.current );
$("#string-locator-feedback-text").text(string_locator.search_started );
perform_string_locator_single_search( response.data.total, 0 );
},
'json'
).fail(function(xhr, textStatus, errorThrown) {
throw_error( xhr.status + ' ' + errorThrown, string_locator.search_error );
});
});
});
|
import React, {Component, PropTypes} from 'react';
import MiddleArticleList from './MiddleArticleList';
import RightDetail from '../RightDetail';
import NoMatchImg from '../NoMatchImg';
import Detail from './Detail';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {selectArticle, saveArticle, deleteArticle} from '../../../store/actions/Article.js';
import styles from './Main.less';
@connect(
state=> {
return {state: state.Article}
},
dispatch=>bindActionCreators({selectArticle, saveArticle, deleteArticle}, dispatch)
)
export default class ArticleMain extends Component {
static defaultProps = {};
static propTypes = {};
constructor (props) {
super(props);
};
componentWillMount () {
}
componentDidMount () {
}
shouldComponentUpdate () {
return true;
}
componentWillUpdate () {
}
componentDidUpdate () {
}
componentWillUnmount () {
}
render () {
let children = (() => {
if (this.props.state.selectIdx != -1) {
return <Detail data={this.props.state.select} save={this.props.saveArticle}
delete={this.props.deleteArticle}
saveing={this.props.state.saveing}
/>;
} else {
return <NoMatchImg/>;
}
})();
return (<div className={styles.Main}>
<MiddleArticleList/>
<RightDetail>
{children}
</RightDetail>
</div>);
}
}
|
'use strict';
var path = require('path');
var conf = require('./gulp/conf');
var _ = require('lodash');
var wiredep = require('wiredep');
var pathSrcHtml = [
path.join(conf.paths.src, '/**/*.html')
];
function listFiles() {
var wiredepOptions = _.extend({}, conf.wiredep, {
dependencies: true,
devDependencies: true
});
var patterns = wiredep(wiredepOptions).js
.concat([
path.join(conf.paths.src, '/app/**/*.module.js'),
path.join(conf.paths.src, '/app/**/*.js'),
path.join(conf.paths.src, '/**/*.spec.js'),
path.join(conf.paths.src, '/**/*.mock.js'),
])
.concat(pathSrcHtml);
var files = patterns.map(function(pattern) {
return {
pattern: pattern
};
});
files.push({
pattern: path.join(conf.paths.src, '/assets/**/*'),
included: false,
served: true,
watched: false
});
return files;
}
module.exports = function(config) {
var configuration = {
files: listFiles(),
singleRun: true,
autoWatch: false,
ngHtml2JsPreprocessor: {
stripPrefix: conf.paths.src + '/',
moduleName: 'appDdhh'
},
logLevel: 'WARN',
frameworks: ['phantomjs-shim', 'jasmine', 'angular-filesort'],
angularFilesort: {
whitelist: [path.join(conf.paths.src, '/**/!(*.html|*.spec|*.mock).js')]
},
browsers : ['PhantomJS'],
plugins : [
'karma-phantomjs-launcher',
'karma-angular-filesort',
'karma-phantomjs-shim',
'karma-coverage',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
],
coverageReporter: {
type : 'html',
dir : 'coverage/'
},
reporters: ['progress'],
proxies: {
'/assets/': path.join('/base/', conf.paths.src, '/assets/')
}
};
// This is the default preprocessors configuration for a usage with Karma cli
// The coverage preprocessor is added in gulp/unit-test.js only for single tests
// It was not possible to do it there because karma doesn't let us now if we are
// running a single test or not
configuration.preprocessors = {};
pathSrcHtml.forEach(function(path) {
configuration.preprocessors[path] = ['ng-html2js'];
});
// This block is needed to execute Chrome on Travis
// If you ever plan to use Chrome and Travis, you can keep it
// If not, you can safely remove it
// https://github.com/karma-runner/karma/issues/1144#issuecomment-53633076
if(configuration.browsers[0] === 'Chrome' && process.env.TRAVIS) {
configuration.customLaunchers = {
'chrome-travis-ci': {
base: 'Chrome',
flags: ['--no-sandbox']
}
};
configuration.browsers = ['chrome-travis-ci'];
}
config.set(configuration);
};
|
nmeta.FlowsBackGridView = Backbone.View.extend({
initialize:function (options) {
// Specify columns that will be displayed in Backgrid:
var columns = [{
name: "timestamp",
label: "Timestamp",
editable: false,
// Extend UriCell to have timestamp custom link to flow_hash value:
cell: Backgrid.UriCell.extend({
render: function () {
this.$el.empty();
var formattedValue = this.formatter.fromRaw(this.model.get('timestamp'), this.model);
this.$el.append($("<a>", {
href: "#flowDetails/" + this.model.get('flow_hash'),
title: 'click for flow details'
}).text(formattedValue));
this.delegateEvents();
return this;
}
}),
}, {
name: "src_location_logical",
label: "Src Location",
editable: false,
cell: "string"
}, {
name: "src",
label: "Src",
editable: false,
cell: "string"
}, {
name: "dst",
label: "Dst",
editable: false,
cell: "string"
}, {
name: "proto",
label: "Proto",
editable: false,
cell: "string"
}, {
name: "tp_src",
label: "TP Src",
editable: false,
cell: "string"
}, {
name: "tp_dst",
label: "TP Dst",
editable: false,
cell: "string"
}, {
name: "classification",
label: "Classification",
editable: false,
cell: "string"
}, {
name: "actions",
label: "Actions",
editable: false,
cell: "string"
}, {
name: "data_sent",
label: "Sent",
editable: false,
cell: "string"
}, {
name: "data_received",
label: "Received",
editable: false,
cell: "string"
}];
// Set up a Backgrid grid to use the pageable collection
this.pageableGrid = new Backgrid.Grid({
columns: columns,
collection: this.model
});
// Display a loading indication whenever the Collection is fetching.
this.model.on("request", function() {
this.$el.html("Loading...");
}, this);
this.model.on('reset', this.render, this);
this.model.on('change', this.render, this);
},
render:function () {
console.log('FlowsBackgridView render function');
// Start with empty el:
this.$el.empty();
// Render the grid:
this.$el.append(this.pageableGrid.render().el)
return this;
},
});
|
'use strict';
module.exports = function (grunt) {
var appPath = './app/';
var tempPath = './tmp/';
var resourcePath = '../src/main/resources/';
var javaAppArtifactLocation = '../build/libs/';
var javaAppPort = 8080;
var globalConfig = {
generatedAssetDestination: '../src/main/resources/static/',
buildDestination: '../build/resources/main/public/gen/',
resourceDestination: resourcePath,
appPath: appPath,
tempPath: tempPath,
jsPath: appPath + 'js/',
partialsPath: appPath + 'partials/',
lessPath: appPath + 'less/',
};
grunt.initConfig({
globalConfig: globalConfig,
availabletasks: {
tasks: {}
},
uglify: {
manam: {
options: {
compress: {
drop_debugger: false
},
mangle: false,
preserveComments: 'all',
beautify: true,
ASCIIOnly: true,
sourceMap: true,
sourceMapName: '<%= globalConfig.generatedAssetDestination %>manam.js.map',
sourceMapIncludeSources: true
},
files: {
'<%= globalConfig.generatedAssetDestination %>manam.js': [
'<%= globalConfig.jsPath %>ManamCommon.js',
'<%= globalConfig.jsPath %>ManamApp.js',
'<%= globalConfig.jsPath %>manam/**/*.js',
'<%= globalConfig.jsPath %>services/**/*.js',
'<%= globalConfig.jsPath %>repositories/**/*.js',
'<%= globalConfig.jsPath %>directives/**/*.js',
'<%= globalConfig.jsPath %>filters/**/*.js',
'<%= globalConfig.tempPath %>partials.js'
]
}
},
thirdParty: {
options: {
mangle: false,
preserveComments: 'all',
beautify: true,
ASCIIOnly: true,
sourceMap: true,
sourceMapName: '<%= globalConfig.generatedAssetDestination %>thirdParty.js.map',
sourceMapIncludeSources: true
},
files: {
'<%= globalConfig.generatedAssetDestination %>thirdParty.js': [require('./third-party-app-dependencies')]
}
}
},
html2js: {
options: {
module: 'partials',
base: '<%= globalConfig.partialsPath %>'
},
main: {
src: ['<%= globalConfig.partialsPath %>**/*.html'],
dest: '<%= globalConfig.tempPath %>partials.js'
}
},
less: {
manam: {
options: {
paths: ['<%= globalConfig.lessPath %>'],
sourceMap: true,
sourceMapFileInline: true
},
files: {
'<%= globalConfig.generatedAssetDestination %>manam.css': '<%= globalConfig.lessPath %>manam.less'
}
}
},
copy: {
generatedFilesToBuild: {
expand: true,
src: ['**/*'],
cwd: '<%= globalConfig.generatedAssetDestination %>',
dest: '<%= globalConfig.buildDestination %>'
}
}
});
require('load-grunt-tasks')(grunt);
grunt.loadNpmTasks('grunt-available-tasks');
grunt.loadNpmTasks('grunt-html2js');
grunt.registerTask('clean', function () {
grunt.file.delete(globalConfig.buildDestination, {force: true});
});
grunt.registerTask('default', ['clean', 'html2js', 'uglify', 'copy:generatedFilesToBuild']);
grunt.registerTask('task', ['availabletasks']);
}
|
/*
* Waltz - Enterprise Architecture
* Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project
* See README.md for more information
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific
*
*/
import _ from "lodash";
import {initialiseData} from "../common";
import {CORE_API} from "../common/services/core-api-utils";
import template from "./user-management.html";
import roles from "./system-roles";
const initialState = {
numAllowedWithoutFilter: 100,
roles
};
function filterUsers(users = [], qry = null) {
if (_.isEmpty(users) || qry === '') return [];
const qryStr = _.toLower(qry);
return users.filter(user => user.searchStr.indexOf(qryStr) > -1);
}
function enrichUsersWithSearchStr(user) {
const searchStr = _.toLower(user.userName);
return Object.assign({}, user, { searchStr });
}
function controller(serviceBroker) {
const vm = initialiseData(this, initialState);
serviceBroker.loadViewData(CORE_API.UserStore.findAll, [])
.then(result => {
vm.users = _.map(result.data, d => enrichUsersWithSearchStr(d));
if(vm.users.length <= vm.numAllowedWithoutFilter) {
vm.filteredUsers = vm.users;
}
});
serviceBroker.loadViewData(CORE_API.RoleStore.findAllRoles, [])
.then(result => vm.roles = result.data);
const refresh = () => {
vm.filteredUsers=[] = filterUsers(vm.users, vm.qry);
};
vm.onQueryStrChange = (qry) => {
vm.qry = qry;
refresh();
};
vm.dismiss = () => {
vm.newUser = null;
vm.selectedUser = null;
vm.newPassword1 = null;
vm.newPassword2 = null;
};
vm.userSelected = (user) => {
vm.dismiss();
vm.selectedUser = user;
vm.roleSelections = _.reduce(
user.roles,
(acc, role) => { acc[role] = true; return acc; },
{});
};
vm.addUserSelected = () => {
vm.dismiss();
vm.newUser = { userName: "", password: ""};
};
vm.isValidNewUser = (user) => {
return user.userName && user.password;
};
vm.registerUser = (user) => {
serviceBroker
.execute(CORE_API.UserStore.register, [user])
.then(
() => {
vm.userSelected(user);
vm.users = [...vm.users, user];
},
err => {
console.error("Error registering user: ", err);
vm.lastError = err.data;
}
);
};
vm.updateUser = (user, roleSelections, password1, password2) => {
if (password1 !== password2) {
vm.lastError = { id: "MISMATCH", message: "Passwords do not match"};
return;
}
const roles = _.chain(roleSelections)
.map((v, k) => v ? k : null) // get selected key name or null if not selected
.compact() // remove non selected names
.value();
serviceBroker
.execute(CORE_API.UserStore.updateRoles, [user.userName, roles])
.then(
() => {
user.roles = roles;
vm.dismiss();
},
e => {
vm.lastError = e.data;
}
);
if (password1) {
serviceBroker
.execute(CORE_API.UserStore.resetPassword, [user.userName, password1]);
}
};
vm.hasRole = (user, role) => {
const existingRoles = user.roles || [];
return existingRoles.indexOf(role) > -1;
};
vm.deleteUser = (user) => {
serviceBroker
.execute(CORE_API.UserStore.deleteUser, [user.userName])
.then(
() => {
vm.users = _.reject(vm.users, u => u === user);
vm.dismiss();
},
e => vm.lastError = e.data
);
return false; // prevent form submission
};
function setAllSelectionsTo(b) {
vm.roleSelections = _.reduce(
_.map(vm.roles, "key"),
(acc, k) => {
acc[k] = b;
return acc;
},
{});
}
vm.selectAll = () => {
setAllSelectionsTo(true);
};
vm.deselectAll = () => {
setAllSelectionsTo(false);
};
}
controller.$inject = [ "ServiceBroker" ];
export default {
template,
controller,
controllerAs: "ctrl",
bindToController: true,
scope: {}
};
|
const React = require('react');
const classNames = require('classnames');
/**
* Component that renders a day on the calendar.
*/
class CalendarDayRenderer extends React.Component {
render() {
const day = this.props.day;
const month = this.props.month;
const dayClass = day.month() === month.month() ? classNames('calendar-day') : classNames('calendar-day-non-current');
return (
<table>
<tbody>
<tr>
<td className={dayClass}>{day.date()}</td>
</tr>
</tbody>
</table>
);
}
}
CalendarDayRenderer.propTypes = {
month: React.PropTypes.object.isRequired,
day: React.PropTypes.object.isRequired,
};
module.exports = CalendarDayRenderer;
|
var data = [
{title:'Basic Information', hasChild:true, test:'../examples/about_troy_more/basic_info.js'},
{title:'Vision Statement', hasChild:true, test:'../examples/about_troy_more/vision.js'},
{title:'ESLRs', hasChild:true, test:'../examples/about_troy_more/eslr_s.js'}
];
var tableview = Titanium.UI.createTableView({
data:data
});
tableview.addEventListener('click', function(e){
if(e.rowData.test){
var win = null;
win = Titanium.UI.createWindow({
url:e.rowData.test,
title:e.rowData.title,
backgroundColor:'#fff',
barColor:'#B22222'
});
if (e.index == 3)
{
win.hideTabBar();
}
Titanium.UI.currentTab.open(win,{animated:true});
}
});
Titanium.UI.currentWindow.add(tableview);
Titanium.UI.currentWindow.addEventListener('focus', function()
{
Ti.API.info('FOCUS RECEIVED IN base_ui');
});
|
var funcModule = require('./functions');
console.log(funcModule.multiply(10));
console.log(funcModule.getScore());
|
'use strict';
require('./controllers/index');
require('./directives/index');
require('./services/analysis-tasks');
require('./services/co-occurrence-matches');
require('./services/match-counts');
|
//// [/lib/initial-buildOutput.txt]
/lib/tsc --b /src/with-references
exitCode:: ExitStatus.Success
//// [/src/core/index.d.ts]
export declare function multiply(a: number, b: number): number;
//# sourceMappingURL=index.d.ts.map
//// [/src/core/index.d.ts.map]
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB"}
//// [/src/core/index.js]
"use strict";
exports.__esModule = true;
function multiply(a, b) { return a * b; }
exports.multiply = multiply;
//// [/src/core/tsconfig.tsbuildinfo]
{
"program": {
"fileInfos": {
"../../lib/lib.d.ts": {
"version": "3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };",
"signature": "3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };"
},
"./index.ts": {
"version": "5112841898-export function multiply(a: number, b: number) { return a * b; }\r\n",
"signature": "3361149553-export declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map"
}
},
"options": {
"composite": true,
"declaration": true,
"declarationMap": true,
"skipDefaultLibCheck": true,
"configFilePath": "./tsconfig.json"
},
"referencedMap": {},
"exportedModulesMap": {},
"semanticDiagnosticsPerFile": [
"../../lib/lib.d.ts",
"./index.ts"
]
},
"version": "FakeTSVersion"
}
|
var EnemyStep = [
{
id:0,
stepAttack: 1,
stepDefense: .13,
stepHP:1.30,
stepRange:2.4,
stepAttackSpeed:1,
stepVelocity:0.14,
coinValueStep: 1,
scoreValueStep: 1.2
},
{
id:1,
stepAttack: 1,
stepDefense: .14,
stepHP:1.6,
stepRange:2.4,
stepAttackSpeed:1,
stepVelocity:0.11,
coinValueStep: 1,
scoreValueStep: 1.2
},
{
id:2,
stepAttack: 1,
stepDefense: .163,
stepHP:1.75,
stepRange:2.4,
stepAttackSpeed:1,
stepVelocity:0.11,
coinValueStep: 1,
scoreValueStep: 1.2
}
];
var EnemyType = [
{
type:0,
enemyStep: EnemyStep[0],
textureName:"images/soldiers.png",
widthImg: 25,
heightImg: 20,
bulletType:"B0.png",
scoreValue: 15,
coinValue: 4,
HP:1.25,
attack:.5,
attackSpeed:1,
defense: 0.12,
velocity: 0.9,
range:10,
dieSound: "",
getSprites: function(){
return new SpriteSheet({
height: 20,
width: 25,
sprites: [
{ name: 'walk0', x: 0, y: 0 },
{ name: 'walk1', x: 0, y: 0 },
//{ name: 'walk2', x: 0, y: 0 }
]
});
},
animateSpr:function( sprites, timeP ){
return new Animation([
{ sprite: 'walk0', time: timeP },
{ sprite: 'walk1', time: timeP },
//{ sprite: 'walk2', time: timeP }
], sprites );
}
},{
type:1,
enemyStep: EnemyStep[1],
textureName:"images/tanks.png",
widthImg: 30,
heightImg: 30,
bulletType:"B0.png",
scoreValue:15,
coinValue:6,
HP:4.0,
attack:.5,
attackSpeed:1,
defense:.012,
velocity: 0.4,
range:10,
dieSound: "die1",
getSprites: function(){
return new SpriteSheet({
width: 30,
height: 30,
sprites: [
{ name: 'walk0', x: 0, y: 0 }
]
});
},
animateSpr:function( sprites, timeP ){
return new Animation([
{ sprite: 'walk0', time: timeP }
], sprites );
}
},{
type:2,
enemyStep: EnemyStep[2],
textureName:"images/tanks.png",
widthImg: 30,
heightImg: 30,
bulletType:"B0.png",
scoreValue:15,
coinValue:7,
HP:5,
attack:.5,
attackSpeed:2,
defense:.015,
velocity: 0.35,
range:15,
dieSound: "die1",
getSprites: function(){
return new SpriteSheet({
width: 30,
height: 30,
sprites: [
{ name: 'walk0', x: 30, y: 0 }
]
});
},
animateSpr:function( sprites, timeP ){
return new Animation([
{ sprite: 'walk0', time: timeP }
], sprites );
}
}
];
|
angular.module('hybridapp.controllers')
.controller('LocationCtrl', ['$rootScope', '$scope', '$http', '$ionicScrollDelegate', 'appConfig', function ($rootScope, $scope, $http, $ionicScrollDelegate, appConfig) {
var locationData = [];
var sortedLocationData = [];
$scope.showMap = false;
$scope.origin = null;
$scope.locations = null;
$scope.scrollTop = function() {
$ionicScrollDelegate.scrollTop();
};
$scope.scrollBottom = function() {
$ionicScrollDelegate.scrollBottom();
};
$scope.toggleMap = function(active) {
$scope.showMap = active;
$scope.scrollTop();
};
$scope.showDetails = function (location) {
$rootScope.currentLocation = location;
window.location.href = "#/app/location/details/" + location.detailsUrl;
};
getCurrentPosition();
function getCurrentPosition() {
if (navigator.geolocation) {
console.log("Attempting to get current position");
var posOptions = {maximumAge: 60000, timeout: 5000, enableHighAccuracy: true};
navigator.geolocation.getCurrentPosition(onFoundPosition, positionError, posOptions);
} else {
alert("GeoLocation is not supported in this mode");
}
}
function positionError(error) {
console.log("Failed to get current position. Error code: " + error.code + " Message: " + error.message);
//Use GOOGLE HQ as default if failed to get current position...
var defaultPosition = {coords: {latitude: 37.422858, longitude: -122.085065}};
onFoundPosition(defaultPosition);
}
function onFoundPosition(position) {
$scope.origin = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
console.log("current position found at: " + $scope.origin.lat + " " + $scope.origin.lng);
if (sortedLocationData.length == 0) {
loadLocations();
}
}
function loadLocations() {
$http.get(appConfig.basePath + '/en/welcome/locations.locationdata.json')
.then(renderLocations, locationError);
}
function locationError(error) {
alert("Unable to load location data: " + error.message);
}
function renderLocations(response) {
locationData = response.data;
sortLocations($scope.origin);
$scope.locations = sortedLocationData;
}
function sortLocations(origin) {
applyDistance(origin);
if (angular.isArray(locationData)) {
sortedLocationData = locationData.sort(compareDistance);
} }
/** Converts numeric degrees to radians */
if (typeof Number.prototype.toRad == 'undefined') {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
}
function compareDistance(a,b) {
if (a.distance == undefined || b.distance == undefined) return 0;
if (a.distance < b.distance)
return -1;
if (a.distance > b.distance)
return 1;
return 0;
}
function calculateDistance(start, end) {
var d = 0;
if (start && end) {
var R = 6371;
var lat1 = start.lat.toRad(), lon1 = start.lng.toRad();
var lat2 = end.lat.toRad(), lon2 = end.lng.toRad();
var dLat = lat2 - lat1;
var dLon = lon2 - lon1;
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
d = R * c;
}
return d;
}
function applyDistance(origin) {
if (origin.lat && origin.lng) {
for (var i=0; i < locationData.length; i++) {
var loc = locationData[i];
loc["distance"] = calculateDistance(origin, {lat:loc.latitude,lng:loc.longitude});
}
}
}
function showError(error) {
alert("Getting the error" + error.code + "\nerror mesg :" + error.message);
}
}])
.filter('masterLocation', function() {
return function(items) {
var filtered = [];
if (!items) {
return filtered;
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item.master) {
filtered.push(item);
}
}
return filtered;
}
})
.filter('secondaryLocation', function() {
return function(items) {
var filtered = [];
if (!items) {
return filtered;
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (!item.master) {
filtered.push(item);
}
}
return filtered;
}
})
.filter('distance', function() {
function formatDistance(d) {
d = d || 0;
if (d > 1) {
return Math.round(d) + " km";
} else {
d = d * 1000;
return Math.round(d) + " m";
}
}
return function(input) {
return formatDistance(input);
}
})
;
|
/**
* File: consumer.js
* Description: This is the AMQP consumer handles incoming
* communication from clients publishing messages to a broker server.
* Messages can be received over AMQP exchange types including one-to-one,
* from broadcast pattern, or selectively using specified binding key.
*
* Author: Eamin Zhang
* robomq.io (http://www.robomq.io)
*/
var amqp = require("amqplib");
var domain = require("domain");
var server = "hostname";
var port = "5672";
var vhost = "yourvhost"; //for "/" vhost, use "%2f" instead
var username = "username";
var password = "password";
var exchangeName = "testEx";
var queueName = "testQ1";
var routingKey = "test.#"; //topic with wildcard
//use domain module to handle reconnecting
var consumer = null;
var dom = domain.create();
dom.on("error", relisten);
dom.run(listen);
function listen() {
consumer = amqp.connect("amqp://" + username + ":" + password + "@" + server + ":" + port + "/" + vhost + "?heartbeat=60");
consumer.then(function(conn) {
return conn.createChannel().then(function(ch) {
ch.assertExchange(exchangeName, "topic", {durable: false, autoDelete: true});
ch.assertQueue(queueName, {durable: false, autoDelete: true, exclusive: true});
ch.bindQueue(queueName, exchangeName, routingKey);
ch.consume(queueName, function(message) {
//callback funtion on receiving messages
console.log(message.content.toString());
}, {noAck: true});
});
}).then(null, function(err) {
console.error("Exception handled, reconnecting...\nDetail:\n" + err);
setTimeout(listen, 5000);
});
}
function relisten() {
consumer.then(function(conn) {
conn.close();
});
setTimeout(listen, 5000);
}
|
/**
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Constants to be used by the siddhi server and the siddhi web worker
* This is not directly imported by the web worker since some of the constants are initiated using the window object
* The SiddhiEditor.constants in passed into the web worker when the siddhi worker is initialized
*/
define(function() {
"use strict"; // JS strict mode
/**
* Constants used by the server
*/
var constants = {
SOURCE: "source",
IO: "io",
MAP: "map",
STORE: "store",
FUNCTION_OPERATION: "functionOperation",
FUNCTIONS: "functions",
STREAM_PROCESSORS: "streamProcessors",
WINDOW_PROCESSORS: "windowProcessors",
STREAMS: "streams",
INNER_STREAMS: "innerStreams",
EVENT_TABLES: "eventTables",
TRIGGERS: "eventTriggers",
AGGREGATIONS: "aggregations",
WINDOWS: "eventWindows",
EVAL_SCRIPTS: "evalScripts",
ATTRIBUTES: "attributes",
LOGICAL_OPERATORS: "logicalOperators",
DATA_TYPES: "dataTypes",
SNIPPETS: "snippet",
SNIPPET_SIDDHI_CONTEXT: "siddhi" // Context provided to the snippet manager to register the snippets
};
// Server side validation related constants
constants.SERVER_URL = window.location.protocol + "//" + window.location.host + "/server/";
constants.SERVER_SIDE_VALIDATION_DELAY = 1000; // Token tooltips are also updated after this delay
constants.TOOLTIP_SHOW_DELAY = 1000; // Time the user needs to hover the mouse to get the tooltip
// Constants related to the completion data generated by the data population listener
constants.dataPopulation = {
UNDEFINED_DATA_TYPE: "#"
};
/*
* Names displayed in the server
*/
constants.typeToDisplayNameMap = {};
constants.typeToDisplayNameMap[constants.FUNCTIONS] = "Function";
constants.typeToDisplayNameMap[constants.STREAM_PROCESSORS] = "Stream Processor";
constants.typeToDisplayNameMap[constants.WINDOW_PROCESSORS] = "Window Processor";
constants.typeToDisplayNameMap[constants.STREAMS] = "Stream";
constants.typeToDisplayNameMap[constants.INNER_STREAMS] = "Inner Stream";
constants.typeToDisplayNameMap[constants.EVENT_TABLES] = "Event Table";
constants.typeToDisplayNameMap[constants.TRIGGERS] = "Event Trigger";
constants.typeToDisplayNameMap[constants.WINDOWS] = "Event Window";
constants.typeToDisplayNameMap[constants.EVAL_SCRIPTS] = "Eval Script";
constants.typeToDisplayNameMap[constants.ATTRIBUTES] = "Attribute";
constants.typeToDisplayNameMap[constants.LOGICAL_OPERATORS] = "Logical Operator";
constants.typeToDisplayNameMap[constants.DATA_TYPES] = "Data Type";
constants.typeToDisplayNameMap[constants.SNIPPETS] = "Snippet";
constants.typeToDisplayNameMap[constants.AGGREGATIONS] = "Aggregation";
/*
* Ace server library related constants
*/
constants.ace = {
SNIPPET_MANAGER: "ace/snippets",
LANG_TOOLS: "ace/ext/language_tools",
SIDDHI_MODE: "ace/mode/siddhi",
DEFAULT_THEME: "ace/theme/twilight",
ACE_RANGE: "ace/range",
LANG_LIB: "ace/lib/lang",
TOKEN_TOOLTIP: "ace/token/tooltips"
};
/*
* ANTLR related constants
*/
constants.antlr = {
INDEX: "antlr4-js-runtime/index",
ROOT: "antlr/",
SYNTAX_ERROR_LISTENER: "SyntaxErrorListener",
SIDDHI_DATA_POPULATION_LISTENER: "DataPopulationListener",
SIDDHI_TOKEN_TOOL_TIP_UPDATE_LISTENER: "TokenTooltipPointRecognitionListener",
SIDDHI_PARSER: "gen/SiddhiQLParser",
SIDDHI_LEXER: "gen/SiddhiQLLexer"
};
/*
* Web worker related constants
* Used in declaring the message type
*/
constants.worker = {
INIT: "INIT",
EDITOR_CHANGE_EVENT: "EDITOR_CHANGE_EVENT",
GENERATE_TOKEN_TOOLTIP: "GENERATE_TOKEN_TOOLTIP",
PARSE_TREE_GENERATION_COMPLETION: "PARSE_TREE_GENERATION_COMPLETION",
DATA_POPULATION_COMPLETION: "DATA_POPULATION_COMPLETION",
TOKEN_TOOLTIP_POINT_RECOGNITION_COMPLETION: "TOKEN_TOOLTIP_POINT_RECOGNITION_COMPLETION"
};
return constants;
});
|
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var resolve = require( 'path' ).resolve;
var tape = require( 'tape' );
var floor = require( '@stdlib/math/base/special/floor' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var float64ToFloat32 = require( '@stdlib/number/float64/base/to-float32' );
var Float32Array = require( '@stdlib/array/float32' );
var tryRequire = require( '@stdlib/utils/try-require' );
// VARIABLES //
var svariancech = tryRequire( resolve( __dirname, './../lib/svariancech.native.js' ) );
var opts = {
'skip': ( svariancech instanceof Error )
};
// TESTS //
tape( 'main export is a function', opts, function test( t ) {
t.ok( true, __filename );
t.strictEqual( typeof svariancech, 'function', 'main export is a function' );
t.end();
});
tape( 'the function has an arity of 4', opts, function test( t ) {
t.strictEqual( svariancech.length, 4, 'has expected arity' );
t.end();
});
tape( 'the function calculates the population variance of a strided array', opts, function test( t ) {
var x;
var v;
x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 0.0, 3.0 ] );
v = svariancech( x.length, 0, x, 1 );
t.strictEqual( v, float64ToFloat32( 53.5/x.length ), 'returns expected value' );
x = new Float32Array( [ -4.0, -4.0 ] );
v = svariancech( x.length, 0, x, 1 );
t.strictEqual( v, 0.0, 'returns expected value' );
x = new Float32Array( [ NaN, 4.0 ] );
v = svariancech( x.length, 0, x, 1 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
t.end();
});
tape( 'the function calculates the sample variance of a strided array', opts, function test( t ) {
var x;
var v;
x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 0.0, 3.0 ] );
v = svariancech( x.length, 1, x, 1 );
t.strictEqual( v, float64ToFloat32( 53.5/(x.length-1) ), 'returns expected value' );
x = new Float32Array( [ -4.0, -4.0 ] );
v = svariancech( x.length, 1, x, 1 );
t.strictEqual( v, 0.0, 'returns expected value' );
x = new Float32Array( [ NaN, 4.0 ] );
v = svariancech( x.length, 1, x, 1 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
t.end();
});
tape( 'if provided an `N` parameter less than or equal to `0`, the function returns `NaN`', opts, function test( t ) {
var x;
var v;
x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 3.0 ] );
v = svariancech( 0, 1, x, 1 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
v = svariancech( -1, 1, x, 1 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
t.end();
});
tape( 'if provided an `N` parameter equal to `1`, the function returns a population variance of `0`', opts, function test( t ) {
var x;
var v;
x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 3.0 ] );
v = svariancech( 1, 0, x, 1 );
t.strictEqual( v, 0.0, 'returns expected value' );
t.end();
});
tape( 'if provided a `correction` parameter yielding `N-correction` less than or equal to `0`, the function returns `NaN`', opts, function test( t ) {
var x;
var v;
x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 3.0 ] );
v = svariancech( x.length, x.length, x, 1 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
v = svariancech( x.length, x.length+1, x, 1 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
t.end();
});
tape( 'the function supports a `stride` parameter', opts, function test( t ) {
var N;
var x;
var v;
x = new Float32Array([
1.0, // 0
2.0,
2.0, // 1
-7.0,
-2.0, // 2
3.0,
4.0, // 3
2.0
]);
N = floor( x.length / 2 );
v = svariancech( N, 1, x, 2 );
t.strictEqual( v, 6.25, 'returns expected value' );
t.end();
});
tape( 'the function supports a negative `stride` parameter', opts, function test( t ) {
var N;
var x;
var v;
x = new Float32Array([
1.0, // 3
2.0,
2.0, // 2
-7.0,
-2.0, // 1
3.0,
4.0, // 0
2.0
]);
N = floor( x.length / 2 );
v = svariancech( N, 1, x, -2 );
t.strictEqual( v, 6.25, 'returns expected value' );
t.end();
});
tape( 'if provided a `stride` parameter equal to `0`, the function returns `0`', opts, function test( t ) {
var x;
var v;
x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 3.0 ] );
v = svariancech( x.length, 1, x, 0 );
t.strictEqual( v, 0.0, 'returns expected value' );
t.end();
});
tape( 'the function supports view offsets', opts, function test( t ) {
var x0;
var x1;
var N;
var v;
x0 = new Float32Array([
2.0,
1.0, // 0
2.0,
-2.0, // 1
-2.0,
2.0, // 2
3.0,
4.0, // 3
6.0
]);
x1 = new Float32Array( x0.buffer, x0.BYTES_PER_ELEMENT*1 ); // start at 2nd element
N = floor(x1.length / 2);
v = svariancech( N, 1, x1, 2 );
t.strictEqual( v, 6.25, 'returns expected value' );
t.end();
});
|
'use strict';
import moment from 'moment';
import _ from 'lodash';
import alt from '../alt';
import EntriesActions from '../actions/EntriesActions';
class EntriesStore {
constructor() {
this.entries = [];
this.id = 0;
this.loading = false;
this.load();
this.computeSelectedDuration();
this.bindListeners({
handleAddEntry: EntriesActions.ADD_ENTRY,
handleUpdateEntry: EntriesActions.UPDATE_ENTRY,
handleDeleteEntry: EntriesActions.DELETE_ENTRY,
handleDeleteAll: EntriesActions.DELETE_ALL,
handleSelectEntry: EntriesActions.SELECT_ENTRY,
handleAccountSelected: EntriesActions.ACCOUNT_SELECTED
});
}
//region handlers
handleAddEntry(entry) {
this.id++;
this.entries.push({
id: this.id,
text: entry.text,
time: entry.time,
workingTime: entry.workingTime,
_time: moment(entry.time, 'HH:mm')
});
this.sort();
this.computeDurations();
this.save();
}
handleUpdateEntry(entry) {
let index = _.findIndex(this.entries, {id: entry.id});
this.entries[index] = _.assign(this.entries[index], {
text: entry.text,
time: entry.time,
workingTime: entry.workingTime,
_time: moment(entry.time, 'HH:mm')
});
this.sort();
this.computeDurations();
this.save();
}
handleDeleteEntry(id) {
_.remove(this.entries, {id});
this.computeDurations();
this.save();
}
handleDeleteAll() {
this.entries = [];
this.id = 0;
this.computeDurations();
this.save();
}
handleSelectEntry(entry) {
let index = _.findIndex(this.entries, {id: entry.id});
this.entries[index] = _.assign(this.entries[index], {
selected: entry.selected
});
this.computeSelectedDuration();
}
handleAccountSelected() {
let selectedEntries = _.filter(this.entries, {selected: true});
_.forEach(selectedEntries, function (value) {
let index = _.findIndex(this.entries, {id: value.id});
this.entries[index] = _.assign(this.entries[index], {
selected: false,
accounted: true
});
}.bind(this));
this.computeSelectedDuration();
}
//endregion
sort() {
this.entries = _.sortBy(this.entries, (entry) => entry._time);
}
computeDurations() {
let hhmm = function (minutes) {
let hours = Math.floor(minutes / 60);
minutes = minutes % 60;
return hours + ':' + `0${minutes}`.slice(-2);
};
if (this.entries.length == 0) {
this.totalDuration = '0:00';
return;
}
let totalDuration = 0;
_.assign(this.entries[this.entries.length - 1], {
_duration: 0,
duration: '-'
});
for (let i = 0; i < this.entries.length - 1; i++) {
let first = this.entries[i];
let second = this.entries[i + 1];
this.entries[i]._duration = second._time.diff(first._time, 'minutes');
this.entries[i].duration = hhmm(this.entries[i]._duration);
if (this.entries[i].workingTime) {
totalDuration += this.entries[i]._duration;
}
}
this.totalDuration = hhmm(totalDuration);
}
computeSelectedDuration() {
let hhmm = function (minutes) {
let hours = Math.floor(minutes / 60);
minutes = minutes % 60;
return hours + ':' + `0${minutes}`.slice(-2);
};
if (this.entries.length == 0) {
this.selectedDuration = '0:00';
return;
}
let selectedEntries = _.filter(this.entries, {selected: true});
let duration = _.reduce(selectedEntries, (total, entry) => total + entry._duration, 0);
this.selectedDuration = hhmm(duration);
}
save() {
if (this.loading) {
return;
}
let entries = _.map(this.entries, (entry) => {
return {
text: entry.text,
time: entry.time,
workingTime: entry.workingTime
}
});
localStorage.setItem('entries', JSON.stringify(entries));
}
load() {
this.loading = true;
this.entries = [];
this.id = 0;
let entries = JSON.parse(localStorage.getItem('entries'));
_.forEach(entries, (entry) => {
this.handleAddEntry(entry);
});
this.loading = false;
}
}
export default alt.createStore(EntriesStore, 'EntriesStore');
|
'use strict';
goog.provide("Entry.Collection");
/*
* Entry Collection object constructor.
*/
Entry.Collection = function(data) {
this.length = 0;
/*
* object for hashing data with id
* @private
*/
this._hashMap = {};
/*
* observers
*/
this._observers = [];
this.set(data);
};
(function(p, ap) {
/* setters */
p.set = function(data) {
while(this.length) ap.pop.call(this);
var hashMap = this._hashMap;
for (var key in hashMap)
delete hashMap[key];
if (data !== undefined) {
for (var i = 0, len = data.length; i<len; i++) {
var datum = data[i];
hashMap[datum.id] = datum;
ap.push.call(this, datum);
}
}
};
p.push = function(elem){
this._hashMap[elem.id] = elem;
ap.push.call(this, elem);
};
p.unshift = function() {
var args = Array.prototype.slice.call(arguments,0);
var hashMap = this._hashMap;
for (var i=args.length-1; i>=0; i--) {
var datum = args[i];
ap.unshift.call(this, datum);
hashMap[datum.id] = datum;
}
};
p.insert = function(datum, index) {
ap.splice.call(this, index, 0, datum);
this._hashMap[datum.id] = datum;
};
p.has = function(id) {return !!this._hashMap[id];};
p.get = function(id) {return this._hashMap[id];};
p.at = function(index) {return this[index];};
p.getAll = function() {
var len = this.length;
var ret = [];
for (var i=0; i<len; i++) ret.push(this[i]);
return ret;
};
p.indexOf = function(obj) {return ap.indexOf.call(this, obj);};
p.find = function(cond) {
var ret = [];
var flag;
for (var i=0,len=this.length; i<len; i++) {
flag = true;
var datum = this[i];
for(var key in cond) {
if (cond[key] != datum[key]) {
flag = false;
break;
}
}
if (flag) ret.push(datum);
}
return ret;
};
p.pop = function() {
var datum = ap.pop.call(this);
delete this._hashMap[datum.id];
return datum;
};
p.shift = function() {
var datum = ap.shift.call(this);
delete this._hashMap[datum.id];
return datum;
};
p.slice = function(index, amount) {
var data = ap.slice.call(this,index, amount);
var hashMap = this._hashMap;
for (var i in data) delete hashMap[data[i].id];
return data;
};
p.remove = function(datum) {
var index = this.indexOf(datum);
if (index > -1) {
delete this._hashMap[datum.id];
this.splice(index, 1);
}
};
p.splice = function(index, amount) {
var args = ap.slice.call(arguments,2);
var hashMap = this._hashMap;
amount = amount === undefined ?
this.length - index: amount;
var splicedData = ap.splice.call(this, index, amount);
for (var i=0,len=splicedData.length; i<len; i++)
delete hashMap[splicedData[i].id];
for (i=0,len=args.length; i<len; i++) {
var datum = args[i];
ap.splice.call(this, index++, 0, datum);
this._hashMap[datum.id] = datum;
}
return splicedData;
};
p.clear = function() {
while(this.length) ap.pop.call(this);
this._hashMap = {};
};
p.map = function(fn, param) {
var array = [];
for (var i=0, len=this.length; i<len; i++)
array.push(fn(this[i], param));
return array;
};
p.moveFromTo = function(from, to) {
var max = this.length-1;
if (from< 0 || to<0 || from>max || to>max)
return;
ap.splice.call(
this, to, 0,
ap.splice.call(this, from, 1)[0]
);
};
p.sort = function() {
};
/* import & export */
p.fromJSON = function() {
};
p.toJSON = function() {
var json = [];
for (var i=0, len=this.length; i<len; i++)
json.push(this[i].toJSON());
return json;
};
/* observe methods */
p.observe = function() {
};
p.unobserve = function() {
};
p.notify = function() {
};
/* end function */
p.destroy = function() {
};
})(Entry.Collection.prototype, Array.prototype);
|
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var resolve = require( 'path' ).resolve;
var tape = require( 'tape' );
var floor = require( '@stdlib/math/base/special/floor' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var isPositiveZero = require( '@stdlib/math/base/assert/is-positive-zero' );
var Float64Array = require( '@stdlib/array/float64' );
var Uint8Array = require( '@stdlib/array/uint8' );
var tryRequire = require( '@stdlib/utils/try-require' );
// VARIABLES //
var dmskrange = tryRequire( resolve( __dirname, './../lib/ndarray.native.js' ) );
var opts = {
'skip': ( dmskrange instanceof Error )
};
// TESTS //
tape( 'main export is a function', opts, function test( t ) {
t.ok( true, __filename );
t.strictEqual( typeof dmskrange, 'function', 'main export is a function' );
t.end();
});
tape( 'the function has an arity of 7', opts, function test( t ) {
t.strictEqual( dmskrange.length, 7, 'has expected arity' );
t.end();
});
tape( 'the function calculates the range of a strided array according to a mask', opts, function test( t ) {
var mask;
var x;
var v;
x = new Float64Array( [ 1.0, -2.0, -4.0, NaN, 5.0, 0.0, 3.0 ] );
mask = new Uint8Array( [ 0, 0, 0, 1, 0, 0, 0 ] );
v = dmskrange( x.length, x, 1, 0, mask, 1, 0 );
t.strictEqual( v, 9.0, 'returns expected value' );
x = new Float64Array( [ -4.0, NaN, -5.0 ] );
mask = new Uint8Array( [ 0, 1, 0 ] );
v = dmskrange( x.length, x, 1, 0, mask, 1, 0 );
t.strictEqual( v, 1.0, 'returns expected value' );
x = new Float64Array( [ -0.0, 0.0, NaN, -0.0 ] );
mask = new Uint8Array( [ 0, 0, 1, 0 ] );
v = dmskrange( x.length, x, 1, 0, mask, 1, 0 );
t.strictEqual( isPositiveZero( v ), true, 'returns expected value' );
x = new Float64Array( [ -4.0, 0.0, NaN, 5.0 ] );
mask = new Uint8Array( [ 0, 0, 0, 0 ] );
v = dmskrange( x.length, x, 1, 0, mask, 1, 0 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
x = new Float64Array( [ NaN ] );
mask = new Uint8Array( [ 0 ] );
v = dmskrange( x.length, x, 1, 0, mask, 1, 0 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
x = new Float64Array( [ NaN ] );
mask = new Uint8Array( [ 1 ] );
v = dmskrange( x.length, x, 1, 0, mask, 1, 0 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
x = new Float64Array( [ NaN, NaN ] );
mask = new Uint8Array( [ 1, 1 ] );
v = dmskrange( x.length, x, 1, 0, mask, 1, 0 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
x = new Float64Array( [ NaN, NaN ] );
mask = new Uint8Array( [ 1, 0 ] );
v = dmskrange( x.length, x, 1, 0, mask, 1, 0 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
x = new Float64Array( [ NaN, NaN ] );
mask = new Uint8Array( [ 0, 1 ] );
v = dmskrange( x.length, x, 1, 0, mask, 1, 0 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
x = new Float64Array( [ NaN, NaN ] );
mask = new Uint8Array( [ 0, 0 ] );
v = dmskrange( x.length, x, 1, 0, mask, 1, 0 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
t.end();
});
tape( 'if provided an `N` parameter less than or equal to `0`, the function returns `NaN`', opts, function test( t ) {
var mask;
var x;
var v;
x = new Float64Array( [ 1.0, -2.0, -4.0, 5.0, 3.0 ] );
mask = new Uint8Array( x.length );
v = dmskrange( 0, x, 1, 0, mask, 1, 0 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
v = dmskrange( -1, x, 1, 0, mask, 1 );
t.strictEqual( isnan( v ), true, 'returns expected value' );
t.end();
});
tape( 'if provided an `N` parameter equal to `1`, the function returns `0`', opts, function test( t ) {
var mask;
var x;
var v;
x = new Float64Array( [ 1.0, -2.0, -4.0, 5.0, 3.0 ] );
mask = new Uint8Array( x.length );
v = dmskrange( 1, x, 1, 0, mask, 1, 0 );
t.strictEqual( v, 0.0, 'returns expected value' );
t.end();
});
tape( 'the function supports `stride` parameters', opts, function test( t ) {
var mask;
var N;
var x;
var v;
x = new Float64Array([
1.0, // 0
2.0,
2.0, // 1
-7.0,
-2.0, // 2
3.0,
4.0, // 3
2.0,
5.0, // 4
6.0
]);
mask = new Uint8Array([
0, // 0
0,
0, // 1
0,
0, // 2
0,
0, // 3
0,
1, // 4
1
]);
N = floor( x.length / 2 );
v = dmskrange( N, x, 2, 0, mask, 2, 0 );
t.strictEqual( v, 6.0, 'returns expected value' );
t.end();
});
tape( 'the function supports negative `stride` parameters', opts, function test( t ) {
var mask;
var N;
var x;
var v;
x = new Float64Array([
5.0, // 4
6.0,
1.0, // 3
2.0,
2.0, // 2
-7.0,
-2.0, // 1
3.0,
4.0, // 0
2.0
]);
mask = new Uint8Array([
1, // 4
1,
0, // 3
0,
0, // 2
0,
0, // 1
0,
0, // 0
0
]);
N = floor( x.length / 2 );
v = dmskrange( N, x, -2, 8, mask, -2, 8 );
t.strictEqual( v, 6.0, 'returns expected value' );
t.end();
});
tape( 'the function supports `offset` parameters', opts, function test( t ) {
var mask;
var N;
var x;
var v;
x = new Float64Array([
2.0,
1.0, // 0
2.0,
-2.0, // 1
-2.0,
2.0, // 2
3.0,
4.0, // 3
5.0,
6.0 // 4
]);
mask = new Uint8Array([
0,
0, // 0
0,
0, // 1
0,
0, // 2
0,
0, // 3
1,
1 // 4
]);
N = floor( x.length / 2 );
v = dmskrange( N, x, 2, 1, mask, 2, 1 );
t.strictEqual( v, 6.0, 'returns expected value' );
t.end();
});
|
const /*--- Declaring imports ---*/
_ = require('underscore');
module.exports = {
index : function(obj, is, value) {
if (typeof is == 'string')
return this.index(obj, is.split('.'), value);
else if (is.length == 1 && value !== undefined)
return obj[is[0]] = value;
else if (is.length == 0)
return obj;
else
return this.index(obj[is[0]], is.slice(1), value);
}
};
|
/**
* 'highlight.js' instance with plugins
*
* @var {highlight.js} $markdown
*/
var $hljs = require('highlight.js');
module.exports = $hljs
|
var filterReflectionByTitle = filterModule.filter('filterReflectionByTitle', function ($window) {
return function (reflections, filterCriteria) {
var strStartsWith = function (str, prefix) {
return (str + "").indexOf(prefix) === 0;
};
if (filterCriteria == null || filterCriteria === '')
return reflections;
var filtered = _.reduce(reflections, function (filteredList, reflection) {
var title = (filterCriteria.contentTextRepresentation === 'Transliteration') ?
reflection.title :
reflection.title;
if (strStartsWith(title.toUpperCase(), filterCriteria.alphabet.toUpperCase()))
filteredList.push(reflection);
return filteredList;
}, []);
return filtered;
}
});
|
import React, { useState } from 'react';
import * as R from 'ramda';
import Head from 'next/head';
import { useQuery } from "@apollo/react-hooks";
import AllProjectsProblemsQuery from 'lib/query/AllProjectsProblems';
import getSeverityEnumQuery, {getProjectOptions, getSourceOptions} from 'components/Filters/helpers';
import { LoadingPageNoHeader } from 'pages/_loading';
import Honeycomb from "components/Honeycomb";
import MainLayout from 'layouts/MainLayout';
import SelectFilter from 'components/Filters';
import { bp } from 'lib/variables';
/**
* Displays problems page by project.
*
*/
const ProblemsDashboardByProjectPageHexDisplay = () => {
const [showCleanProjects, setShowCleanProjects] = useState(true);
const [source, setSource] = useState([]);
const [severity, setSeverity] = useState(['CRITICAL']);
const [envType, setEnvType] = useState('PRODUCTION');
const { data: severities, loading: severityLoading } = useQuery(getSeverityEnumQuery);
const { data: sources, loading: sourceLoading } = useQuery(getSourceOptions);
const { data: projectsProblems, loading: projectsProblemsLoading} =
useQuery(AllProjectsProblemsQuery, {
variables: {
severity: severity,
source: source,
envType: envType
}
});
const handleEnvTypeChange = (envType) => setEnvType(envType.value);
const handleShowAllProjectsCheck = () => setShowCleanProjects(!showCleanProjects);
const handleSourceChange = (source) => {
let values = source && source.map(s => s.value) || [];
setSource(values);
};
const handleSeverityChange = (severity) => {
let values = severity && severity.map(s => s.value) || [];
setSeverity(values);
};
const sourceOptions = (sources) => {
return sources && sources.map(s => ({ value: s, label: s}));
};
const severityOptions = (enums) => {
return enums && enums.map(s => ({ value: s.name, label: s.name}));
};
return (
<>
<Head>
<title>Problems Dashboard By Project</title>
</Head>
<MainLayout>
<div className="filters-wrapper">
<div className="filters">
<SelectFilter
title="Severity"
loading={severityLoading}
options={severities && severityOptions(severities.__type.enumValues)}
defaultValue={{value: "CRITICAL", label: "CRITICAL"}}
onFilterChange={handleSeverityChange}
isMulti
/>
<SelectFilter
title="Source"
loading={sourceLoading}
options={sources && sourceOptions(sources.sources)}
onFilterChange={handleSourceChange}
isMulti
/>
<SelectFilter
title="Type"
defaultValue={{value: 'PRODUCTION', label: 'Production'}}
options={[
{value: 'PRODUCTION', label: 'Production'},
{value: 'DEVELOPMENT', label: 'Development'}
]}
onFilterChange={handleEnvTypeChange}
/>
</div>
<div className="extra-filters">
<label>Show Projects with no problems: </label>
<input name="env-type" onClick={handleShowAllProjectsCheck} defaultChecked={showCleanProjects} type="checkbox" />
</div>
</div>
<div className="content-wrapper">
<div className="overview">
{projectsProblemsLoading && <LoadingPageNoHeader />}
{!projectsProblemsLoading &&
<Honeycomb
data={!R.isNil(projectsProblems) && projectsProblems}
filter={{showCleanProjects: showCleanProjects}}
/>
}
</div>
</div>
<style jsx>{`
.filters-wrapper, .project-filter {
margin: 32px calc((100vw / 16) * 1);
@media ${bp.wideUp} {
margin: 32px calc((100vw / 16) * 2);
}
@media ${bp.extraWideUp} {
margin: 32px calc((100vw / 16) * 3);
}
.filters {
display: flex;
flex-direction: column;
@media ${bp.wideUp} {
flex-flow: row;
}
&:first-child {
padding-bottom: 1em;
}
}
}
.extra-filters {
padding: 0 15px;
}
.content-wrapper {
h2 {
margin: 38px calc((100vw / 16) * 1) 0;
@media ${bp.wideUp} {
margin: 62px calc((100vw / 16) * 2) 0;
}
@media ${bp.extraWideUp} {
margin: 62px calc((100vw / 16) * 3) 0;
}
}
.content {
background: #fff;
margin: 0 calc((100vw / 16) * 1);
@media ${bp.wideUp} {
margin: 0 calc((100vw / 16) * 2);
}
@media ${bp.extraWideUp} {
margin: 0 calc((100vw / 16) * 3);
}
li.result {
display: inline;
}
}
.environment-wrapper {
padding: 0 1em 1em;
background: #fefefe;
margin: 0 0 2em;
h4 {
font-weight: 500;
}
}
.data-none {
display: flex;
justify-content: space-between;
padding: 1em;
border: 1px solid #efefef;
}
}
`}</style>
</MainLayout>
</>);
};
export default ProblemsDashboardByProjectPageHexDisplay;
|
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/**
* Preferences controller for our user profile. Allows explicit editing of
* individual preferences.
*/
angular.module('sb.profile').controller('ProfilePreferencesController',
function ($scope, Preference, Notification, Severity) {
'use strict';
$scope.preferences = Preference.getAll();
/**
* Save all the preferences.
*/
$scope.save = function () {
$scope.saving = true;
Preference.saveAll($scope.preferences).then(
function () {
Notification.send(
'preferences',
'Preferences Saved!',
Severity.SUCCESS
);
$scope.saving = false;
},
function () {
$scope.saving = false;
}
);
};
});
|
angular.module('restServices', [ 'ngResource' ]).factory('RestService',
[ '$resource', function($resource) {
return function(restEntitiesUrl) {
return $resource(restEntitiesUrl, {}, {
query : {
method : 'GET',
isArray : false
},
update : {
method : 'PUT'
}
});
};
} ]);
|
var row_data = [
{ id: "api_sample", title: "API SAMPLE", hasChild: true, dst: "api_sample"},
{ id: "login", title: "LOGIN SAMPLE", hasChild: true, dst: "login" }
];
rows = [];
row_data.map(function(row){
rows.push(Titanium.UI.createTableViewRow(row));
});
$.main_menu.appendRow(rows);
$.main_menu.addEventListener('click', function(e) {
Ti.API.info("================================================");
Ti.API.info(e.rowData.title);
Ti.API.info(e.rowData.dst);
Ti.API.info("================================================");
if(e.rowData.dst != "") {
var args = {};
var view = Alloy.createController(e.rowData.dst, args).getView();
$.tab1.open(view);
};
});
$.index.open();
Alloy.Globals.tab1 = $.tab1;
Alloy.Globals.tab2 = $.tab2;
|
(function() {
'use strict';
angular
.module('woodstock24App')
.controller('ModuleMySuffixDetailController', ModuleMySuffixDetailController);
ModuleMySuffixDetailController.$inject = ['$scope', '$rootScope', '$stateParams', 'previousState', 'entity', 'Module', 'Unit', 'Reference', 'Question'];
function ModuleMySuffixDetailController($scope, $rootScope, $stateParams, previousState, entity, Module, Unit, Reference, Question) {
var vm = this;
vm.module = entity;
vm.previousState = previousState.name;
var unsubscribe = $rootScope.$on('woodstock24App:moduleUpdate', function(event, result) {
vm.module = result;
});
$scope.$on('$destroy', unsubscribe);
}
})();
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
reporter: require('jshint-stylish')
},
// when this task is run, lint the Gruntfile and all js files ilisted
build: ['Gruntfile.js', 'server.js', 'public/js/**/*.js', 'public/js/app.js','app/**/*.js', 'config/db.js']
},
csslint: {
strict: {
options: {
"import": 2
}
},
files: ['public/css/style.css']
},
autoprefixer: {
options: {
browsers: ['last 2 versions', 'ie 8', 'ie 9']
},
build: {
files: {
'public/css/build/style.css': 'public/css/style.css'
}
}
},
watch: {
styles: {
files: ['public/css/style.css'],
tasks: ['autoprefixer', 'csslint']
},
// for scripts, run jshint
scripts: {
files: ['Gruntfile.js', 'server.js', 'public/js/**/*.js', 'public/js/app.js','app/**/*.js', 'config/db.js'],
tasks: ['jshint']
}
},
nodemon: {
dev: {
script: 'server.js'
}
},
// run watch and nodemon at the same time
concurrent: {
options: {
logConcurrentOutput: true
},
tasks: ['nodemon', 'watch']
}
}); //closes grunt initconfig
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-nodemon');
grunt.loadNpmTasks('grunt-concurrent');
grunt.registerTask('default', ['jshint', 'csslint', 'autoprefixer', 'concurrent']);
};
|
exports.AppWindow = function(){
var self = Titanium.UI.createWindow({
backgroundColor: "#888888",
title: "My List"
});
return self;
};
|
import React from 'react';
import { Bluetooth as Memory, Storage, Trigger } from 'grommet-icons';
import {
Box,
Card,
CardBody,
CardFooter,
Chart,
Grid,
Grommet,
Text,
} from 'grommet';
const theme = {
themeMode: 'dark',
global: {
font: {
family: `-apple-system,
BlinkMacSystemFont,
"Segoe UI"`,
},
},
card: {
hover: {
container: {
elevation: 'large',
},
},
container: {
elevation: 'medium',
extend: `transition: all 0.2s ease-in-out;`,
},
footer: {
pad: { horizontal: 'medium', vertical: 'small' },
background: '#00000008',
},
},
};
const gradient = [
{ value: 28, color: 'status-ok' },
{ value: 50, color: 'status-warning' },
{ value: 80, color: 'status-critical' },
];
const data = [
{
icon: <Memory size="large" />,
title: 'Memory (EEC)',
subTitle: '8 GB @ 400Hz',
message: 'Past 24hrs',
type: 'bar',
},
{
icon: <Storage size="large" />,
title: 'Storage',
subTitle: 'Sub-system and Devices',
message: '36.8 TB available',
type: 'line',
},
{
icon: <Trigger size="large" />,
title: 'Power (Watts)',
subTitle: '720 Watt Service',
message: 'Past 12hrs',
type: 'point',
},
];
const ChartPreview = ({ type }) => (
<Box>
<Chart
type={type}
id={type}
dash={type === 'line'}
round
thickness="xsmall"
bounds={[
[0, 6],
[0, 100],
]}
values={[
{ value: [6, 100], label: 'one hundred' },
{ value: [5, 70], label: 'seventy' },
{ value: [4, 40], label: 'sixty' },
{ value: [3, 80], label: 'eighty' },
{ value: [2, 25], label: 'forty' },
{ value: [1, 50], label: 'thirty' },
{ value: [0, 25], label: 'sixty' },
]}
aria-label="chart card"
color={gradient}
size={{ height: 'xsmall' }}
/>
</Box>
);
const Identifier = ({ children, title, subTitle, size, ...rest }) => (
<Box gap="small" align="center" direction="row" pad="small" {...rest}>
{children}
<Box>
<Text size={size} weight="bold">
{title}
</Text>
<Text size={size}>{subTitle}</Text>
</Box>
</Box>
);
export const Clickable = () => (
<Grommet theme={theme} full>
<Box pad="large" height="100%">
<Grid gap="medium" columns={{ count: 'fit', size: 'small' }}>
{data.map((value) => (
<Card
key={value.title}
onClick={() => {
// eslint-disable-next-line no-alert
alert('Card was Clicked!');
}}
>
<CardBody pad="small">
<Identifier
title={value.title}
subTitle={value.subTitle}
size="small"
>
{value.icon}
</Identifier>
<ChartPreview type={value.type} />
</CardBody>
<CardFooter pad={{ horizontal: 'medium', vertical: 'small' }}>
<Text size="xsmall">{value.message}</Text>
</CardFooter>
</Card>
))}
</Grid>
</Box>
</Grommet>
);
Clickable.parameters = {
chromatic: { disable: true },
};
export default {
title: 'Layout/Card/Clickable',
};
|
/*
* Copyright 2015 Caleb Brose, Chris Fogerty, Rob Sheehy, Zach Taylor, Nick Miller
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// auth/init.js
// Handles user session data and view access control.
var authService = require('./authService'),
sessionService = require('./sessionService'),
loginController = require('./loginController');
var auth = angular.module('lighthouse.auth', []);
auth.controller('loginController', loginController);
auth.factory('authService', authService);
auth.factory('sessionService', sessionService);
module.exports = auth;
|
/**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
/* global document ClipboardEvent getOuterHTMLSnippet */
const Gatherer = require('../gatherer.js');
const pageFunctions = require('../../../lib/page-functions.js');
// This is run in the page, not Lighthouse itself.
/**
* @return {LH.Artifacts['PasswordInputsWithPreventedPaste']}
*/
/* istanbul ignore next */
function findPasswordInputsWithPreventedPaste() {
return Array.from(document.querySelectorAll('input[type="password"]'))
.filter(passwordInput =>
!passwordInput.dispatchEvent(
new ClipboardEvent('paste', {cancelable: true})
)
)
.map(passwordInput => ({
// @ts-ignore - getOuterHTMLSnippet put into scope via stringification
snippet: getOuterHTMLSnippet(passwordInput),
}));
}
class PasswordInputsWithPreventedPaste extends Gatherer {
/**
* @param {LH.Gatherer.PassContext} passContext
* @return {Promise<LH.Artifacts['PasswordInputsWithPreventedPaste']>}
*/
afterPass(passContext) {
return passContext.driver.evaluateAsync(`(() => {
${pageFunctions.getOuterHTMLSnippetString};
return (${findPasswordInputsWithPreventedPaste.toString()}());
})()`);
}
}
module.exports = PasswordInputsWithPreventedPaste;
|
"use strict";
var chai = require("chai"),
checker = require("./password_checker");
let expect = chai.expect;
describe("The password checker component", () => {
describe("password encryption method", () => {
it("can encrypt a password", () => {
let input = "derp";
return checker.encryptPassword(input)
.then(encrypted => expect(encrypted).to.not.equal(input));
});
it("throws an error if the password is undefined", () => {
expect(() => checker.encryptPassword()).to.throw();
});
});
describe("password checking method", () => {
it("throws an error if the test password is undefined", () => {
expect(() => checker.isValidPassword(null, "some_hash")).to.throw();
});
it("throws an error if the hash is undefined", () => {
expect(() => checker.isValidPassword("some_password")).to.throw();
});
it("can determine if an input password matches an encrypted password", () => {
let existingPasswordPlain = "youshallnotpass";
return checker.encryptPassword(existingPasswordPlain)
.then(encryptedPassword => checker.isValidPassword(existingPasswordPlain, encryptedPassword))
.then(isMatch => expect(isMatch).to.be.true);
});
it("can determine if an input password does not match an encrypted password", () => {
let existingPasswordPlain = "youshallnotpass";
return checker.encryptPassword(existingPasswordPlain)
.then(encryptedPassword => checker.isValidPassword("derp derp", encryptedPassword))
.then(isMatch => expect(isMatch).to.be.false);
});
});
});
|
log("NOtification View..");
var win = Ti.UI.createWindow({
"backgroundColor": "yellow"
});
function checkForIntent(){
var _intent = Ti.Android.currentActivity.getIntent();
log(JSON.stringify(_intent));
if (_intent.hasExtra('payload')) {
Ti.API.info("*******found " + intent.getStringExtra('payload'));
}
}
function log(msg){
Ti.API.info(msg);
}
win.addEventListener("open", function(e){
checkForIntent();
});
win.open();
|
const Promise = require('q');
const Resource = require('./resource');
/**
* Model to represent an organization.
* @type {Resource}
*/
class Organization extends Resource {
constructor(client, github, clientID) {
super(client);
this.id = clientID;
}
/**
* Return API endpoint for this organization
*/
url(...args) {
return super.url(`orgs/${this.id}`, ...args);
}
// Get a single organization
info() {
return this.get('')
.get('body');
}
// Edit this organization
edit(params) {
return this.patch('', params)
.get('body');
}
// Check membership
// https://developer.github.com/v3/orgs/members/#check-membership
isMember(user) {
return this.get(`members/${user}`)
.then(() => {
return true;
}, () => {
return Promise(false);
});
}
// Return list of members
// https://developer.github.com/v3/orgs/members/#members-list
members(params, options) {
return this.page('members', params, options);
}
// Create a new repository
// https://developer.github.com/v3/repos/#create
createRepo(info) {
return this.post('repos', info)
.get('body');
}
}
module.exports = Organization;
|
/**
* XPDF phase list
*/
define(['marionette',
'backgrid',
'utils/table',
'modules/samples/views/proteinlist'
], function(Marionette,
Backgrid,
table,
ProteinList) {
var ClickableRow = table.ClickableRow.extend({
event: 'phases:view',
argument: 'PROTEINID',
cookie: true,
})
return ProteinList.extend({
clickableRow: ClickableRow,
showFilter: false,
title: 'Phase',
url: 'phase',
events: {
'change .uas': 'showOriginalOnly'
},
ui: { toggleUAS: '.uas' },
columns: [
{ name: 'NAME', label: 'Name', cell: 'string', editable: false },
{ name: 'ACRONYM', label: 'Acronym', cell: 'string', editable: false },
{ name: 'SAFETYLEVEL', label: 'Risk Rating', cell: table.SafetyCell, editable: false },
{ name: 'MOLECULARMASS', label: 'Molecular Mass', cell: 'string', editable: false },
{ name: 'SEQUENCE', label: 'Composition', cell: 'string', editable: false },
{ name: 'DENSITY', label: 'Crystallographic Density', cell: 'string', editable: false },
{ name: 'PDBS', label: 'Has CIF', cell: table.TemplateCell, editable: false, template: '<%-(PDBS > 0 ? "Yes" : "No")%>' },
],
hiddenColumns: [],
// Toggle between displaying all phases or only UAS approved originals
showOriginalOnly: function(){
if(this.ui.toggleUAS[0].checked == true){
this.collection.queryParams['original'] = 1
this.collection.state['currentPage'] = 1
this.collection.fetch()
} else {
delete this.collection.queryParams['original']
this.collection.fetch()
}
}
})
})
|
var win;
function fireUpTheCamera()
{
Ti.Media.showCamera({
success : function(event){
Ti.API.info(event);
var cropRect = event.cropRect;
var image = event.media;
Ti.API.info("image :"+image);
Ti.API.debug('Our type was: '+event.mediaType);
if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
{
var imageView = Ti.UI.createImageView({
image:event.media
});
win.add(imageView);
Ti.App.Properties.setString('profile_image',event.media);
win.close();
}
else
{
alert("got the wrong type back ="+event.mediaType);
}
},
cancel : function(){
},
error : function(error){
var a = Ti.UI.createAlertDialog({title : 'Camera'});
//set message
if(error.code == Titanium.Media.NO_CAMERA)
{
a.setMessage('Please run this test on device');
}
else
{
a.setMessage('Unexpected error: ' + error.code);
}
// show alert
a.show();
},
saveToPhotoGallery:true,
allowEditing:true,
mediaTypes:[Ti.Media.MEDIA_TYPE_PHOTO]
});
}
function call_fun() {
win = Ti.UI.createWindow();
if (Ti.Platform.osname === 'android') {
win.addEventListener('open', function(e) {
fireUpTheCamera();
});
} else {
fireUpTheCamera();
}
return win;
};
module.exports = call_fun;
|
/**
* @license
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
CLASS({
package: 'foam.apps.builder.kiosk',
name: 'ChromeView',
extendsModel: 'foam.ui.View',
imports: [
'kiosk',
'url$',
'webview',
],
properties: [
{
name: 'data',
postSet: function(old, nu) {
if ( old === nu ) return;
if ( old ) {
Events.unfollow(old.homepage$, this.url$);
Events.unfollow(old.enableNavBar$, this.urlEnabled$);
}
if ( nu ) {
Events.follow(nu.homepage$, this.url$);
Events.follow(nu.enableNavBar$, this.urlEnabled$);
}
},
},
{
model_: 'StringProperty',
name: 'url',
view: 'foam.ui.md.TextFieldView',
},
{
model_: 'BooleanProperty',
name: 'urlEnabled',
}
],
methods: [
function init() {
this.SUPER();
this.webview &&
this.webview.subscribe(['action', 'navigate'], this.onNavigate);
},
function updateInnerHTML() {
if ( ! this.$ ) return;
this.children = [];
var out = TemplateOutput.create(this);
this.toInnerHTML(out);
this.$.innerHTML = out.toString();
},
],
listeners: [
{
name: 'onNavigate',
code: function(_, __, url) { this.url = url; },
},
],
actions: [
{
name: 'back',
iconUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAQAAABKfvVzAAAAOUlEQVR4AWMYxqABCElS/p/hN4MWacpDSFMeSlPlYaQo/0OScnyQYg0IJ4XjcsLI0KJFmpa64Zt3AdTaQlFOlKYFAAAAAElFTkSuQmCC',
ligature: 'arrow_back',
isAvailable: function() { return this.data.enableNavBttns; },
isEnabled: function() {
return ( ! this.webview ) || this.webview.canGoBack;
},
code: function() { this.webview && this.webview.back(); }
},
{
name: 'forward',
iconUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAQAAABKfvVzAAAAOUlEQVR4AWMYxqCRoYEU5boMfxj+k6YlgnQtkXTREkW6lmjcWv7jhQ3kayDspGGrnPLE1wCEwxYAABNmQoikBfhoAAAAAElFTkSuQmCC',
ligature: 'arrow_forward',
isAvailable: function() { return this.data.enableNavBttns; },
isEnabled: function() {
return ( ! this.webview ) || this.webview.canGoForward;
},
code: function() { this.webview && this.webview.forward(); }
},
{
name: 'home',
iconUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAQAAABKfvVzAAAAeElEQVR4Ae3Lr9WCABxA0UugaWUB3YAZdAgdgzncQpdghs8NWIBMI/DTQOBw+Bcser778vMtErd3iY1SDyHcpTbYK0VfaWdF5ikG/cksOKrEqMrBjFwtJqrlJpw1YqbGychVKxZqXQwUOrFSpzASC4EPDr3/4Ye8AFVvsVUqqgZTAAAAAElFTkSuQmCC',
ligature: 'home',
isAvailable: function() { return this.data.enableHomeBttn; },
code: function() { this.webview && this.webview.home(); }
},
{
name: 'reload',
iconUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAQAAABKfvVzAAAAwElEQVR4Ad3SP04CURDA4a8RlpNYEP5zQbBGIYT4Ck5iZbwEcStj9AQW7JrI2LLxuYmx45tuMr9uXKSJpFT7VErGgIWsnr1ozElSWIr8+ZNwtDLV1TGzUQsvIh/shVd958Y+RD6YCEd9TTciH5CElaal+D0ohalzC9EW1EJXi38Hz8LMH9wLd3K2wq0fRk4qg8y+9uVaRhLeDJ0behfWsgqPQmVtrqcwt1EJD64gnyQnzefb6mg1snNQqR3sDFygb3rVYPgYJpUVAAAAAElFTkSuQmCC',
ligature: 'refresh',
isAvailable: function() { return this.data.enableReloadBttn; },
code: function() { this.webview && this.webview.reload(); }
},
{
name: 'logout',
iconUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAQAAABKfvVzAAAAcklEQVR4AWMYvCCQ4SXDfzzwFYM/inqQcgLwJYp6sBAqwJCnqgZFhgMMCqRoWAnkPUBoIewCPobjCC0IDfi1nIBoweMkTAjXQrkGTMCP6SQSlBMO1lUw5cRqUMAWcfROS68IJu8XqBoCGF4SUO47aDM/AFyMnK0wQYLQAAAAAElFTkSuQmCC',
ligature: 'exit_to_app',
isAvailable: function() { return this.data.enableLogoutBttn; },
code: function() { this.kiosk.logout(); }
},
],
templates: [
function toHTML() {/*
<kiosk-chrome id="%%id" <%= this.cssClassAttr() %>>
<% this.toInnerHTML(out) %>
</kiosk-chrome>
*/},
function toInnerHTML() {/*
$$back
$$forward
$$home
$$url{ enabled$: this.urlEnabled$ }
$$reload
$$logout
<% this.setClass('hidden', function() {
return ! this.data.enableNavBar;
}.bind(this), this.urlView.id); %>
*/},
function CSS() {/*
kiosk-chrome {
display: flex;
align-items: center;
flex-grow: 0;
flex-shrink: 0;
padding: 0 0 0 8px;
box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.38);
overflow: hidden;
}
kiosk-chrome .md-button {
flex-grow: 0;
flex-shrink: 0;
margin-left: 0;
}
kiosk-chrome .md-text-field-container {
flex-grow: 1;
flex-shrink: 1;
}
kiosk-chrome .md-text-field-container.hidden {
display: inherit!important;
transition-delay: 0ms, 250ms, 250ms, 250ms;
opacity: 0;
width: 0;
margin: 0;
padding: 0;
}
kiosk-chrome .md-text-field-container {
transition: opacity 250ms ease, width 249ms ease, margin 249ms ease, padding 249ms ease;
transition-delay: 249ms, 0ms, 0ms, 0ms;
opacity: unset;
}
*/},
]
});
//# sourceURL=js/foam/apps/builder/kiosk/KioskChromeView.js
|
//Bind pages to tabs
var pages = document.getElementById('pages');
var tabs = document.getElementById('tabs');
var aboutpages = document.getElementById('aboutpages');
var gamepages = document.getElementById('gamepages');
var gamehome = document.getElementById('gamehome');
if (tabs.addEventListener){
tabs.addEventListener('core-select', function() {
// home page selected
if(tabs.selected == 0){
pages.selected = 0;
pages.style.display = "";
gamepages.style.display = "none";
aboutpages.style.display = "none";
} // game page selected
else if (tabs.selected == 1){
pages.style.display = "none";
gamepages.selected = 0;
gamepages.style.display = "";
gamehome.style.display = "";
aboutpages.style.display = "none";
} // about page selected
else if (tabs.selected == 2){
pages.style.display = "none";
gamepages.style.display = "none";
aboutpages.selected = 0;
aboutpages.style.display = "";
}
});
} else if (tabs.attachEvent){
tabs.attachEvent('core-select', function() {
// home page selected
if(tabs.selected == 0){
pages.selected = 0;
pages.style.display = "";
gamepages.style.display = "none";
aboutpages.style.display = "none";
} // game page selected
else if (tabs.selected == 1){
pages.style.display = "none";
gamepages.selected = 0;
gamepages.style.display = "";
gamehome.style.display = "";
aboutpages.style.display = "none";
} // about page selected
else if (tabs.selected == 2){
pages.style.display = "none";
gamepages.style.display = "none";
aboutpages.selected = 0;
aboutpages.style.display = "";
}
});
}
|
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.xml} class, which represents a
* loaded XML document.
*/
( function() {
/* global ActiveXObject */
CKEDITOR.plugins.add( 'xml', {} );
/**
* Represents a loaded XML document.
*
* var xml = new CKEDITOR.xml( '<books><book title="My Book" /></books>' );
*
* @class
* @constructor Creates xml class instance.
* @param {Object/String} xmlObjectOrData A native XML (DOM document) object or
* a string containing the XML definition to be loaded.
*/
CKEDITOR.xml = function( xmlObjectOrData ) {
var baseXml = null;
if ( typeof xmlObjectOrData == 'object' )
baseXml = xmlObjectOrData;
else {
var data = ( xmlObjectOrData || '' ).replace( / /g, '\xA0' );
// Check ActiveXObject before DOMParser, because IE10+ support both, but
// there's no XPath support in DOMParser instance.
// Also, the only check for ActiveXObject which still works in IE11+ is with `in` operator.
if ( 'ActiveXObject' in window ) {
try {
baseXml = new ActiveXObject( 'MSXML2.DOMDocument' );
} catch ( e ) {
try {
baseXml = new ActiveXObject( 'Microsoft.XmlDom' );
} catch ( err ) {}
}
if ( baseXml ) {
baseXml.async = false;
baseXml.resolveExternals = false;
baseXml.validateOnParse = false;
baseXml.loadXML( data );
}
}
else if ( window.DOMParser ) {
baseXml = ( new DOMParser() ).parseFromString( data, 'text/xml' );
}
}
/**
* The native XML (DOM document) used by the class instance.
*
* @property {Object}
*/
this.baseXml = baseXml;
};
CKEDITOR.xml.prototype = {
/**
* Get a single node from the XML document, based on a XPath query.
*
* // Create the XML instance.
* var xml = new CKEDITOR.xml( '<list><item id="test1" /><item id="test2" /></list>' );
* // Get the first <item> node.
* var itemNode = <b>xml.selectSingleNode( 'list/item' )</b>;
* // Alert "item".
* alert( itemNode.nodeName );
*
* @param {String} xpath The XPath query to execute.
* @param {Object} [contextNode] The XML DOM node to be used as the context
* for the XPath query. The document root is used by default.
* @returns {Object} A XML node element or null if the query has no results.
*/
selectSingleNode: function( xpath, contextNode ) {
var baseXml = this.baseXml;
if ( contextNode || ( contextNode = baseXml ) ) {
if ( 'selectSingleNode' in contextNode ) // IEs
return contextNode.selectSingleNode( xpath );
else if ( baseXml.evaluate ) { // Others
var result = baseXml.evaluate( xpath, contextNode, null, 9, null );
return ( result && result.singleNodeValue ) || null;
}
}
return null;
},
/**
* Gets a list node from the XML document, based on a XPath query.
*
* // Create the XML instance.
* var xml = new CKEDITOR.xml( '<list><item id="test1" /><item id="test2" /></list>' );
* // Get all <item> nodes.
* var itemNodes = xml.selectNodes( 'list/item' );
* // Alert "item" twice, one for each <item>.
* for ( var i = 0; i < itemNodes.length; i++ )
* alert( itemNodes[i].nodeName );
*
* @param {String} xpath The XPath query to execute.
* @param {Object} [contextNode] The XML DOM node to be used as the context
* for the XPath query. The document root is used by default.
* @returns {Array} An array containing all matched nodes. The array will
* be empty if the query has no results.
*/
selectNodes: function( xpath, contextNode ) {
var baseXml = this.baseXml,
nodes = [];
if ( contextNode || ( contextNode = baseXml ) ) {
if ( 'selectNodes' in contextNode ) // IEs
return contextNode.selectNodes( xpath );
else if ( baseXml.evaluate ) { // Others
var result = baseXml.evaluate( xpath, contextNode, null, 5, null );
if ( result ) {
var node;
while ( ( node = result.iterateNext() ) )
nodes.push( node );
}
}
}
return nodes;
},
/**
* Gets the string representation of hte inner contents of a XML node,
* based on a XPath query.
*
* // Create the XML instance.
* var xml = new CKEDITOR.xml( '<list><item id="test1" /><item id="test2" /></list>' );
* // Alert "<item id="test1" /><item id="test2" />".
* alert( xml.getInnerXml( 'list' ) );
*
* @param {String} xpath The XPath query to execute.
* @param {Object} [contextNode] The XML DOM node to be used as the context
* for the XPath query. The document root is used by default.
* @returns {String} The textual representation of the inner contents of
* the node or null if the query has no results.
*/
getInnerXml: function( xpath, contextNode ) {
var node = this.selectSingleNode( xpath, contextNode ),
xml = [];
if ( node ) {
node = node.firstChild;
while ( node ) {
if ( node.xml ) // IEs
xml.push( node.xml );
else if ( window.XMLSerializer ) // Others
xml.push( ( new XMLSerializer() ).serializeToString( node ) );
node = node.nextSibling;
}
}
return xml.length ? xml.join( '' ) : null;
}
};
} )();
|
/*
* FCKeditor - The text editor for internet
* Copyright (C) 2003-2005 Frederico Caldeira Knabben
*
* Licensed under the terms of the GNU Lesser General Public License:
* http://www.opensource.org/licenses/lgpl-license.php
*
* For further information visit:
* http://www.fckeditor.net/
*
* "Support Open Source software. What about a donation today?"
*
* File Name: fckxml.js
* Defines the FCKXml object that is used for XML data calls
* and XML processing.
* This script is shared by almost all pages that compose the
* File Browser frameset.
*
* File Authors:
* Frederico Caldeira Knabben (fredck@fckeditor.net)
*/
var FCKXml = function()
{}
FCKXml.prototype.GetHttpRequest = function()
{
if ( window.XMLHttpRequest ) // Gecko
return new XMLHttpRequest() ;
else if ( window.ActiveXObject ) // IE
return new ActiveXObject("MsXml2.XmlHttp") ;
}
FCKXml.prototype.LoadUrl = function( urlToCall, asyncFunctionPointer )
{
var oFCKXml = this ;
var bAsync = ( typeof(asyncFunctionPointer) == 'function' ) ;
var oXmlHttp = this.GetHttpRequest() ;
oXmlHttp.open( "GET", urlToCall, bAsync ) ;
if ( bAsync )
{
oXmlHttp.onreadystatechange = function()
{
if ( oXmlHttp.readyState == 4 )
{
oFCKXml.DOMDocument = oXmlHttp.responseXML ;
if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 )
asyncFunctionPointer( oFCKXml ) ;
else
alert( 'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')' ) ;
}
}
}
oXmlHttp.send( null ) ;
if ( ! bAsync )
{
if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 )
this.DOMDocument = oXmlHttp.responseXML ;
else
{
alert( 'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')' ) ;
}
}
}
FCKXml.prototype.SelectNodes = function( xpath )
{
if ( document.all ) // IE
return this.DOMDocument.selectNodes( xpath ) ;
else // Gecko
{
var aNodeArray = new Array();
var xPathResult = this.DOMDocument.evaluate( xpath, this.DOMDocument,
this.DOMDocument.createNSResolver(this.DOMDocument.documentElement), XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
if ( xPathResult )
{
var oNode = xPathResult.iterateNext() ;
while( oNode )
{
aNodeArray[aNodeArray.length] = oNode ;
oNode = xPathResult.iterateNext();
}
}
return aNodeArray ;
}
}
FCKXml.prototype.SelectSingleNode = function( xpath )
{
//alert(xpath);
if ( document.all ) // IE
return this.DOMDocument.selectSingleNode( xpath ) ;
else // Gecko
{
var xPathResult = this.DOMDocument.evaluate( xpath, this.DOMDocument, this.DOMDocument.createNSResolver(this.DOMDocument.documentElement), 9, null);
if ( xPathResult && xPathResult.singleNodeValue )
return xPathResult.singleNodeValue ;
else
return null ;
}
}
|
// ----------------------------------------------------------------------------
// Copyright 2007-2013, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Change History:
// 2009/11/10 Martin D. Flynn
// -Initial Creation
// ----------------------------------------------------------------------------
var MAX_COMMAND_ARGS = 10;
var COMMAND_ARG_PREFIX = "rct_";
// Onload
function devCommandOnLoad() {
devCommandRadioChanged();
};
// Command radio button selection changed
function devCommandRadioChanged() {
//try {
if (document.DeviceCommandForm.cmdRadioSel.length) {
var rc = document.DeviceCommandForm.cmdRadioSel.length;
//alert("Radio selection changed ... " + rc);
for (var i = 0; i < rc; i++) {
var cmdName = document.DeviceCommandForm.cmdRadioSel[i].value;
var cmdChkd = document.DeviceCommandForm.cmdRadioSel[i].checked;
//alert("Command: " + i + " " + cmdName);
for (var a = 0; a < MAX_COMMAND_ARGS; a++) {
var cmdOptn = document.getElementById(COMMAND_ARG_PREFIX + cmdName + '_' + a);
if (!cmdOptn) { continue; }
//alert("Radio selection changed ... " + i + " " + cmdChkd);
if (cmdChkd) {
cmdOptn.disabled = false;
cmdOptn.className = "textInput";
} else {
cmdOptn.disabled = true;
cmdOptn.className = "textReadOnly";
}
}
}
}
//} catch (e) {
//
//}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.