text
stringlengths 2
6.14k
|
|---|
var pavlok = require('pavlok-beta-api-login');
var os = require('os');
var alertValid = true;
function bytesToGb(bytes){
return (bytes / 1024 / 1024 / 1024).toFixed(2);
}
function checkMem(){
var freeMem = os.freemem();
var totalMem = os.totalmem();
var usedMem = totalMem - freeMem;
var percent = usedMem / totalMem;
console.log(bytesToGb(usedMem) + "/" + bytesToGb(totalMem) + "GB used; " +
(percent * 100).toFixed(1) + "% usage");
if(percent > 0.8 && alertValid){
pavlok.vibrate({
"intensity": 200,
"message": "PC RAM usage at " + (percent * 100).toFixed(0) + "%!"
});
alertValid = false; //Don't alert again until we drop below 80% and then go above
console.log("Warned about usage on your Pavlok!");
} else {
alertValid = true;
}
setTimeout(checkMem, 30000);
}
pavlok.init(
//NOTE: Don't expect these client ID/client secrets to work.
"9377ed97a2ccfd3bfd4b7a6d226e3f92504416ac5aeb6aa6fee96343e05fbc4e",
"ddea1deb41de6c18097997f8d63f9296ea4565917f8617961f198bb7d145f8cd");
pavlok.login(function(result, code){
if(result){
checkMem();
} else {
console.log("Unable to sign-in to Pavlok!");
}
});
|
export default [
{
address: 'iGwEZUvfA',
modelAddress: 'm8y7nEtAe',
status: 'AVAILABLE',
isFaulty: false,
faultHistory: [],
isCheckedOutTo: 111111
},
{
address: 'iGwEZVHHE',
modelAddress: 'm8y7nEtAe',
status: 'AVAILABLE',
isFaulty: false,
faultHistory: []
},
{
address: 'iGwEZVeaT',
modelAddress: 'm8y7nFLsT',
status: 'CHECKED_OUT',
isFaulty: false,
faultHistory: [],
timestamp: 0
},
{
address: 'iGwEZVvgu',
modelAddress: 'm8y7nEtAe',
status: 'AVAILABLE',
isFaulty: false,
faultHistory: []
},
{
address: 'iGwEZW6nn',
modelAddress: 'm8y7nFLsT',
status: 'AVAILABLE',
isFaulty: false,
faultHistory: []
},
{
address: 'iGwEZWXhn',
modelAddress: 'm8y7nFLsT',
status: 'AVAILABLE',
isFaulty: false,
faultHistory: []
}
];
|
var count;
var time;
var counter;
var videoID = "Dr3STRBtTp0";
var player;
var pauseIn;
$(window).load(function() {
var query = get_query();
pauseIn = 102;
if (query.pause != null) {
pauseIn = parseInt(query.pause);
}
if (query.video != null) {
videoID = query.video;
}
var minutes = 10;
console.log(query);
if (query.minutes != null) {
minutes = parseInt(query.minutes);
}
var seconds = 0;
if (query.seconds != null) {
seconds = parseInt(query.seconds);
}
time = new Date(0, 0, 0, 0, minutes, seconds, 0);
count = seconds + minutes * 60;
console.log(count);
setTime();
showVideo();
});
function setTime() {
var text = "";
var prev = false;
if (time.getMinutes() > 0 || prev) {
text += Math.floor(time.getMinutes() / 10) + "" + time.getMinutes() % 10 + " : ";
prev = true;
}
if (time.getSeconds() > 0 || prev) {
text += Math.floor(time.getSeconds() / 10) + "" + time.getSeconds() % 10;
}
$("div#time").text(text);
}
/**
* Used to get the query part of the URL
* @return {Object} result result is a JSONObject containing the different query parameters in the URL
*/
function get_query() {
var url = location.href;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0, result = {}; i < qs.length; i++) {
qs[i] = qs[i].split('=');
result[qs[i][0]] = qs[i][1];
}
return result;
}
function timer() {
count = count - 1;
if (count <= 10) {
$("div#time").animate({
"font-size" : "750px"
}, 999, function() {
$("div#time").css("font-size","384px");
});
}
if (count <= 0) {
clearInterval(counter);
$("#video").css("top", "0");
$("div#current").css("top", "0");
player.playVideo();
counter = setInterval(progressTimer, 1000);
return;
}
time = new Date(time.getTime() - 1000);
console.log(time);
setTime();
}
function progressTimer() {
pauseIn = pauseIn - 1;
if (pauseIn <= 0) {
player.pauseVideo();
clearInterval(counter);
}
console.log(pauseIn);
}
function showVideo() {
createYTPlayer("video", "100%", "100%", videoID);
}
/**
* The 'createYTPlayer' function embeds an <iframe> player.
* @param {string} playerDiv Mandatory The DOM ID for the div where the
* <iframe> will be embedded.
* @param {string} playerHeight Mandatory The height of the embedded player.
* @param {string} playerWidth Mandatory The width of the embedded player.
* @param {string} playerVideoId Mandatory The video ID to embed.
* @param {Object} playerVars Mandatory Player parameters or {}.
*/
function createYTPlayer(playerDiv, playerHeight, playerWidth, playerVideoId, playerVars) {
player = new YT.Player(playerDiv, {
height : playerHeight,
width : playerWidth,
videoId : playerVideoId,
playerVars : playerVars,
events : {
'onError' : onPlayerError,
'onReady' : onReady,
'onProgress' : onProgress
}
});
}
function onReady() {
player.playVideo();
player.pauseVideo();
$("#video").css("top", "100%");
counter = setInterval(timer, 1000);
}
/**
* The 'onPlayerError' function executes when the onError event fires.
* It captures the error and adds it to an array that is displayed in
* the "Errors" section of the demo.
* @param {string} errorCode Mandatory A code that explains the error.
*/
function onPlayerError(errorCode) {
alert("YouTube player error:" + errorCode);
}
function onProgress() {
}
// Find the right method, call on correct element
function launchFullScreen(element) {
if (element.requestFullScreen) {
element.requestFullScreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.webkitRequestFullScreen) {
element.webkitRequestFullScreen();
}
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _utils = require('./utils');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var colSizes = ['xs', 'sm', 'md', 'lg', 'xl'];
var stringOrNumberProp = _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]);
var columnProps = _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number, _propTypes2.default.shape({
size: stringOrNumberProp,
push: stringOrNumberProp,
pull: stringOrNumberProp,
offset: stringOrNumberProp
})]);
var propTypes = {
children: _propTypes2.default.node,
hidden: _propTypes2.default.bool,
check: _propTypes2.default.bool,
inline: _propTypes2.default.bool,
disabled: _propTypes2.default.bool,
size: _propTypes2.default.string,
for: _propTypes2.default.string,
tag: _propTypes2.default.string,
className: _propTypes2.default.string,
cssModule: _propTypes2.default.object,
xs: columnProps,
sm: columnProps,
md: columnProps,
lg: columnProps,
xl: columnProps
};
var defaultProps = {
tag: 'label'
};
var Label = function Label(props) {
var className = props.className,
cssModule = props.cssModule,
hidden = props.hidden,
Tag = props.tag,
check = props.check,
inline = props.inline,
disabled = props.disabled,
size = props.size,
htmlFor = props.for,
attributes = _objectWithoutProperties(props, ['className', 'cssModule', 'hidden', 'tag', 'check', 'inline', 'disabled', 'size', 'for']);
var colClasses = [];
colSizes.forEach(function (colSize) {
var columnProp = props[colSize];
delete attributes[colSize];
if (columnProp && columnProp.size) {
var _classNames;
colClasses.push((0, _utils.mapToCssModules)((0, _classnames2.default)((_classNames = {}, _defineProperty(_classNames, 'col-' + colSize + '-' + columnProp.size, columnProp.size), _defineProperty(_classNames, 'push-' + colSize + '-' + columnProp.push, columnProp.push), _defineProperty(_classNames, 'pull-' + colSize + '-' + columnProp.pull, columnProp.pull), _defineProperty(_classNames, 'offset-' + colSize + '-' + columnProp.offset, columnProp.offset), _classNames))), cssModule);
} else if (columnProp) {
colClasses.push('col-' + colSize + '-' + columnProp);
}
});
var classes = (0, _utils.mapToCssModules)((0, _classnames2.default)(className, hidden ? 'sr-only' : false, check ? 'form-check-' + (inline ? 'inline' : 'label') : false, check && inline && disabled ? 'disabled' : false, size ? 'col-form-label-' + size : false, colClasses, colClasses.length ? 'col-form-label' : false), cssModule);
return _react2.default.createElement(Tag, _extends({ htmlFor: htmlFor }, attributes, { className: classes }));
};
Label.propTypes = propTypes;
Label.defaultProps = defaultProps;
exports.default = Label;
|
function VehicleConstructor(name, numberWheels, passengers) {
var vehicle = {};
vehicle.name = name;
vehicle.numberWheels = numberWheels;
vehicle.passengers = passengers;
vehicle.makeNoise = function() {
console.log("Vroom!");
}
return vehicle;
}
var bike = VehicleConstructor("Cannondale", 2, 1);
bike.makeNoise = function() {
console.log("ring, ring");
}
bike.makeNoise();
var sedan = VehicleConstructor("Sedan", 4, 5);
sedan.makeNoise = function() {
console.log("Honk, Honk");
}
sedan.makeNoise();
var bus = VehicleConstructor("Bus", 8, 50);
console.log(bus);
bus.pickup = function(passengers) {
bus.passengers += passengers;
}
console.log(bus);
bus.pickup(5);
console.log(bus.passengers);
|
//-----------------------------------------------------------
// DebugUtil v4
//-----------------------------------------------------------
var DebugUtil={c:true,f:false,ws:null,
Init: function(target){this.c=true; this.f=false;
if(target=="both"){this.f=true;} else if(target=="file"){this.c=false;this.f=true;}
if(this.f){var fso=new ActiveXObject("Scripting.FileSystemObject");
this.ws=fso.OpenTextFile(WScript.ScriptFullName.replace(WScript.ScriptName, "debuglog.txt"),8,true,0);
this.ws.WriteLine("\n\n\n[[[LOG START: "+new Date()+" ]]]\n"); fso=null;}},
Term: function(){if(this.f){this.ws.Close(); this.ws=null;}}
};
function LOG(str){
if(DebugUtil.f){DebugUtil.ws.WriteLine(str);} if(DebugUtil.c){WScript.StdOut.WriteLine(str);}
}
function LOG_ARRAY(ary){
var hr = "+-----------------------"; var c=0;
LOG(hr); for(var i in ary){LOG("| "+i+" : "+ary[i]); c++;} LOG("| +len = "+c); LOG(hr);
}
//-----------------------------------------------------------
var fso = new ActiveXObject("Scripting.FileSystemObject");
WScript.Quit(main(WScript.Arguments.Count(), WScript.Arguments));
function main( argc, argv )
{
// WScriptÈçCScriptÅN®µ¼µ
if ( WScript.FullName.substr(WScript.FullName.length - 11, 11).toUpperCase() == "WSCRIPT.EXE" ) {
var wshShell = new ActiveXObject("WScript.Shell");
var cmd = "cmd.exe /c cscript.exe //NOLOGO \"" + WScript.ScriptFullName + "\"";
for ( var i = 0; i < argc; i++ ) {
cmd += " \"" + argv(i) + "\"";
}
cmd += " | more & pause"
return wshShell.Run(cmd, 1, true);
}
return ExecScript();
}
function ExecScript()
{
DebugUtil.Init("both");
read_csv(WScript.ScriptFullName.replace(WScript.ScriptName, "test1.csv"));
read_csv(WScript.ScriptFullName.replace(WScript.ScriptName, "test2.csv"));
DebugUtil.Term();
}
function read_csv( filespec )
{
LOG(filespec);
var csv = ReadCSV(filespec);
for ( var i in csv ) {
LOG("[" + i + "]");
LOG_ARRAY(csv[i]);
}
}
function ReadCSV( filespec )
{
var GetLines = function( filespec, newline ) {
var lines = null;
if ( fso.FileExists(filespec) ) {
var rs = fso.OpenTextFile(filespec, 1, false, 0);
var text = rs.ReadAll();
rs.Close();
lines = text.split(newline);
} else {
LOG("[ERROR] file not found : " + filespec);
}
return lines;
};
var FormatItem = function( str ) {
var s = str.replace(/^\s+|\s+$/g, "")
if ( s.length > 1 && s.slice(0, 1) == "\"" && s.slice(-1) == "\"" ) {
s = s.slice(1, s.length - 1)
}
return s;
}
var ary = [], line;
var lines = GetLines(filespec, "\r\n");
for ( var i in lines ) {
line = lines[i].replace(/^\s+|\s+$/g, "");
if ( line.length == 0 ) {
continue;
}
var items = line.split(",")
for ( var i in items ) {
items[i] = FormatItem(items[i]);
}
ary.push(items)
}
return ary;
}
|
var apiPath = "/feiying-service/api/";
$.createUUID = function() {
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4()
+ S4() + S4());
};
var S4 = function() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
$(function() {
$("#submit").bind('click', function() {
var actionType = $('#actionType option:selected').val();
if (actionType == "") {
alert("Please select the action type!");
return false;
}
var json = $("#json").val();
console.debug(json);
console.debug(JSON.stringify(eval('(' + json + ')')));
$.ajax({
url : apiPath + actionType.replace("_","/"),
dataType : 'json',
type : 'POST',
async : false,
contentType : 'application/json; charset=UTF-8',
data : JSON.stringify(eval('(' + json + ')')), // {'name':'sss'},//
success : function(json) {
console.debug(json);
console.debug(JSON.stringify(json));
console.debug(JSON.parse(JSON.stringify(json)));
console.debug(JSON.parse(JSON.stringify(json)) == json);
console.debug(FormatJSON(json));
$("#response").val(FormatJSON(json));
}
});
});
$("#clear").bind('click', function() {
$("#actionType option").filter(function() {
return $.trim($(this).text()) == "----";
}).attr('selected', true);
$("#json").val("");
$("#response").val("");
});
});
function change(o) {
var type = $(o).val();
if (type != "") {
$("#json").val($("#" + type + "SampleData").html());
$("#tips").val($("#" + type + "Tips").html());
}
}
|
;(function (root, factory) {
'use strict'
if (typeof define === 'function' && define.amd) {
define([], factory)
} else if (typeof module === 'object' && module.exports) {
module.exports = factory()
} else {
root.perljs = factory()
}
})(this, function () {
'use strict'
var singleQuote = "'"
var perljs = { name: 'perljs' }
perljs.version = '0.3.10'
perljs.VERSION = perljs.version
perljs._console = console
function truth() {
return true
}
perljs._valueMap = {
null: null,
undefined: void 0,
undef: void 0,
empty: '',
true: true,
false: false,
NaN: Number.NaN,
Infinity: Number.POSITIVE_INFINITY,
'-Infinity': Number.NEGATIVE_INFINITY,
}
perljs._value = function (string) {
var value = string
if (!/^function|object|array$/.test(typeof string)) {
value = Number(string)
if (Number.isNaN(value)) {
value =
string in perljs._valueMap
? perljs._valueMap[string]
: string
}
}
return value
}
perljs._stringify = function (mixed) {
if ('function' === typeof mixed) {
return perljs._stringify(mixed())
}
if (
mixed === null ||
mixed === undefined ||
('number' === typeof mixed &&
(Number.isNaN(mixed) ||
mixed === Number.POSITIVE_INFINITY ||
mixed === Number.NEGATIVE_INFINITY))
) {
mixed = ''
}
else if ('object' !== typeof mixed) {
mixed = mixed.toString()
}
return mixed
}
perljs.q = function (string, open, close) {
open = open || singleQuote
close = close || open
if (Array.isArray(string)) {
return perljs.qA(string, open, close)
}
if ('object' === typeof string && string !== null) {
return perljs.qO(string, open, close)
}
return open + perljs._stringify(string) + close
}
perljs.qq = function (string, open, close) {
return perljs.q(string, open || '"', close)
}
perljs.qw = function (string) {
return string.replace(/^\s+/, '').replace(/\s+$/, '').split(/\s+/g)
}
perljs.qA = function (aArray, open, close) {
var aNewArray = []
aArray.forEach(function (value) {
aNewArray.push(perljs.q(value, open, close))
})
return aNewArray
}
perljs.qqA = function (aArray, open, close) {
return perljs.qA(aArray, open || '"', close)
}
perljs.qO = function (oObject, open, close) {
var oNewObject = {}
Object.keys(oObject).forEach(function (key) {
oNewObject[key] = perljs.q(oObject[key], open, close)
})
return oNewObject
}
perljs.qqO = function (oObject, open, close) {
return perljs.qO(oObject, open || '"', close)
}
perljs.qwm = function (string) {
var oMap = {},
key
perljs.qw(string).forEach(function (keyValue) {
if ('undefined' === typeof key) {
key = keyValue
} else {
oMap[key] = perljs._value(keyValue)
key = void 0
}
})
if ('undefined' !== typeof key) {
oMap[key] = void 0
perljs._console.warn(
'Odd number of elements in ' +
'hash assignment from ' +
perljs.q(string)
)
}
return oMap
}
perljs.mapFromString = perljs.qwm
perljs.mapFromArray = function (aArray) {
var oMap = {},
key
aArray = aArray || []
aArray.forEach(function (keyValue) {
if ('undefined' === typeof key) {
key = String(keyValue)
} else {
oMap[key] = keyValue
key = void 0
}
})
if ('undefined' !== typeof key) {
oMap[key] = void 0
perljs._console.warn(
'Odd number of elements in hash assignment from [' +
aArray.join(', ') +
']'
)
}
return oMap
}
perljs.reverseMap = function (oMap, function_) {
var oReverseMap = {}
function_ =
function_ ||
function (value) {
return value
}
Object.keys(oMap).forEach(function (key) {
oReverseMap[function_(oMap[key], oReverseMap)] = perljs._value(key)
})
return oReverseMap
}
perljs.makeMap = function (aArray, defaultValue) {
var function_,
oMap = {},
functionDefaultValue = function () {
return defaultValue
}
aArray = aArray || []
function_ =
'undefined' === typeof defaultValue
? truth
: 'function' === typeof defaultValue
? defaultValue
: functionDefaultValue
aArray.forEach(function (key) {
oMap[String(key)] = function_(key)
})
return oMap
}
perljs.x = function (token, repeat) {
var index,
string = ''
token = perljs._stringify(token)
if (isNaN(repeat)) {
perljs._console.warn(
'Argument ' +
perljs.qq(repeat) +
' isn’t numeric in repeat .x()'
)
}
repeat = Number.parseInt(repeat)
for (index = 0; index < repeat; index += 1) {
string += token
}
return string
}
return perljs
})
|
angular.module('directive', [
'kwDirective'
]);
|
/*
Copyright (c)2016 Ridgeback Network Defense, 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.
*/
/*
This file is part of a tutorial on how to make a dashboard widget for Ridgeback Hunter.
Dashboard widget files go here:
/opt/ridgeback/plugins/ui
Important parts of a widget:
* id - unique identifier for the widget
* version - version number of the widget
* title - human-readable title for the widget panel
* description - human-readable description of the widget
* copyright - widget copyright information
* render(element, datasource) - render the widget
*/
(function(){
var widget =
{
id: "tutorial-hello",
version: "1.0",
title: "Hello World (tutorial)",
description: "This is a simple tutorial widget.",
copyright: "(C)2016 Ridgeback Network Defense, Inc. (GPL3)",
render: function(e, source)
{
var count = source.log().length;
$(e + " .data").append("<h1>Hello, world!</h1>");
$(e + " .value").append("There are " + count + " records.");
} // render()
}; // widget
AWM.registerWidget(widget);
})(); // widget
|
/**
* @license Copyright 2019 The Lighthouse Authors. 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';
/* eslint-disable no-console */
/**
* @fileoverview Minifies a trace by removing unnecessary events, throttling screenshots, etc.
* See the following files for necessary events:
* - lighthouse-core/computed/page-dependency-graph.js
* - lighthouse-core/lib/dependency-graph/cpu-node.js
* - lighthouse-core/lib/tracehouse/trace-processor.js
*/
const TracingProcessor = require('./tracehouse/trace-processor.js');
const toplevelTaskNames = new Set([
'RunTask', // m71+
'ThreadControllerImpl::RunTask', // m69-70
'ThreadControllerImpl::DoWork', // m66-68
'TaskQueueManager::ProcessTaskFromWorkQueue', // m65 and below
]);
const traceCategoriesToAlwaysKeep = new Set([
// Labels the threads correctly in DevTools Performance panel
'__metadata',
]);
const traceEventsToAlwaysKeep = new Set([
'Screenshot',
'TracingStartedInBrowser',
'TracingStartedInPage',
'navigationStart',
'ParseAuthorStyleSheet',
'ParseHTML',
'PlatformResourceSendRequest',
'ResourceSendRequest',
'ResourceReceiveResponse',
'ResourceFinish',
'ResourceReceivedData',
'EventDispatch',
'LayoutShift',
'FrameCommittedInBrowser',
// Not currently used by Lighthouse but might be used in the future for cross-frame LCP
'NavStartToLargestContentfulPaint::Invalidate::AllFrames::UKM',
'NavStartToLargestContentfulPaint::Candidate::AllFrames::UKM',
// Needed for CPU profiler task attribution
'Profile',
'ProfileChunk',
]);
const traceEventsToKeepInToplevelTask = new Set([
// Needed for CPU node timing simulations
'Layout',
'RunMicrotasks',
// All of these are needed to create graph relationships
'TimerInstall',
'TimerFire',
'InvalidateLayout',
'ScheduleStyleRecalculation',
'EvaluateScript',
'XHRReadyStateChange',
'FunctionCall',
'v8.compile',
'ParseAuthorStyleSheet',
'ResourceSendRequest',
]);
const traceEventsToKeepInProcess = new Set([
...toplevelTaskNames,
...traceEventsToKeepInToplevelTask,
// See the DevTools marker events
// https://source.chromium.org/chromium/chromium/src/+/main:third_party/devtools-frontend/src/front_end/timeline_model/TimelineModel.js?q=-f:out%20f:TimelineModel%20%22MarkLoad:%20%27%22&ss=chromium
'firstPaint',
'firstContentfulPaint',
'firstMeaningfulPaint',
'firstMeaningfulPaintCandidate',
'loadEventEnd',
'MarkLoad',
'domContentLoadedEventEnd',
'MarkDOMContent',
'largestContentfulPaint::Invalidate',
'largestContentfulPaint::Candidate',
'Animation',
]);
/**
* @param {LH.TraceEvent[]} events
*/
function filterOutUnnecessaryTasksByNameAndDuration(events) {
const {pid} = TracingProcessor.findMainFrameIds(events);
return events.filter(evt => {
if (toplevelTaskNames.has(evt.name) && evt.dur < 1000) return false;
if (evt.pid === pid && traceEventsToKeepInProcess.has(evt.name)) return true;
if (traceCategoriesToAlwaysKeep.has(evt.cat)) return true;
return traceEventsToAlwaysKeep.has(evt.name);
});
}
/**
* Filters out tasks that are not within a toplevel task.
* @param {LH.TraceEvent[]} events
*/
function filterOutOrphanedTasks(events) {
const toplevelRanges = events
.filter(evt => toplevelTaskNames.has(evt.name))
.map(evt => [evt.ts, evt.ts + evt.dur]);
/** @param {LH.TraceEvent} e */
const isInToplevelTask = e => toplevelRanges.some(([start, end]) => e.ts >= start && e.ts <= end);
return events.filter((evt, index) => {
if (!traceEventsToKeepInToplevelTask.has(evt.name)) return true;
if (!isInToplevelTask(evt)) return false;
if (evt.ph === 'B') {
const endEvent = events.slice(index).find(e => e.name === evt.name && e.ph === 'E');
return endEvent && isInToplevelTask(endEvent);
} else {
return true;
}
});
}
/**
* Throttles screenshot events in the trace to 2fps.
* @param {LH.TraceEvent[]} events
*/
function filterOutExcessiveScreenshots(events) {
const screenshotTimestamps = events.filter(evt => evt.name === 'Screenshot').map(evt => evt.ts);
let lastScreenshotTs = -Infinity;
return events.filter(evt => {
if (evt.name !== 'Screenshot') return true;
const timeSinceLastScreenshot = evt.ts - lastScreenshotTs;
const nextScreenshotTs = screenshotTimestamps.find(ts => ts > evt.ts);
const timeUntilNextScreenshot = nextScreenshotTs ? nextScreenshotTs - evt.ts : Infinity;
const threshold = 500 * 1000; // Throttle to ~2fps
// Keep the frame if it's been more than 500ms since the last frame we kept or the next frame won't happen for at least 500ms
const shouldKeep = timeUntilNextScreenshot > threshold || timeSinceLastScreenshot > threshold;
if (shouldKeep) lastScreenshotTs = evt.ts;
return shouldKeep;
});
}
/**
* @param {LH.TraceEvent[]} events
*/
function filterTraceEvents(events) {
// Filter out event names we don't care about and tasks <1ms
let filtered = filterOutUnnecessaryTasksByNameAndDuration(events);
// Filter out events not inside a toplevel task
filtered = filterOutOrphanedTasks(filtered);
// Filter down the screenshots to key moments + 2fps animations
return filterOutExcessiveScreenshots(filtered);
}
/**
* @param {LH.Trace} inputTrace
* @return {LH.Trace}
*/
function minifyTrace(inputTrace) {
return {traceEvents: filterTraceEvents(inputTrace.traceEvents)};
}
module.exports = {minifyTrace};
|
/**
* This is the main interface of the JungleDB.
* @interface
*/
class IJungleDB {
/**
* Connects to the indexedDB.
* @abstract
* @returns {Promise} A promise resolving on successful connection.
*/
connect() {} // eslint-disable-line no-unused-vars
/**
* Closes the database connection.
* @abstract
* @returns {Promise} The promise resolves after closing the database.
*/
close() {} // eslint-disable-line no-unused-vars
/**
* Fully deletes the database.
* @abstract
* @returns {Promise} The promise resolves after deleting the database.
*/
async destroy() {} // eslint-disable-line no-unused-vars
/** @type {boolean} Whether a connection is established. */
get connected() { return false; } // eslint-disable-line no-unused-vars
/**
* Returns the ObjectStore object for a given table name.
* @abstract
* @param {string} tableName The table name to access.
* @returns {ObjectStore} The ObjectStore object.
*/
getObjectStore(tableName) {} // eslint-disable-line no-unused-vars
/**
* Creates a new object store (and allows to access it).
* This method always has to be called before connecting to the database.
* If it is not called, the object store will not be accessible afterwards.
* If a call is newly introduced, but the database version did not change,
* the table does not exist yet.
* @abstract
* @param {string} tableName The name of the object store.
* @param {ObjectStoreConfig} [options] An options object.
* @returns {IObjectStore}
*/
createObjectStore(tableName, options = {}) {} // eslint-disable-line no-unused-vars
/**
* Deletes an object store.
* This method has to be called before connecting to the database.
* @abstract
* @param {string} tableName
* @param {{upgradeCondition:?boolean|?function(oldVersion:number, newVersion:number):boolean}} [options]
*/
deleteObjectStore(tableName, options = {}) {} // eslint-disable-line no-unused-vars
/**
* Creates a volatile object store (non-persistent).
* @abstract
* @param {{codec:?ICodec}} [options] An options object.
* @returns {ObjectStore}
*/
static createVolatileObjectStore(options = {}) {} // eslint-disable-line no-unused-vars
/**
* Is used to commit multiple transactions atomically.
* This guarantees that either all transactions are written or none.
* The method takes a list of transactions (at least two transactions).
* If the commit was successful, the method returns true, and false otherwise.
* @abstract
* @param {Transaction|CombinedTransaction} tx1 The first transaction
* (a CombinedTransaction object is only used internally).
* @param {Transaction} tx2 The second transaction.
* @param {...Transaction} txs A list of further transactions to commit together.
* @returns {Promise.<boolean>} A promise of the success outcome.
*/
static commitCombined(tx1, tx2, ...txs) {} // eslint-disable-line no-unused-vars
}
|
'use strict';
var MarkerPopupController = function($scope, $rootScope, $timeout, $window, $compile, services, leafletData, leafletEvents) {
if (window._gaq) {
window._gaq.push(['_trackEvent', services.config().demoName, 'marker:click']);
}
};
|
var libTools = require("./tools");
exports.TOKENS = {
year: "year",
month: "month",
week: "week",
day: "day",
hour: "hour",
min: "min",
sec: "sec",
ms: "ms"
};
exports.TOKENS_ORDER = ["year", "month", "week", "day", "hour", "min", "sec", "ms"];
exports.TOKENS_MS = {
ms: 1,
sec: 1000,
min: 60000, // 60 * sec
hour: 3600000, // 60 * 60 * sec
day: 86400000, // 24 * hour
week: 604800000, // 7 * day
month: 2592000000, // 30 * day
year: 31536000000 // 365 * day
};
exports.FORMATS = {
condensed: "condensed",
short: "short",
default: "default",
full: "full",
iso: "iso",
postgres: "postgres"
};
exports.DEFAULT_FORMAT = exports.FORMATS.default;
exports.FORMAT_DEFS = {
condensed: require("./formats/condensed.format"),
short: require("./formats/short.format"),
default: require("./formats/default.format"),
full: require("./formats/full.format"),
iso: require("./formats/iso.format"),
postgres: require("./formats/postgres.format")
};
var CACHE = null;
function cache(recook) {
if (recook) {
CACHE = null;
}
if (!CACHE) {
CACHE = {
recognizers: libTools.cookRecognizers(exports.FORMAT_DEFS, exports.TOKENS_ORDER),
tokensMap: libTools.cookTokensMap(exports.FORMAT_DEFS, exports.TOKENS_ORDER)
};
}
return CACHE;
}
exports.cache = cache;
|
(function() {
'use strict';
function allSourcesChartDirective() {
return {
restrict: 'E',
templateUrl: 'scripts/allsourceschart/allSourcesChart.directive.html',
controller: 'AllSourcesChartController',
controllerAs: 'ascCtrl'
};
}
angular.module('uncertApp.allsourceschart').directive('allSourcesChartDirective', allSourcesChartDirective);
})();
|
class NavbarController {
constructor($scope, $firebaseArray, userService) {
'ngInject';
this.name = 'navbar';
this.user = userService.getUser();
this.hint = false;
userService.onChangeAuth((user) => {
this.user = user;
$scope.$apply();
});
}
}
export default NavbarController;
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: {
bundle: path.join(__dirname, 'index.js')
},
output: {
path: path.join(__dirname, 'build'),
filename: '[name].js'
},
module: {
loaders: [
/*
----------------------------------------------------------------
--- 说明:对不同的文件,配置对应的加载器,对应加载器的配置在独立的文件中 ---
----------------------------------------------------------------
*/
{
/*对jsx文件进行ES6->ES5的处理*/
test: /\.js?$/,
loader: 'babel-loader'
}
]
}
}
|
/**
*
* 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';
import idbKeyval from '../../third_party/libs/idb-keyval';
import Utils from './utils';
class LicensePersister {
static get CONTENT_FORMAT () {
return 'cenc';
}
static get CONTENT_TYPE () {
return 'video/mp4; codecs="avc1.4d401f"';
}
static get CONFIG () {
return [{
initDataTypes: [LicensePersister.CONTENT_FORMAT],
videoCapabilities: [{
contentType: LicensePersister.CONTENT_TYPE
}],
persistentState: 'required',
sessionTypes: ['persistent-license']
}];
}
static remove (videoName) {
return idbKeyval.delete(videoName);
}
static restore (session, videoName) {
let tasks = Promise.resolve();
if (this._activeSession) {
console.log('Closing active session.');
tasks = tasks
.then(_ => this._activeSession.close())
.then(_ => {
this._activeSession = null;
});
}
return tasks.then(_ => {
return idbKeyval.get(videoName).then(storedSession => {
if (!storedSession) {
throw new Error('Unable to restore license; please download again.');
return;
}
console.log('Restoring session: ', storedSession);
return session.load(storedSession);
});
});
}
static close (session) {
session.close();
}
static persist (videoName, {name, url, manifest} = drmInfo) {
return idbKeyval.get(videoName).then(storedSession => {
if (storedSession) {
console.log('Already persisted license');
return true;
}
const config = LicensePersister.CONFIG;
const _onMessage = evt => {
const session = evt.target;
this._activeSession = session;
return Utils.load({
url,
body: evt.message
}).then(license => {
session.update(license).then(_ => {
console.log('4. Setting new license: ', license);
console.log('5. Storing license for next play: ' + session.sessionId);
return idbKeyval.set(videoName, session.sessionId);
})
.catch(error => {
console.error('Failed to update the session', error);
});
});
};
return navigator.requestMediaKeySystemAccess(name, config)
.then(keySystemAccess => {
console.log(`1. Creating Media Keys ${name}`);
return keySystemAccess.createMediaKeys();
})
.then(createdMediaKeys => {
console.log('2. Setting Media Keys', createdMediaKeys);
return createdMediaKeys.createSession('persistent-license');
})
.then(session => {
// Get the PSSH data from the manifest.
return fetch(manifest)
.then(r => r.text())
.then(manifestText => {
const parser = new DOMParser();
return parser.parseFromString(manifestText, 'text/xml');
})
.then(manifestDoc => {
if (!manifestDoc) {
console.log('Unable to read manifest');
return false;
}
const PSSH = Array
.from(manifestDoc.querySelectorAll('*'))
.find(node => node.nodeName === 'cenc:pssh');
if (!PSSH) {
console.log('No PSSH');
return false;
}
console.log('3. Using PSSH data: ' + PSSH.textContent);
const initData = Utils.base64ToUint8Array(PSSH.textContent);
session.addEventListener('message', _onMessage);
return session.generateRequest('cenc', initData);
});
})
.catch(error => {
console.error('Failed to set up MediaKeys', error);
});
});
}
}
export default LicensePersister;
|
'use strict';
app.factory('ordersService', ['$http', 'ngAuthSettings', function ($http, ngAuthSettings) {
var serviceBase = ngAuthSettings.apiServiceBaseUri;
var ordersServiceFactory = {};
var _getOrders = function () {
return $http.get(serviceBase + 'api/orders').then(function (results) {
return results;
});
};
ordersServiceFactory.getOrders = _getOrders;
return ordersServiceFactory;
}]);
|
/**
* @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';
/**
* Evaluate the incomplete gamma function.
*
* @module @stdlib/math/base/special/gammainc
*
* @example
* var gammainc = require( '@stdlib/math/base/special/gammainc' );
*
* var v = gammainc( 6.0, 2.0 );
* // returns ~0.9826
*
* v = gammainc( 1.0, 2.0, true, true );
* // returns ~0.7358
*
* v = gammainc( 7.0, 5.0 );
* // returns ~0.8270
*
* v = gammainc( 7.0, 5.0, false );
* // returns ~19.8482
*
* v = gammainc( NaN, 2.0 );
* // returns NaN
*
* v = gammainc( 6.0, NaN );
* // returns NaN
*/
// MODULES //
var gammainc = require( './gammainc.js' );
// EXPORTS //
module.exports = gammainc;
|
const userService = require('../../services/consumers/user.service');
const appService = require('../../services/consumers/application.service');
module.exports = function findConsumer (id) {
return userService.findByUsernameOrId(id)
.then(user => {
if (user) {
return user;
}
return appService.findByNameOrId(id);
});
};
|
goog.provide('ms.Grid');
/**
* One map sheets grid.
* @constructor
*/
ms.Grid = function() {
/**
* Title.
* @type {string}
*/
this.title;
/**
* Series that defines this grid.
* @type {ms.Series}
*/
this.mainSeries;
/**
* Map series with given grid.
* @type {Array.<ms.Series>}
*/
this.seriess;
};
/**
* @return {string} title without region part.
*/
ms.Grid.prototype.getShortTitle = function() {
return this.title.substr(this.title.indexOf(':') + 1);
};
|
// Utility functions for obtaining and diffing top and latency histogram statistics.
/**
* Returns the latency histograms for the given collection.
*/
function getHistogramStats(coll) {
return coll.latencyStats().next().latencyStats;
}
/**
* Returns the differences in read, write, and command counts between two histograms.
*/
function diffHistogram(coll, thisHistogram, lastHistogram) {
return {
reads: thisHistogram.reads.ops - lastHistogram.reads.ops,
writes: thisHistogram.writes.ops - lastHistogram.writes.ops,
commands: thisHistogram.commands.ops - lastHistogram.commands.ops
};
}
/**
* Asserts that the difference of histogram stats on collection coll since the lastHistogram was
* recorded is equal to the readDiff, writeDiff, and commandDiff values. Returns the new histogram.
*/
function assertHistogramDiffEq(coll, lastHistogram, readDiff, writeDiff, commandDiff) {
let thisHistogram = getHistogramStats(coll);
let diff = diffHistogram(coll, thisHistogram, lastHistogram);
// Running the $collStats aggregation itself will increment read stats by one.
assert.eq(diff.reads, readDiff + 1, "miscounted histogram reads");
assert.eq(diff.writes, writeDiff, "miscounted histogram writes");
assert.eq(diff.commands, commandDiff, "miscounted histogram commands");
return thisHistogram;
}
/**
* Asserts that top contains stats for this collection and returns the recorded stats.
*/
function getTop(coll) {
let collName = coll.getFullName();
let res = coll.getDB().adminCommand("top");
assert.commandWorked(res);
assert.eq(true, res.totals.hasOwnProperty(collName), collName + " not found in top");
return res.totals[collName];
}
/**
* Returns the difference of the time and count for a given key of two sets of top stats.
*/
function diffTop(key, thisTop, lastTop) {
return {
time: thisTop[key].time - lastTop[key].time,
count: thisTop[key].count - lastTop[key].count
};
}
/**
* Asserts that the count difference of top stats of the key on collection coll since lastTop was
* recorded is equal to expectedCountDiff. Returns the new top stats.
*/
function assertTopDiffEq(coll, lastTop, key, expectedCountDiff) {
let thisTop = getTop(coll);
let diff = diffTop(key, thisTop, lastTop);
assert.gte(diff.count, 0, "non-decreasing count");
// TODO (JBR for SERVER-26812): We don't currently guarantee that the time will not be zero
// which causes occaisional test failures here. If we change the timers in top to use a
// monotonic clock in SERVER-26812, then we can uncomment these.
// assert.gte(diff.time, 0, "non-decreasing time");
// assert.eq(diff.count !== 0, diff.time > 0, "non-zero time iff non-zero count");
assert.eq(diff.count, expectedCountDiff, "top reports wrong count for " + key);
return thisTop;
}
|
import React, {Component} from 'react';
import './styles.scss';
import {cssClassName} from 'utils'
import A_Container from 'A_Container'
const cn = cssClassName('ContactUs');
import A_H from 'A_H';
import A_P from 'A_P';
import A_Link from 'A_Link';
import O_Hero from 'O_Hero'
class ContactUs extends Component {
render() {
return (
<div className={cn('section-wrapper')}>
<A_Container type='equal'>
<O_Hero>
<A_H type='hero'>Contact Humaniq</A_H>
<A_P type='hero'>Humaniq is proud of its wide partnership network which includes everybody from fintech companies and Blockchain communities to publishing media and app developers.</A_P>
</O_Hero>
<div className={cn('contactus')}>
<section className={cn('support')}>
<A_H type='section'>Customer Support</A_H>
<A_P type='third'>For any questions you may have please contact:</A_P>
<A_Link to="mailto:info@humaniq.com" type='primary' external>info@humaniq.com</A_Link>
</section>
<section className={cn('policy')}>
<A_H type='section'>Questions regarding Privacy Policy</A_H>
<A_P type='third'>If you have any questions regarding our user or data Privacy Policy, please <A_Link to="mailto:info@humaniq.com" type='primary' external>reach out to us.</A_Link></A_P>
</section>
{/*<section className={cn('partnerships')}>*/}
{/*<A_H type='section'>Partnerships</A_H>*/}
{/*<A_P type='third'>For any inquires regarding partnerships, please <A_Link to="/form/join" type='primary'>fill out this form.</A_Link></A_P>*/}
{/*</section>*/}
{/*<section className={cn('program')}>*/}
{/*<A_H type='section'>Ambassador’s Program</A_H>*/}
{/*<A_P type='third'>If you want to become a part of Humaniq’s Global Initiative Program, please <A_Link to="/form/ambassadors" type='primary'>fill out this form.</A_Link></A_P>*/}
{/*</section>*/}
<section className={cn('office')}>
<A_H type='section'>Humaniq’s Legal Office</A_H>
<ul className={cn('address')}>
<li>41 Luke St</li>
<li>London, EC2A</li>
<li>United Kingdom</li>
</ul>
</section>
</div>
</A_Container>
</div>
)
}
}
export default ContactUs;
|
var dir_4f0d91c6eae7618629055f626fa2f2b6 =
[
[ "cli", "dir_6f1e4bedc91251929933596116aeb2f9.html", "dir_6f1e4bedc91251929933596116aeb2f9" ]
];
|
import { ActionTypes } from 'actions/account-info';
import { combineReducers } from 'redux';
import { createPagedReducer } from './paged';
// Default state for the user profile info
const defaultUserInfo = {
isLoading: false
};
// Reducer for the user profile info
function user(state = defaultUserInfo, action) {
switch (action.type) {
case ActionTypes.RESET_USER:
return defaultUserInfo;
case ActionTypes.GET_USER.LOADING:
return {
isLoading: true
};
case ActionTypes.GET_USER.SUCCESS:
return {
isLoading: false,
...action.payload
};
case ActionTypes.GET_USER.FAILURE:
return {
isLoading: false
};
}
return state;
}
// Create reducers for user's comments and videos
const COMMENTS_LIST_ID = 'userComments';
const COMMENTS_PAGING_CONFIG = {
recordsPerPage: 5,
recordsPerRequest: 10
};
const comments = createPagedReducer(COMMENTS_LIST_ID, COMMENTS_PAGING_CONFIG);
const VIDEOS_LIST_ID = 'userVideos';
const VIDEOS_PAGING_CONFIG = {
recordsPerPage: 10
};
const videos = createPagedReducer(VIDEOS_LIST_ID, VIDEOS_PAGING_CONFIG);
const accountInfo = combineReducers({
user,
comments,
videos
});
export default accountInfo;
|
var url = "http://10.16.90.76/php/";
var content = "application/json; charset=UTF-8";
window.onload = function(){
$.ajax({
type : "GET",
url : url+"get_primeiros_registros.php",
contentType: content,
success: function (response) {
var json = JSON.parse(response);
if(json['success']){
inserir_resultado(json['data']);
}else{
alert('erro');
}
},
error: function (e) {
console.log(e);
}
});
}
function buscar(){
$.ajax({
type : "GET",
url : url+"buscar_masp_cpf.php?type="+$("#maspcpf").val()+"&number="+$("#inp_buscar").val(),
contentType: content,
success: function (response) {
var json = JSON.parse(response);
if(json['success']){
inserir_resultado(json['data']);
}else{
alert('erro');
}
},
error: function (e) {
console.log(e);
}
});
}
function inserir_resultado(data){
$('#tabela_ultimos_registros td').remove();
for (let index = 0; index < data.length; index++) {
if (data[index].state == "PENDENTE") {
$("#tabela_ultimos_registros tbody").append(
'<tr>'+
'<td>'+ data[index].nome_1_0 +'</td>'+
'<td>'+ data[index].cpf_1_1 +'</td>'+
'<td>'+ data[index].masp_1_1 +'</td>'+
'<td>'+ data[index].dt_2_0 +'</td>'+
'<td style="color: yellow; font-weight: bold">'+ data[index].state +'</td>'+
'<td>' +
'<div class="btn-group btn-group-sm">' +
'<div class="btn-group"> ' +
'<a href="#" class="parents js-view-parents">' +
'<span class="glyphicon glyphicon-eye-open" style="color:black;" onclick="visualizar('+ data[index].id_finalidade +','+ data[index].id_pessoa +')"></span>' +
'</a>' +
'</div>' +
'<div class="btn-group ">' +
'<a href="#">' +
'<span class="glyphicon glyphicon-pencil" aria-hidden="true" style="color: black; margin-left: 10px;" onclick="editar('+ data[index].id_finalidade +','+ data[index].id_pessoa +')"></span>' +
'</a>' +
'</div>' +
'</div>' +
'</td>' +
'</tr>'
);
}
else {
$("#tabela_ultimos_registros tbody").append(
'<tr>'+
'<td>'+ data[index].nome_1_0 +'</td>'+
'<td>'+ data[index].cpf_1_1 +'</td>'+
'<td>'+ data[index].masp_1_1 +'</td>'+
'<td>'+ data[index].dt_2_0 +'</td>'+
'<td style="color: green; font-weight: bold">'+ data[index].state +'</td>'+
'<td>' +
'<div class="btn-group btn-group-sm">' +
'<div class="btn-group"> ' +
'<a href="#" class="parents js-view-parents">' +
'<span class="glyphicon glyphicon-eye-open" style="color:black;" onclick="visualizar('+ data[index].id_finalidade +','+ data[index].id_pessoa +')"></span>' +
'</a>' +
'</div>' +
'</div>' +
'</td>' +
'</tr>'
);
}
}
}
function visualizar(finalidade, identificacao) {
window.open("http://10.16.90.76/visualizar_formulario/index.php?id="+identificacao+"&fi="+finalidade);
}
function editar(finalidade, identificacao) {
window.open("http://10.16.90.76/editar_formulario/index.php?id="+identificacao+"&fi="+finalidade);
}
function mascara(o,f){
v_obj=o
v_fun=f
setTimeout("execmascara()",1)
}
function execmascara(){
v_obj.value=v_fun(v_obj.value)
}
function cpf(v){
if(document.getElementById("maspcpf").value == 1){
v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
v=v.replace(/(\d{3})(\d)/,"$1.$2") //Coloca um ponto entre o terceiro e o quarto dígitos
v=v.replace(/(\d{3})(\d)/,"$1.$2") //Coloca um ponto entre o terceiro e o quarto dígitos de novo (para o segundo bloco de números)
v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
return v
}else{
v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
v=v.replace(/(\d{3})(\d)/,"$1.$2") //Coloca um ponto entre o terceiro e o quarto dígitos
v=v.replace(/(\d{2})(\d{1,1})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
return v
}
}
|
/**
* @ngdoc directive
* @name safe-utils.directive:fallbacked-src
*
* @element img
*
* @description
*
* Verilen resim kaynağı boşsa veya resim yüklenemediyse
* img etiketini silip yerine `noimage` class'lı boş bir
* div ekleyen directive
*
* @example
<example>
<file name="index.html">
<img fallbacked-src="/resim-yuklenemedi.jpg">
</file>
</example>
*/
angular.module('sahibinden.image', [])
.directive('fallbackedSrc', function () {
'use strict';
return {
restrict: 'A',
require: '?img',
link: function (scope, element, attrs) {
var placeholder = angular.element(document.createElement('span')).addClass('noImage ng-hide');
element.after(placeholder);
element.bind('error', function () {
element.addClass('ng-hide');
placeholder.removeClass('ng-hide');
});
attrs.$observe('fallbackedSrc', function (value) {
if (value !== '') {
element.attr('src', value).removeClass('ng-hide');
placeholder.addClass('ng-hide');
} else {
element.addClass('ng-hide');
placeholder.removeClass('ng-hide');
}
});
}
};
});
|
//销毁上一个content页面遗留vueContentObject对象实例
if (vueContentObject)
getVueObject().$destroy();
// 当前用户能够操作的所有行为
var actions = {'update': {'key': 'update', 'url': 'singleUpdate'}};
//table column 显示名
tableColumnsName = ['ID', 'UserID', '昵称', '用户名', '角色', '操作'];
//table column 对应data中的属性名
tableColumnsKey = ['id', 'userId', 'nickname', 'username', 'roleName', 'operation'];
//table 每行需要的按钮
tableButtonsOnEachRow = ['clickRowSetRoleButton#设置'];
//分页取数据url
loadPageableDataUrl = 'userRolesByPage';
//格式化table行数据格式
parseValuesOnTableEachRow = function (obj) {
return {
id: obj.id,
userId: obj.userId,
nickname: obj.nickname,
username: obj.username,
roleName: obj.roleName === '' ? '暂无角色' : obj.roleName};
};
//设置add update vue form data obj
//setFormDataObject({id: -1, name: '', priority: ''});
//排序方法
vueContentMethods.vueBindTableSortMethod = function (a, b, c, d, e) {
this.vueTableLoadPageMethod();
console.log(a);
console.log(b);
console.log(e);
console.log(d);
console.log(e);
};
// 自定义 Data
vueContentBeforeCreate = function () {
customVueContentData = {
vueSetRoleTreeData: loadSetRoleAllRole2TreeData(),
vueSetRoleFormData: {userId: 0, nickName: '', userName: '', allRoles: [], userRoles: []},
vueSetRoleCondition: null,
vueSetRoleModalVisible: false
};
};
hasQueryForm = false; //是否有queryForm
// 自定义 Module
vueContentMethods.loadSetRoleAllRole2TreeData = loadSetRoleAllRole2TreeData;
vueContentMethods.onSelectChangeTree = onSelectChangeTree;
vueContentMethods.clickRowSetRoleButton = clickRowSetRoleButton;
vueContentMethods.loadSetRoleUserRole = loadSetRoleUserRole;
vueContentMethods.submitSetRoleForm = submitSetRoleForm;
vueContentMethods.cancelSetRoleForm = cancelSetRoleForm;
vueContentMethods.loadUserRolesBypage = loadUserRolesBypage;
//调入所有权限信息并初始化
function loadSetRoleAllRole2TreeData() {
let curSetRoleTreeData = [{title: '角色列表', expand: true, selected: true, children: []}];
$.iposty('all', {}, function (data) {
for (let role of data.all) {
curSetRoleTreeData[0].children.push({title: role.name, id: role.id});
}
});
return curSetRoleTreeData;
}
//
function onSelectChangeTree() {
let treeData = this.vueSetRoleTreeData;
if (treeData[0].selected) {
this.vueSetRoleCondition = null;
this.doLoadPage(); //loadUserRolesBypage(vueCurrentPage - 1, this[currentPageSizeName], null);
} else {
let selectedRoleId = treeData[0].children.find(obj => obj.selected);
if (selectedRoleId === undefined) {
if (this.vueSetRoleCondition === null) {
treeData[0].selected = true;
} else {
treeData[0].children.find(obj => obj.id === this.vueSetRoleCondition.ids).selected = true;
}
} else {
this.vueSetRoleCondition = {ids: selectedRoleId.id};
}
loadUserRolesBypage(0, this[currentPageSizeName], this.vueSetRoleCondition);
}
}
//
function loadUserRolesBypage(page, size, condition) {
$.iposty("userRolesByPage", {page: page, size: size, condition: condition}, function (data) {
vueContentObject.vueTableData = [];
for (let rowContent of data.pageableData.content) {
let row = {};
for (let key of tableColumnsKey) {
row[key] = rowContent[key];
}
vueContentObject.vueTableData.push(row);
}
vueContentObject.vueRecordTotal = data.pageableData.totalElements;
setTimeout(toastLoading('正在加载中...', 0), 30);
});
}
//
function clickRowSetRoleButton(index, tableDataName) {
this.vueSetRoleFormData.allRoles = [];
let formdata = this.vueSetRoleFormData;
formdata.userId = this.vueTableData[index].userId;
formdata.nickName = this.vueTableData[index].nickname;
formdata.userName = this.vueTableData[index].username;
for (let children of this.vueSetRoleTreeData[0].children) {
formdata.allRoles.push({id: children.id, name: children.title});
}
this.loadSetRoleUserRole(formdata.userId);
this.vueSetRoleModalVisible = true;
}
//调入角色相应的权限并更新
function loadSetRoleUserRole(userId) {
$.iposty("singleUserRoleCombineRole", {id: userId}, function (data) {
vueContentObject.vueSetRoleFormData.userRoles = data.obj.roleName.split(",").slice(0);
});
}
//Modal 提交按钮
function submitSetRoleForm() {
let formdata = this.vueSetRoleFormData;
if (formdata.userRoles[0] === '') {
formdata.userRoles.splice(0, 1);
}
let roleId = "";
for (let userRole of formdata.userRoles) {
for (let allRole of formdata.allRoles) {
if (userRole === allRole.name) {
roleId += ((roleId === "") ? "" : ",") + allRole.id;
break;
}
}
}
$.iposty("setUserRoles", {userId: this.vueSetRoleFormData.userId, roleId: roleId}, function (data) {
vueContentObject.loadUserRolesBypage(vueCurrentPage - 1, vueContentObject[currentPageSizeName], vueContentObject.vueSetRoleCondition);
});
this.cancelSetRoleForm();
}
//Modal 取消按钮 / X按钮
function cancelSetRoleForm() {
this.vueSetRoleFormData = {userId: 0, nickName: '', userName: '', allRoles: [], userRoles: []};
this.vueSetRoleModalVisible = false;
}
var vueContentObject = new Vue(initializeContentOptions());
|
/*
Copyright 2015 Packt Publishing
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.
*/
(function( $, undefined ) {
function run( ) {
console.log( "I'm running from script_a.js!" );
}
$( run );
})( jQuery );
|
import React from 'react'
import { render } from 'react-dom'
import { Router, Route, browserHistory } from 'react-router'
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import './index.css'; // bootstrap css
import App from './App';
import IHM_N3 from './maquinas/perfiladeiras/n3';
import IHM_N3_MAIN from './maquinas/perfiladeiras/n3/main.js';
import IHM_N3_AUTOMATICO from './maquinas/perfiladeiras/n3/automatico.js';
import IHM_N3_MANUAL from './maquinas/perfiladeiras/n3/manual.js';
const NoMatch = props => (
<div><h1>Rota não encontrada !</h1></div>
)
render((
<Router history={browserHistory}>
<Route path="/" component={App} >
{/* incluir novas maquinas aqui*/}
<Route path="maquinas/perfiladeiras/n3" component={IHM_N3}>
<Route path="main" component={IHM_N3_MAIN}/>
<Route path="automatico" component={IHM_N3_AUTOMATICO}/>
<Route path="manual" component={IHM_N3_MANUAL}/>
</Route>
{/*fim*/}
<Route path="*" component={NoMatch}/>
</Route>
</Router>
), document.getElementById('root'))
|
'use strict';
var url = require('url');
var Announcement = require('./AnnouncementService');
module.exports.announcementsGET = function announcementsGET (req, res, next) {
Announcement.announcementsGET(req.swagger.params, res, next);
};
module.exports.announcementsPOST = function announcementsPOST (req, res, next) {
Announcement.announcementsPOST(req.swagger.params, res, next);
};
|
/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Fields can be created based on a JSON definition. This file
* contains methods for registering those JSON definitions, and building the
* fields based on JSON.
* @author bekawestberg@gmail.com (Beka Westberg)
*/
'use strict';
goog.provide('Blockly.fieldRegistry');
goog.require('Blockly.registry');
goog.requireType('Blockly.Field');
goog.requireType('Blockly.IRegistrableField');
/**
* Registers a field type.
* Blockly.fieldRegistry.fromJson uses this registry to
* find the appropriate field type.
* @param {string} type The field type name as used in the JSON definition.
* @param {!Blockly.IRegistrableField} fieldClass The field class containing a
* fromJson function that can construct an instance of the field.
* @throws {Error} if the type name is empty, the field is already
* registered, or the fieldClass is not an object containing a fromJson
* function.
*/
Blockly.fieldRegistry.register = function(type, fieldClass) {
Blockly.registry.register(Blockly.registry.Type.FIELD, type, fieldClass);
};
/**
* Unregisters the field registered with the given type.
* @param {string} type The field type name as used in the JSON definition.
*/
Blockly.fieldRegistry.unregister = function(type) {
Blockly.registry.unregister(Blockly.registry.Type.FIELD, type);
};
/**
* Construct a Field from a JSON arg object.
* Finds the appropriate registered field by the type name as registered using
* Blockly.fieldRegistry.register.
* @param {!Object} options A JSON object with a type and options specific
* to the field type.
* @return {?Blockly.Field} The new field instance or null if a field wasn't
* found with the given type name
* @package
*/
Blockly.fieldRegistry.fromJson = function(options) {
var fieldObject = /** @type {?Blockly.IRegistrableField} */ (
Blockly.registry.getObject(Blockly.registry.Type.FIELD, options['type']));
if (!fieldObject) {
console.warn('Blockly could not create a field of type ' + options['type'] +
'. The field is probably not being registered. This could be because' +
' the file is not loaded, the field does not register itself (Issue' +
' #1584), or the registration is not being reached.');
return null;
}
return fieldObject.fromJson(options);
};
|
ajsl.log = {
_levels : {
'trace' : 5,
'debug' : 4,
'info' : 3,
'log' : 3,
'warn' : 2,
'error' : 1,
'none' : 0
},
_fbug : false,
_lvl : 5,
_div : null,
init : function() {
// register in window
window.LOG = this;
// look for firebug
if (window.console && window.console.firebug) {
this._fbug = true;
}
// register in jquery
// TODO: change this
var $this = this;
jQuery.fn.LOG = function(msg) {
$this.log("%s: %o", msg, this);
return this;
};
// register ajax events
$().ajaxError(function (e, xhr, settings, exception) {
LOG.info("load error", e);
});
// register to window onerror
window.onerror = function(errorMsg, url, lineNumber) {
LOG.error("Uncaught exception " + errorMsg + " at " + url + " :" + lineNumber);
return true;
};
},
// this._out = {'console', 'div'};
// ///////////////////////
setLevel : function(level) {
if (this._levels[level] == undefined) {
LOG.error("can not set ajsl logger to level ", level);
}
this._lvl = this._levels[level];
},
// ////////////
trace : function() {
if (this._lvl >= 5) {
this._logger('trace', arguments);
}
},
debug : function() {
if (this._lvl >= 4) {
this._logger('debug', arguments);
}
},
info : function() {
if (this._lvl >= 3) {
this._logger('info', arguments);
}
},
log : function() {
if (this._lvl >= 3) {
this._logger('log', arguments);
}
},
warn : function() {
if (this._lvl >= 2) {
this._logger('warn', arguments);
}
},
error : function() {
if (this._lvl >= 1) {
this._logger('error', arguments);
}
},
// ////////////
assert : function(expr) {
if (this._lvl >= 1) {
try {
throw "assert fail";
} catch (e) {
LOG.exception(e);
}
}
// console.assert("str".length == 23);
},
exception : function(e, back) {
if (this._lvl >= 1) {
if (this._fbug) {
var tmp = [ e ];
eval('console.exception(tmp[0])');
}
// div error
}
},
_logger : function(lvl, args) {
// firebug
if (this._fbug) {
var fbugLvl = lvl;
if (lvl == 'trace') {
fbugLvl = 'debug';
}
this._fbugConsole(fbugLvl, args);
}
// div error
this._divConsole(lvl, args);
},
_fbugConsole : function(lvl, args) {
var res = "";
for ( var i = 0; args[i] != undefined; i++) {
if (i != 0) {
res += ",";
}
res += "args[" + i + "]";
}
eval('console[lvl](' + res + ')');
},
_divConsole : function(lvl, args) {
if (this._div == null) {
this._createDiv();
}
var argsArray = Array.prototype.slice.call(args);
var logDiv = $("<div>" + lvl + " : " + argsArray.join(" ") + "</div>");
this._div.append(logDiv);
},
_createDiv : function() {
this._div = $('<div id="console" class="ui-widget-content"><h3 class="ui-widget-header">Console</h3></div>');
this._div.css( {position: "absolute", bottom : 0, right : 0, border : "1px solid red", backgroundColor : "white", 'z-index' : 100000, height: '100px', overflow : 'auto'});
this._div.resizable({animate: true});
$('body').append(this._div);
}
};
ajsl.log.init();
|
//// [duplicateTypeParameters3.ts]
interface X {
x: () => <A, A>() => void;
}
//// [duplicateTypeParameters3.js]
|
import StrengthFormulaModule from './strengthFormula'
import StrengthFormulaController from './strengthFormula.controller';
import StrengthFormulaComponent from './strengthFormula.component';
import StrengthFormulaTemplate from './strengthFormula.html';
describe('StrengthFormula', () => {
let $rootScope, makeController;
beforeEach(window.module(StrengthFormulaModule));
beforeEach(inject((_$rootScope_) => {
$rootScope = _$rootScope_;
makeController = () => {
return new StrengthFormulaController();
};
}));
describe('Module', () => {
// top-level specs: i.e., routes, injection, naming
});
describe('Controller', () => {
// controller specs
it('has a name property [REMOVE]', () => { // erase if removing this.name from the controller
let controller = makeController();
expect(controller).to.have.property('name');
});
});
describe('Template', () => {
// template specs
// tip: use regex to ensure correct bindings are used e.g., {{ }}
it('has name in template [REMOVE]', () => {
expect(StrengthFormulaTemplate).to.match(/{{\s?\$ctrl\.name\s?}}/g);
});
});
describe('Component', () => {
// component/directive specs
let component = StrengthFormulaComponent;
it('includes the intended template',() => {
expect(component.template).to.equal(StrengthFormulaTemplate);
});
it('invokes the right controller', () => {
expect(component.controller).to.equal(StrengthFormulaController);
});
});
});
|
const STATIC_REG = /.*\.(png|jpe?g|gif|svg|woff2?|eot|ttf|otf)$/
const VER_REG = /[\W][\d\w]+(?=\.\w+$)/;
export default (req, res, next) => {
let filePaths = req.url.split('/')
if (STATIC_REG.test(req.path) && filePaths[2] === 'prd') {
filePaths.splice(2, 1)
req.url = filePaths.join('/').replace(VER_REG, '')
}
next()
}
|
/*! angualr-demo 2015-11-09 */
|
if(typeof _ !== 'undefined') {
_.ai = ai.lodashExtensions;
var mixinObject = {};
_.each(_.keys(ai.lodashExtensions), function(methodName) {
if(!_.has(_, methodName)) {
mixinObject[methodName] = ai.lodashExtensions[methodName];
}
});
if(!_.isEmpty(mixinObject)) {
_.mixin(mixinObject);
}
}
|
const code = `
Flexio.pipe()
.javascript((context) => {
context.output.write("Hello, world.")
})
.javascript((context) => {
var data = context.input.read()
context.output.write(data.toUpperCase())
})
.run(function(err, response) {
console.log(response.text)
})`
const fn = (Flexio, callback) => {
Flexio.pipe()
.javascript((context) => {
context.output.write("Hello, world.")
})
.javascript((context) => {
var data = context.input.read()
context.output.write(data.toUpperCase())
})
.run(callback)
}
export default {
title: 'Simple Input/Output with Javascript jobs',
code,
fn
}
|
// 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 app from "../../app";
import FauxtonAPI from "../../core/api";
import ActiveTasksResources from "./resources";
import ActiveTasksComponents from "./components.react";
import Actions from "./actions";
var ActiveTasksRouteObject = FauxtonAPI.RouteObject.extend({
selectedHeader: 'Active Tasks',
layout: 'one_pane',
disableLoader: true,
routes: {
'activetasks/:id': 'showActiveTasks',
'activetasks': 'showActiveTasks'
},
crumbs: [
{'name': 'Active Tasks', 'link': 'activetasks'}
],
apiUrl: function () {
var apiurl = window.location.origin + '/_active_tasks';
return [apiurl, FauxtonAPI.constants.DOC_URLS.ACTIVE_TASKS];
},
roles: ['_admin'],
initialize: function () {
this.allTasks = new ActiveTasksResources.AllTasks();
},
showActiveTasks: function () {
Actions.init(this.allTasks);
this.setComponent('#dashboard-content', ActiveTasksComponents.ActiveTasksController);
this.setComponent('#right-header', ActiveTasksComponents.ActiveTasksPollingWidgetController);
}
});
ActiveTasksResources.RouteObjects = [ActiveTasksRouteObject];
export default ActiveTasksResources;
|
export { default } from './Layer';
|
/**
* Copyright (C) 2014 Wesleyan University
*
* 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.
*/
(function() {
Tp.ContextView = Backbone.View.extend({
initialize: function() {
return Tp.actions.bind("change:selection", this.actionChanged);
},
actionChanged: function() {
var action, module;
action = Tp.actions.selection;
module = Tp.modules[action != null ? typeof action.get === "function" ? action.get('module') : void 0 : void 0];
Tp.log(module);
$(".context-area").html((module != null ? typeof module.render === "function" ? module.render() : void 0 : void 0) || "");
return module != null ? typeof module.module_loaded === "function" ? module.module_loaded() : void 0 : void 0;
}
});
}).call(this);
|
// F O R
// D E V E L O P M E N T O N L Y
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
/* since content security policy got more strict with manifest
version 2 and I still want to load some stuff dynamically
I need to get the hashes of used inline-scripts and add them
to manifest.json - so far this is the only good workaround for
this problem and to spare me some time, I'm generating the hashes
while going (manually) through the background-page
*/
var csp_hashes = [], csp_result;
$(document).on('DOMNodeInserted', function(e){
var target = e.target;
if(
(!$(target).attr('src')) &&
(!$(target).attr('class')) &&
($(target).prop('tagName') === 'SCRIPT')
){
target = target.innerHTML,
target = sjcl.hash.sha256.hash(target),
target = sjcl.codec.base64.fromBits(target);
csp_hashes.indexOf(target) === -1 ? csp_hashes.push(target) : false;
$.get('manifest.json', function(res){
var csp_string = "'sha256-" + csp_hashes.join("' 'sha256-") + "'",
csp_string = "script-src 'self' 'unsafe-eval' "+csp_string+";object-src 'self'"
csp_result = res;
csp_result.content_security_policy = csp_string;
});
}
});
function downloadManifest(){
download(JSON.stringify(csp_result, null, "\t"), 'manifest.json', 'application/json')
}
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// Fix for warnings about sync requests (we are loading scripts inside html-templates)
// ToDo: remove when using fetch - since it shouldn't error out
$.ajaxPrefilter(function( options, original_Options, jqXHR ){ options.async = true; });
/*************************************************
MUTATION OBSERVER FOR MULTILANGUAGE
Because security-concerns blabla we need to
add mutlilang-text when DOM is updated/modified
(we can´t use placeholders inside html)
Now using Mutation Observer for better performance
*************************************************/
$(document).on("ready", function() {
$('[data-i18n]').each(function() {
var datavalue = $(this).data('i18n');
$(this).prepend(browser.i18n.getMessage(datavalue));
});
// Listen for added elements and iterate over nodelist
// only update added elements!
var target = document.querySelector('.wrapper');
var observer = new MutationObserver(function(mutation) {
for (var m of mutation) {
$(m.addedNodes).each(function(value, index) {
var nodes = $(index).find('[data-i18n]');
$(nodes).each(function() {
var datavalue = $(this).data('i18n');
$(this).prepend(browser.i18n.getMessage(datavalue));
});
});
}
});
var config = { attributes: true, childList: true, subtree: true, characterData: true };
observer.observe(target, config);
});
$(document).ready(function(){
// Sidebar-Toggle - use AdminLTE framework
toggleSidebar();
// generate Database menu entries
idb.opendb().then(function(db){
var tables = Object.keys(db._allTables),
tblstr = '';
for(var i=0;i<tables.length;i++){ tblstr += '<li><a href="#db'+tables[i]+'" data-table="'+tables[i]+'">'+tables[i]+'</a></li>'; }
$('#loadDbContent').append(tblstr);
// Events for Content-Loading + Menu
var hash = window.location.hash;
(hash === '') ? loadContent($('.sidebar-menu li a').get(0)) : loadContent($('a[href="'+hash+'"]')[0]);
});
$(window).on('hashchange', function(){ loadContent($('a[href="'+window.location.hash+'"]')[0]); });
$('.sidebar-menu li a, .treeview-menu li a').on('click', function(){ loadContent(this); });
});
function loadContent(that){
// Don't reload content - especially on hashchange which happens inside this function too
if($(that).parent().is('.active')) return;
// Get values to find out which menu-item was clicked
var parent = $(that).parent().get(0),
menuElem = $('ul li:eq(0)', parent),
treeView = $(parent).is('.treeview') || false,
treeIndex = $(that).closest('.sidebar-menu > li').index(),
allMenus = '.sidebar-menu li, .treeview-menu li',
eid = (treeView) ? $('a', menuElem).attr('href') : $(that).attr('href');
// Toggle active-class on menus
if(treeView){
$(allMenus).removeClass('active');
$(parent).add(menuElem).addClass('active');
}
else if(!treeView){
$(allMenus).add('.sidebar-menu > li:not(:eq('+treeIndex+'))').removeClass('active');
$(parent).add(menuElem).add('.sidebar-menu > li:eq('+treeIndex+')').addClass('active');
}
// Toggle hashchange
window.location.hash = eid;
eid = eid.substr(1); // remove #
// Load Content depending if it uses unique db string or not - remove leading db for function-call
(/db/.test(eid)) ? loadDatabaseContent(eid.substr(2)) : $('.content-wrapper').load('/app_templates/'+eid+'.html');
}
function toggleSidebar(){
// Ripped from https://github.com/almasaeed2010/AdminLTE/issues/896
var $body = $('body');
// On click, capture state and save it in localStorage
$($.AdminLTE.options.sidebarToggleSelector).click(function () {
localStorage.setItem('sidebar', $body.hasClass('sidebar-collapse') ? 1 : 0);
});
// On ready, read the set state and collapse if needed
if (localStorage.getItem('sidebar') === '0') {
$body.addClass('disable-animations sidebar-collapse');
requestAnimationFrame(function () {
$body.removeClass('disable-animations');
});
}
}
function updateProgress(percent, message){
var percentage = Math.round(percent);
$('#progress-bar span').css('width', percentage+'%');
$('#progress-bar span').attr('data-value', percentage);
if(message){
$('#progress-bar + div').text(message);
}
}
|
var quick__sort__simple__vec__dec__real_8f90 =
[
[ "quick_sort_vec_dec_real", "quick__sort__simple__vec__dec__real_8f90.html#gaa06ec59e6a34d94bc37ec7d776769f56", null ]
];
|
/**
* @description Camera SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M1,21 L1,7 L6,7 L8,3 L16,3 L18,7 L23,7 L23,21 L1,21 Z M12,18 C14.7614237,18 17,15.7614237 17,13 C17,10.2385763 14.7614237,8 12,8 C9.23857625,8 7,10.2385763 7,13 C7,15.7614237 9.23857625,18 12,18 Z"/></svg>
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-camera`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'camera');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M1,21 L1,7 L6,7 L8,3 L16,3 L18,7 L23,7 L23,21 L1,21 Z M12,18 C14.7614237,18 17,15.7614237 17,13 C17,10.2385763 14.7614237,8 12,8 C9.23857625,8 7,10.2385763 7,13 C7,15.7614237 9.23857625,18 12,18 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Camera';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
vti_encoding:SR|utf8-nl
vti_timelastmodified:TR|08 Apr 2001 17:51:26 -0000
vti_extenderversion:SR|4.0.2.2717
vti_backlinkinfo:VX|
|
var dir_2386ed5787e70e32ede036a1538ec47a =
[
[ "DataServiceBase.cs", "_dist_2src_2_f_h_s_d_k_2_services_2_data_2_data_service_base_8cs.html", [
[ "DataServiceBase", "class_f_h_s_d_k_1_1_services_1_1_data_1_1_data_service_base.html", "class_f_h_s_d_k_1_1_services_1_1_data_1_1_data_service_base" ]
] ],
[ "IDataService.cs", "_dist_2src_2_f_h_s_d_k_2_services_2_data_2_i_data_service_8cs.html", [
[ "IDataService", "interface_f_h_s_d_k_1_1_services_1_1_data_1_1_i_data_service.html", "interface_f_h_s_d_k_1_1_services_1_1_data_1_1_i_data_service" ]
] ],
[ "IIOService.cs", "_dist_2src_2_f_h_s_d_k_2_services_2_data_2_i_i_o_service_8cs.html", [
[ "IIOService", "interface_f_h_s_d_k_1_1_services_1_1_data_1_1_i_i_o_service.html", "interface_f_h_s_d_k_1_1_services_1_1_data_1_1_i_i_o_service" ]
] ]
];
|
/**
*
* template management, javascript for the management of the templates in the file area and their creation
*
* @author Patrick Lockley
* @version 1.0
* @package
*
* PLEASE USE DOUBLE QUOTES IN THESE FILES, OTHERWISE XERTE TRANS DOES NOT WORK!
*/
var RECYCLE_EDIT = "You cannot edit files in the recycle bin. Please remove the file from the recycle bin before editing";
var FOLDER_EDIT = "You cannot edit a folder. To change a folder's properties please click 'Properties'";
var NO_EXAMPLE = "Sorry an example does not exist for this template";
var PROJECT_SELECT = "Please select a project to preview.";
var RECYCLE_PROPERTIES = "You cannot set the properties on a file in the recycle bin, please remove this file before continuing";
var DELETE_ERROR = "Error while trying to delete template";
var RECYCLE_DUPLICATE = "Please remove content from the recycle bin before duplicating it.";
var DUPLICATE_PROMPT = "Please select a project to duplicate";
var DUPLICATE_PROMPT_OTHER = "Please select a template you would like to duplicate";
var DUPLICATE_LIMIT = "Only 1 template can be duplicated at any time.";
var DUPLICATE_ERROR = "Error while duplicating : ";
var PUBLISH_LIMIT = "Only 1 template can be published at any time";
var PUBLISH_SUCCESS = "Your file has been published";
var WORKSPACE_DELETE = "You cannot delete the Workspace folder";
var DELETE_MULTIPLE_PROMPT = "Are you sure you with to delete these items?";
var DELETE_PROMPT = "Are you sure you wish to delete?";
var DELETE_PERMENANT_PROMPT = "Are you sure you want to permenantly delete file";
var DELETE_FOLDER_NOT_EMPTY = "Sorry you cannot delete a folder that has projects in it. Please empty the folder first";
var NAME_FAIL = "Sorry that is not a valid name. Please use only letters and numbers.";
var FILE_SYNC_FAIL = "Error synchronising ";
var ERROR_DELETE = "Error while trying to delete template";
var ERROR_DUPLICATE = "Error while duplicating ";
var RECYCLE_EMPTY = "Are you sure you want to empty the recycle bin?";
|
'use strict';
var subStateController = function ($scope, $state) {
var vm = this;
vm.$state = $state;
};
console.log('register controller SubStateController');
angular.module('testApp').controller('SubStateController', ['$scope', '$state', subStateController]);
|
// @link http://schemas.wbeme.com/json-schema/eme/users/command/import-user/1-0-0.json#
import EmeAccountsAccountRefV1Mixin from '@wbeme/schemas/eme/accounts/mixin/account-ref/AccountRefV1Mixin';
import Fb from '@gdbots/pbj/FieldBuilder';
import Format from '@gdbots/pbj/enums/Format';
import GdbotsCommonTaggableV1Mixin from '@gdbots/schemas/gdbots/common/mixin/taggable/TaggableV1Mixin';
import GdbotsPbjxCommandV1Mixin from '@gdbots/schemas/gdbots/pbjx/mixin/command/CommandV1Mixin';
import GdbotsPbjxCommandV1Trait from '@gdbots/schemas/gdbots/pbjx/mixin/command/CommandV1Trait';
import Message from '@gdbots/pbj/Message';
import MessageResolver from '@gdbots/pbj/MessageResolver';
import Schema from '@gdbots/pbj/Schema';
import T from '@gdbots/pbj/types';
import UserId from '@wbeme/schemas/eme/users/UserId';
export default class ImportUserV1 extends Message {
/**
* @private
*
* @returns {Schema}
*/
static defineSchema() {
return new Schema('pbj:eme:users:command:import-user:1-0-0', ImportUserV1,
[
Fb.create('user_id', T.IdentifierType.create())
.classProto(UserId)
.build(),
Fb.create('first_name', T.StringType.create())
.build(),
Fb.create('last_name', T.StringType.create())
.build(),
Fb.create('email', T.StringType.create())
.required()
.format(Format.EMAIL)
.build(),
Fb.create('is_staff', T.BooleanType.create())
.build(),
Fb.create('is_active', T.BooleanType.create())
.build(),
Fb.create('created_at', T.MicrotimeType.create())
.useTypeDefault(false)
.build(),
],
[
EmeAccountsAccountRefV1Mixin.create(),
GdbotsPbjxCommandV1Mixin.create(),
GdbotsCommonTaggableV1Mixin.create(),
],
);
}
}
GdbotsPbjxCommandV1Trait(ImportUserV1);
MessageResolver.register('eme:users:command:import-user', ImportUserV1);
Object.freeze(ImportUserV1);
Object.freeze(ImportUserV1.prototype);
|
/*-- Servidor en nodeJS para CineUdea -- */
/*--- DEPENDENCIAS ---*/
var express = require("express"),
bodyParser = require("body-parser"),
path = require("path");
var app = express();
/*-- Controladores del servidor --*/
var ctrlCartelera = require('./servidor/controladores/ctrlCartelera'); //Para operaciones con la cartelera
var peliculaCtrl = require("./servidor/controladores/peliculaCtrl"); //Operaciones de insersión, edición de una nueva pelicula
var cineCtrl = require("./servidor/controladores/cinemasCtrl");
var usuariCtrl = require("./servidor/controladores/usuarioCtrl");
app.use(bodyParser.json());
/*-- Directorios Estaticos --*/
app.use('/cliente', express.static(__dirname + "/cliente"));
app.use('/servidor', express.static(__dirname + "/servidor"));
/*--- END POINTS --*/
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname,'/cliente/index.html'));
});
app.post('/api/cartelera/listar',ctrlCartelera.listarCartelera); //Listo la cartelera
app.get('/api/cines/listar', cineCtrl.listarCinemas); //Listar cines
app.post('/api/pelicula/get', peliculaCtrl.obtenerPelicula); //Obtener una pelicula con el id
//autenticacion
app.post('/api/usuario/login', usuariCtrl.login);
/*-- Corro el servidor --*/
app.listen(process.env.PORT||3000, process.env.IP||"0.0.0.0",function function_name() {
console.log("Servidor corriendo en el puerto: ", process.env.PORT);
});
|
/*
* 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.
*/
'use strict';
angular.module('dgc.tags.definition').controller('DefinitionTagsController', ['$scope', '$resource', '$state', '$stateParams', 'lodash', 'AttributeDefinition', 'TagClasses', 'TagsResource', 'NotificationService',
function($scope, $resource, $state, $stateParams, _, AttributeDefinition, Categories, TagsResource, NotificationService) {
$scope.categoryList = Categories;
$scope.category = 'TRAIT';
$scope.tagModel = {
typeName: null,
attributeDefinitions: []
};
$scope.addAttribute = function AddAttribute() {
$scope.tagModel.attributeDefinitions.push(AttributeDefinition.getModel());
};
$scope.removeAttribute = function(index){
$scope.tagModel.attributeDefinitions.splice(index,1);
};
$scope.categoryChange = function CategorySwitched() {
$scope.categoryInst = Categories[$scope.category].clearTags();
};
$scope.save = function saveTag(form) {
$scope.savedTag = null;
if (form.$valid) {
$scope.categoryInst = Categories[$scope.category];
$scope.categoryInst.clearTags().addTag($scope.tagModel);
NotificationService.reset();
$scope.saving = true;
TagsResource.save($scope.categoryInst.toJson()).$promise
.then(function TagCreateSuccess() {
NotificationService.info('"' + $scope.tagModel.typeName + '" has been created', false);
}).catch(function TagCreateFailed(error) {
NotificationService.error(error.data.error, false);
}).finally(function() {
$scope.saving = false;
});
}
};
}
]);
|
function goActivity(){
var activity = Alloy.createController('navbar').getView();
var navbar = Alloy.createController('activityFeed').getView();
activity.open();
navbar.open();
}
|
treeServices.factory(
'TreeService',
[
'$timeout',
'StorageService',
function ($timeout, StorageService) {
var treeData = {
elements: []
};
var addElement = function (name, parent) {
if (name && name.length) {
if ((typeof parent == 'undefined') || !parent) {
parent = treeData;
}
if ((typeof parent['elements'] == 'undefined') || !parent['elements']) {
parent['elements'] = [];
}
var element = {
name: name,
elements: []
};
parent['elements'].push(element);
StorageService.setObject('tree', treeData.elements);
element['isNew'] = 1;
(function (element) {
$timeout(function () {
delete element['isNew'];
}, 1000)
})(element);
}
};
var editElement = function (name, element) {
if ((typeof element != 'undefined') && element && (name && name.length)) {
element['name'] = name;
StorageService.setObject('tree', treeData.elements);
element['isNew'] = 1;
(function (element) {
$timeout(function () {
delete element['isNew'];
}, 1000)
})(element);
}
};
var removeElement = function (index, parent) {
if ((typeof parent == 'undefined') || !parent) {
parent = treeData;
}
if ((index >= 0) && (typeof parent['elements'] != 'undefined') && (typeof parent['elements'][index] != 'undefined') && parent['elements'][index]) {
if (index <= parent['elements'].length) {
parent['elements'] = parent['elements'].slice(0, index).concat(parent['elements'].slice(index + 1));
StorageService.setObject('tree', treeData.elements);
}
}
};
var init = function () {
var elementsData = StorageService.getObject('tree');
if ((typeof elementsData != 'undefined') && elementsData && elementsData.length) {
var i;
for (i = 0; i < elementsData.length; i++) {
treeData.elements.push(elementsData[i]);
}
}
};
init();
return {
treeData: treeData,
addElement: function (name, parent) {
addElement(name, parent);
},
editElement: function (name, element) {
editElement(name, element);
},
removeElement: function (index, parent) {
removeElement(index, parent);
}
};
}
]
);
|
Ext.define('Notes.view.NotesList', {
extend: 'Ext.Container',
layout: 'fit',
items: [ {
xtype: "toolbar",
title: "My Notes",
docked: "top",
items: [ {
xtype: 'spacer'
}, {
xtype: "button",
text: 'New',
ui: 'action',
handler: 'onNew'
} ]
}, {
xtype: "list",
bind: {
store: '{notes}'
},
loadingText: "Loading Notes...",
emptyText: "<div class=\"notes-list-empty-text\">No notes found.</div>",
onItemDisclosure: true,
grouped: true,
listeners: {
disclose: 'onItemDisclose'
},
// plugins: [ {
// xclass: 'Ext.plugin.PullRefresh'
// } ],
itemTpl: "<div class=\"list-item-title\">{id}: {title}</div><div class=\"list-item-narrative\">{narrative}</div>"
} ]
});
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.22/esri/copyright.txt for details.
/* jshint worker: true */
/* global self: true, postMessage: true */
(function(context) {
var self = context;
function actionHandler(evt) {
var msg = evt.data;
var error, success;
if (msg.action) {
switch(msg.action) {
case 'import-script':
try {
if (!Array.isArray(msg.url)) {
msg.url = [msg.url];
}
self.importScripts.apply(self, msg.url);
success = true;
} catch (err) {
error = err;
postMessage({msgId:msg.msgId, urls:msg.url, status: 'debug', message: 'import failed - '+err.message});
}
break;
case 'add-callback':
try {
self.importScripts(msg.url);
var cb = self[msg.cbName || 'main'];
if (!cb) {
error = {
message: (msg.cbName || 'main') + ' was not found in ' + msg.url
};
break;
}
self.postMessage = (function(origPostMessage) {
return function(msg, transfers) {
if (cb(msg) !== false) {
/*stupid IE can't handle undefined/null transfers argument*/
if (transfers) {
origPostMessage(msg, transfers);
} else {
origPostMessage(msg);
}
}
};
})(self.postMessage);
success = true;
} catch (err) {
error = err;
}
break;
}
if (success) {
var pbMsg = {
msgId: msg.msgId,
success: true,
action: msg.action,
actionUrl: msg.url
};
if (msg.action == 'add-callback') {
pbMsg.cbName = (msg.cbName || 'main');
}
postMessage(pbMsg);
} else if (error) {
postMessage({
status: 'error',
msgId: msg.msgId,
message: error.message,
action: msg.action
});
}
}
}
if (!self.__mutable) {
self.addEventListener('message', actionHandler, false);
}
self.__mutable = true;
})(self);
|
/**
* @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 sqrtUint32 = require( './../lib' );
var v;
var i;
for ( i = 0; i < 101; i++ ) {
v = sqrtUint32( i );
console.log( 'sqrt(%d) ≈ %d', i, v );
}
|
sap.ui.define(['sap/ui/webc/common/thirdparty/base/asset-registries/Icons'], function (Icons) { 'use strict';
const name = "circle-task-2";
const pathData = "M256 1q53 0 99.5 20T437 76t55 81 20 99-20 99.5-55 81.5-81.5 55-99.5 20q-52 0-98.5-20T76 437t-55-81.5T1 256t20-99 55-81 81.5-55T256 1z";
const ltr = false;
const collection = "SAP-icons-v5";
const packageName = "@ui5/webcomponents-icons";
Icons.registerIcon(name, { pathData, ltr, collection, packageName });
var pathDataV4 = { pathData };
return pathDataV4;
});
|
var mongoose = require('mongoose');
var config = global.thisapp.config;
var logger = global.thisapp.logger;
require('./user');
require('./menu');
require('./user_menu');
require('./access_path');
require('./user_access_path');
require('./role');
require('./user_role');
require('./role_access_path');
require('./role_menu');
require('./business');
exports.User = mongoose.model('User');
exports.Menu = mongoose.model('Menu');
exports.UserMenu = mongoose.model('UserMenu');
exports.AccessPath = mongoose.model('AccessPath');
exports.UserAccessPath = mongoose.model('UserAccessPath');
exports.Role = mongoose.model('Role');
exports.UserRole = mongoose.model('UserRole');
exports.RoleAccessPath = mongoose.model('RoleAccessPath');
exports.RoleMenu = mongoose.model('RoleMenu');
exports.Business = mongoose.model('Business');
|
var _files = [];
var plugins = require("./src/plugins.js")
for (var i in plugins) {
if (plugins[i].pagesList) {
for (var j in plugins[i].pagesList) {
_files.push(j);
}
}
}
console.log(_files)
|
/*
* Copyright 2015 Andrew Romanenco
* www.romanenco.com
* andrew@romanenco.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.
*/
QUnit.module( "Tokinizer" );
QUnit.test( "good token", function( assert ) {
var token = new Token('+', 10, 99);
assert.ok(token);
assert.strictEqual(token.value(), '+');
assert.strictEqual(token.line(), 10);
assert.strictEqual(token.position(), 99);
});
QUnit.test( "good token with no line and pos", function( assert ) {
var token = new Token('+');
assert.ok(token);
assert.strictEqual(token.value(), '+');
assert.strictEqual(token.line(), -1);
assert.strictEqual(token.position(), -1);
});
QUnit.test( "bad empty token", function( assert ) {
raises(function() {
new Token();
}, {name:'Error' , message: 'Token must be a string'});
});
QUnit.test( "bad empty token", function( assert ) {
raises(function() {
new Token(99);
}, {name:'Error' , message: 'Token must be a string'});
});
QUnit.test( "token equals to self", function( assert ) {
var token = new Token('+');
assert.strictEqual(token.equals(token), true);
});
QUnit.test( "token equals", function( assert ) {
var token1 = new Token('+');
var token2 = new Token('+');
assert.strictEqual(token1.equals(token2), true);
});
QUnit.test( "token not equals to token", function( assert ) {
var token1 = new Token('+');
var token2 = new Token('-');
assert.strictEqual(token1.equals(token2), false);
});
QUnit.test( "token not equals to non-token", function( assert ) {
var token1 = new Token('+');
var token2 = "abc";
assert.strictEqual(token1.equals(token2), false);
});
QUnit.test( "valid source", function( assert ) {
var tokenizer = new Tokenizer();
var tokens = tokenizer.tokenize('><+-.,[]');
assert.strictEqual(tokens.length, 8);
assert.ok(tokens[0].value() === '>');
assert.ok(tokens[1].value() === '<');
assert.ok(tokens[2].value() === '+');
assert.ok(tokens[3].value() === '-');
assert.ok(tokens[4].value() === '.');
assert.ok(tokens[5].value() === ',');
assert.ok(tokens[6].value() === '[');
assert.ok(tokens[7].value() === ']');
});
QUnit.test( "valid source with whitespaces", function( assert ) {
var tokenizer = new Tokenizer();
var tokens = tokenizer.tokenize("> <\t+-IGNORED\r\n.,\n[]");
assert.strictEqual(tokens.length, 8);
assert.ok(tokens[0].value() === '>');
assert.ok(tokens[1].value() === '<');
assert.ok(tokens[2].value() === '+');
assert.ok(tokens[3].value() === '-');
assert.ok(tokens[4].value() === '.');
assert.ok(tokens[5].value() === ',');
assert.ok(tokens[6].value() === '[');
assert.ok(tokens[7].value() === ']');
});
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var multer = require('multer');
var session = require('express-session');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.use(multer({dest: './public/img/portfolio/'}));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
app.use(falsh());
app.locals.moment = require('moment');
app.use(function(req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
// express validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
(function (angular) {
'use strict';
//// JavaScript Code ////
function tagsFilterCtrl($scope, $rootScope, Constants, $location, $log) {
/*jshint validthis:true */
var vm = this;
vm.maxTags = 10;
vm.filterMode = $location.search().filterMode || '||';
var unbind = $scope.$watch('vm.filterMode', function(newVal, oldVal) {
if (newVal !== oldVal) {
$log.debug('vm.filterMode: ' + vm.filterMode);
$location.search('filterMode', newVal);
$rootScope.$emit(Constants.EVENTS.TAGS_CHANGED);
}
});
function setTagState(name,stateVal) {
for (var f=0; f < $scope.projectStatus.tag_info.length ; f++) {
if ($scope.projectStatus.tag_info[f].immutable.name === name) {
$scope.projectStatus.tag_info[f].state = stateVal;
}
}
}
vm.initTagsFromQueryString = function() {
var queryStringObject = $location.search();
var shouldRefresh = false;
for (var j=0; j < $scope.projectStatus.tag_info.length ; j++) {
$scope.projectStatus.tag_info[j].state = 0;
}
if (angular.isDefined(queryStringObject.tagsOn)) {
shouldRefresh = true;
var array = queryStringObject.tagsOn.split(',');
for (var i=0; i < array.length; i++) {
setTagState(array[i],1);
}
}
return shouldRefresh;
};
vm.initTagsFromQueryString();
vm.updateTags = function() {
var on = [];
for (var i=0; i < $scope.projectStatus.tag_info.length ; i++) {
if ($scope.projectStatus.tag_info[i].state === 1) {
on.push($scope.projectStatus.tag_info[i].immutable.name);
}
}
if (on.length > 0) {
$location.search('tagsOn', on.join(','));
} else {
$location.search('tagsOn', undefined);
}
$rootScope.$emit(Constants.EVENTS.TAGS_CHANGED);
};
vm.hasSelectedTags = function() {
for (var i=0; i < $scope.projectStatus.tag_info.length ; i++) {
if ($scope.projectStatus.tag_info[i].state === 1) {
return true;
}
}
return false;
};
vm.clearSelectedTags = function() {
for (var i=0; i < $scope.projectStatus.tag_info.length ; i++) {
$scope.projectStatus.tag_info[i].state = 0;
}
vm.updateTags();
};
$scope.$on('$destroy', unbind);
}
//// Angular Code ////
angular.module('codeine').controller('tagsFilterCtrl', tagsFilterCtrl);
})(angular);
|
/*
Copyright 2016 IBM Corporation
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.
*/
const path = require("path");
const fs = require("fs");
const utils = require("wchtools-api").getUtils();
const rimraf = require("rimraf");
const loadPath = path.dirname(__filename);
const cDir = path.normalize(loadPath + path.sep + '../commands');
const homeDir = utils.getUserHome();
try {
console.log('quote:' + cDir + '/quote.js');
if (fs.existsSync( cDir + '/quote.js')) {
fs.unlinkSync(cDir + '/quote.js');
}
rimraf.sync(homeDir + path.sep + utils.ProductName);
} catch (e) {
// Ignore and keep going.
}
|
(function() {
'use strict';
angular.module('akkabot-ui').controller(
'MessageCountController',
[
'$scope',
'messageCountFactory',
function($scope, messageCountFactory) {
$scope.options = {
chart: {
type: 'historicalBarChart',
height: 450,
margin: {
top: 20,
right: 20,
bottom: 65,
left: 50
},
x: function(d) {
return d[0];
},
y: function(d) {
return d[1];
},
showValues: true,
valueFormat: function(d) {
return d3.format(',.1f')(d);
},
duration: 100,
xAxis: {
axisLabel: 'Date and time',
tickFormat: function(d) {
return d3.time.format('%x')(new Date(d * 1000))
},
rotateLabels: 30,
showMaxMin: false
},
yAxis: {
axisLabel: 'Message count',
axisLabelDistance: -10,
tickFormat: function(d) {
return d3.format(',.1f')(d);
}
},
tooltip: {
keyFormatter: function(d) {
return d3.time.format('%H:%M')(new Date(d * 1000));
}
},
zoom: {
enabled: true,
scaleExtent: [1, 10],
useFixedDomain: false,
useNiceScale: false,
horizontalOff: false,
verticalOff: true,
unzoomEventType: 'dblclick.zoom'
}
}
};
}]);
})();
|
/*
This helper modules allows us to create different type of errors we can throw
*/
function customError(message, errorName)
{
this.name = errorName || "Error";
this.message = message;
var stackParts = new Error().stack.split("\n");
stackParts.splice(0,2);
stackParts.unshift(this.name + ": " + message);
this.stack = stackParts.join("\n");
}
customError.prototype = Error.prototype;
module.exports = customError;
|
/**
* @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';
// MODULES //
var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var abs = require( '@stdlib/math/base/special/abs' );
var EPSILON = require( '@stdlib/constants/float64/eps' );
var incrmgmean = require( './../lib' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.equal( typeof incrmgmean, 'function', 'main export is a function' );
t.end();
});
tape( 'the function throws an error if not provided a positive integer', function test( t ) {
var values;
var i;
values = [
'5',
-5.0,
0.0,
3.14,
true,
null,
void 0,
NaN,
[],
{},
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
incrmgmean( value );
};
}
});
tape( 'the function returns an accumulator function', function test( t ) {
t.equal( typeof incrmgmean( 3 ), 'function', 'returns a function' );
t.end();
});
tape( 'the accumulator function computes a moving geometric mean incrementally', function test( t ) {
var expected;
var actual;
var delta;
var data;
var tol;
var acc;
var N;
var i;
data = [ 2.0, 3.0, 2.0, 4.0, 3.0, 4.0 ];
N = data.length;
acc = incrmgmean( 3 );
actual = [];
for ( i = 0; i < N; i++ ) {
actual.push( acc( data[ i ] ) );
}
// Note: computed by hand using textbook formula:
expected = [
2.0,
2.449489742783178,
2.2894284851066637,
2.8844991406148166,
2.8844991406148166,
3.634241185664279
];
for ( i = 0; i < N; i++ ) {
if ( actual[ i ] === expected[ i ] ) {
t.equal( actual[ i ], expected[ i ], 'returns expected value' );
} else {
delta = abs( expected[ i ] - actual[ i ] );
tol = 1.2 * EPSILON * abs( expected[ i ] );
t.equal( delta <= tol, true, 'within tolerance. Expected: '+expected[ i ]+'. Actual: '+actual[ i ]+'. Delta: '+delta+'. Tol: '+tol+'.' );
}
}
t.end();
});
tape( 'if not provided an input value, the accumulator function returns the current geometric mean', function test( t ) {
var expected;
var actual;
var delta;
var data;
var acc;
var tol;
var i;
data = [ 2.0, 3.0, 5.0 ];
acc = incrmgmean( 2 );
for ( i = 0; i < data.length; i++ ) {
acc( data[ i ] );
}
actual = acc();
expected = 3.872983346207417; // Note: computed by hand using textbook formula
delta = abs( expected - actual );
tol = 1.0 * EPSILON * abs( expected );
t.equal( delta <= tol, true, 'within tolerance. Expected: '+expected+'. Actual: '+actual+'. Delta: '+delta+'. Tol: '+tol+'.' );
t.end();
});
tape( 'if data has yet to be provided, the accumulator function returns `null`', function test( t ) {
var acc = incrmgmean( 3 );
t.equal( acc(), null, 'returns null' );
t.end();
});
tape( 'if provided `NaN`, the accumulated value is `NaN` for at least `W` invocations', function test( t ) {
var expected;
var delta;
var data;
var acc;
var tol;
var v;
var i;
acc = incrmgmean( 3 );
data = [
NaN, // NaN
3.14, // NaN, 3.14
3.14, // NaN, 3.14, 3.14
NaN, // 3.14, 3.14, NaN
3.14, // 3.14, NaN, 3.14
3.14, // NaN, 3.14, 3.14
3.14, // 3.14, 3.14, 3.14
NaN, // 3.14, 3.14, NaN
3.14, // 3.14, NaN, 3.14
3.14, // NaN, 3.14, 3.14
3.14, // 3.14, 3.14, 3.14
NaN, // 3.14, 3.14, NaN
3.14, // 3.14, NaN, 3.14
3.14, // NaN, 3.14, 3.14
NaN, // 3.14, 3.14, NaN
NaN, // 3.14, NaN, NaN
NaN, // NaN, NaN, NaN
NaN, // NaN, NaN, NaN
3.14 // NaN, NaN, 3.14
];
expected = [
NaN,
NaN,
NaN,
NaN,
NaN,
NaN,
3.14,
NaN,
NaN,
NaN,
3.14,
NaN,
NaN,
NaN,
NaN,
NaN,
NaN,
NaN,
NaN
];
for ( i = 0; i < data.length; i++ ) {
v = acc( data[ i ] );
if ( isnan( expected[ i ] ) ) {
t.equal( isnan( v ), true, 'returns expected value for window '+i );
} else if ( v === expected[ i ] ) {
t.equal( v, expected[ i ], 'returns expected value for window '+i );
} else {
delta = abs( expected[ i ] - v );
tol = 1.0 * EPSILON * abs( expected[ i ] );
t.equal( delta <= tol, true, 'within tolerance for window '+i+'. Expected: '+expected[ i ]+'. Actual: '+v+'. Delta: '+delta+'. Tol: '+tol+'.' );
}
}
t.end();
});
|
import {LinkItem} from '../../../src/common/iServer/LinkItem';
describe('LinkItem', () => {
it('constructor, destroy', () => {
var options = {
foreignKeys: ["test1", "test2"],
foreignTable: "test",
linkFields: ["test1", "test2"],
linkFilter: "test",
name: "test",
primaryKeys: ["test1", "test2"]
};
var linkItem = new LinkItem(options);
expect(linkItem.foreignKeys.length).toBe(2);
expect(linkItem.foreignTable).toBe("test");
expect(linkItem.linkFields.length).toBe(2);
expect(linkItem.linkFilter).toBe("test");
expect(linkItem.name).toBe("test");
expect(linkItem.primaryKeys.length).toBe(2);
linkItem.destroy();
expect(linkItem.foreignKeys).toBeNull();
expect(linkItem.foreignTable).toBeNull();
expect(linkItem.linkFields).toBeNull();
expect(linkItem.linkFilter).toBeNull();
expect(linkItem.name).toBeNull();
expect(linkItem.primaryKeys).toBeNull();
})
});
|
/* Setup file run before spec files to setup the context (and RequireJS
* specifically) to execute the spec file.
*
* Defined by caller:
* - Jasmine predefines
* - require (Node require)
* - __dirname, __filename
* - baseUrl (Relative path to the directory containing this file)
* - csPath (Path to require-cs module)
*
* See requirejs-runner source for full invocation details.
*/
var define,
requirejsOrig = require('requirejs'),
ostring = Object.prototype.toString,
path = require('path'),
isArray = function(it){
return ostring.call(it) === '[object Array]';
},
isFunction = function(it){
return ostring.call(it) === '[object Function]';
},
requirejs = function(deps, callback){
var retVal;
if(!isArray(deps) && typeof deps !== 'string'){
if(isArray(callback)){
retVal = requirejsOrig(deps, callback, arguments[2]);
} else {
retVal = requirejsOrig(deps, [], callback);
}
} else {
retVal = requirejsOrig(deps, callback);
}
return retVal;
};
requirejsOrig.config({
baseUrl: 'app/js/',
nodeRequire: require,
paths: {
cs: csPath
}
});
for(var key in requirejsOrig) {
requirejs[key] = requirejsOrig[key];
}
requirejs.config = function(config){
var alteredConfig = {};
for(var key in config) {
alteredConfig[key] = config[key];
}
if(alteredConfig.baseUrl){
var base = baseUrl.replace(/\\/g, '/'),
splitUrl = alteredConfig.baseUrl.replace(/\\/g, '/').split('/'),
index = 0;
for(; index < splitUrl.length; index++){
if(splitUrl[index] === '..'){
base = path.dirname(base);
} else {
base += '/' + splitUrl[index];
}
}
alteredConfig.baseUrl = base;
}
return requirejsOrig.config(alteredConfig);
};
require = requirejs;
define = requirejs.define;
|
/*
* Copyright 2015 Open Networking Laboratory
*
* 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.
*
*/
/*
ONOS GUI -- Topology Traffic Module.
Defines behavior for viewing different traffic modes.
Installed as a Topology Overlay.
*/
(function () {
'use strict';
// injected refs
var $log;
// traffic overlay definition
var overlay = {
overlayId: 'traffic',
glyph: { id: 'allTraffic' },
tooltip: 'Traffic Overlay',
activate: activateTraffic,
deactivate: deactivateTraffic
};
// === implementation of overlay API (essentially callbacks)
function activateTraffic() {
$log.debug("Topology traffic overlay ACTIVATED");
}
function deactivateTraffic() {
$log.debug("Topology traffic overlay DEACTIVATED");
}
// invoke code to register with the overlay service
angular.module('ovTopo')
.run(['$log', 'TopoOverlayService',
function (_$log_, tov) {
$log = _$log_;
tov.register(overlay);
}]);
}());
|
/*
* This file is part of SIMPL4(http://simpl4.org).
*
* Copyright [2017] [Manfred Sattler] <manfred@ms123.org>
*
* 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.
*/
/*
*/
qx.Class.define("ms123.graphicaleditor.plugins.Split", {
extend: qx.core.Object,
/******************************************************************************
CONSTRUCTOR
******************************************************************************/
construct: function (facade) {
this.base(arguments);
this.facade = facade;
this._propertyPanelVisible = true;
this.facade.offer({
name: "graphicaleditor.togglePropertyPanel",
description: "",
icon: this.__getResourceUrl("view.png"),
keyCodes: [{
metaKeys: [ms123.oryx.Config.META_KEY_META_CTRL],
keyCode: 65,
keyAction: ms123.oryx.Config.KEY_ACTION_DOWN
}],
functionality: this.togglePropertyPanel.bind(this),
group: "zzGroup",
isEnabled: qx.lang.Function.bind(function () {
return true
}, this),
index: 2
});
/*this.facade.offer({
name: this.tr("ge.Split.toggleShapeMenu"),
description: this.tr("ge.Split.toggleShapeMenuDesc"),
icon: this.__getResourceUrl("arrow_redo.png"),
keyCodes: [{
metaKeys: [ms123.oryx.Config.META_KEY_META_CTRL],
keyCode: 83,
keyAction: ms123.oryx.Config.KEY_ACTION_DOWN
}],
functionality: this.toggleShapeMenu.bind(this),
group: "zzGroup",
isEnabled: qx.lang.Function.bind(function () {
return true
}, this),
index: 0
});*/
},
/******************************************************************************
PROPERTIES
******************************************************************************/
properties: {},
/******************************************************************************
STATICS
******************************************************************************/
statics: {},
/******************************************************************************
MEMBERS
******************************************************************************/
members: {
/**
*
*/
togglePropertyPanel: function () {
if( this._propertyPanelVisible ){
this.facade.container.dialogPanel.exclude();
this._propertyPanelVisible = false;
}else{
this.facade.container.dialogPanel.show();
this._propertyPanelVisible = true;
}
},
/**
*
*/
toggleShapeMenu: function () {
},
__getResourceUrl: function (name) {
var am = qx.util.AliasManager.getInstance();
return am.resolve("resource/ms123/" + name);
}
},
/******************************************************************************
DESTRUCTOR
******************************************************************************/
destruct: function () {}
});
|
"use strict"
const helper = require("../../helper.js");
let utils = helper.requireModule('./utilities/utils.js');
describe("Testing utilities", () => {
let res = {
status: () => {
return {
send: (input2) => {
return input2;
}
};
},
jsonp: () => {
return 2;
}
};
let req = {
soajs: {
log: {
error: (input) => {
// console.error(input);
}
},
buildResponse: (input) => {
return input;
},
controllerResponse: (input) => {
return input;
}
}
};
it("logErrors - number error", (done) => {
utils.logErrors(123, req, res, (error) => {
done();
});
});
it("logErrors - object, no code no message", (done) => {
utils.logErrors({}, req, res, (error) => {
done();
});
});
it("logErrors - string error", (done) => {
utils.logErrors("error", req, res, (error) => {
done();
});
});
it("controllerClientErrorHandler - request without xhr", (done) => {
utils.controllerClientErrorHandler(null, req, res, () => {
done();
});
});
it("controllerClientErrorHandler - request xhr", (done) => {
req.xhr = {};
utils.controllerClientErrorHandler(null, req, res, () => {
done();
});
});
it("controllerErrorHandler - number error", (done) => {
req.xhr = {};
utils.controllerErrorHandler(150, req, res, null);
done();
});
it("controllerErrorHandler - with error", (done) => {
utils.controllerErrorHandler({"code": 200, "msg": "dummy200"}, req, res, null);
done();
});
});
|
/**
* (c) Copyright 2016 Hewlett Packard Enterprise Development Company LP
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use self 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.
*/
(function() {
'use strict';
angular
.module('horizon.app.core.instances.actions')
.factory('horizon.app.core.instances.actions.pause.service', factory);
factory.$inject = [
'horizon.app.core.openstack-service-api.nova',
'horizon.app.core.instances.actions.generic-simple.service',
'horizon.app.core.instances.instance-status.service'
];
/**
* @ngDoc factory
* @name horizon.app.core.instances.actions.pause.service
*
* @Description
* Pauses the instance
*/
function factory(nova, simpleService, statusService) {
var config = {
rules: [['compute', 'compute_extension:admin_actions:pause']],
execute: execute,
validState: validState
};
return simpleService(config);
function execute(instance) {
return nova.pauseServer(instance.id);
}
function validState(instance) {
// TODO: Original Python code describes extension-supported: AdminActions
return statusService.anyStatus(instance, ['ACTIVE']) &&
!statusService.isDeleting(instance);
}
}
})();
|
// FoodChain audio stuff
// Basic HTML 5 Audio Element encapsulation
enyo.kind({
name: "HTML5.Audio",
kind: enyo.Control,
tag: "audio",
published: {
src: "", crossorigin: "", preload: "auto",
mediagroup: "", loop: false, muted: "", controlsbar: false
},
events: {
onSoundEnded: "",
onSoundTimeupdate: ""
},
// Constructor
create: function() {
this.inherited(arguments);
this.isCordova = (enyo.platform.android || enyo.platform.androidChrome || enyo.platform.ios) && document.location.protocol.substr(0,4) != "http";
this.startPlay = false;
this.srcChanged();
this.crossoriginChanged();
this.preloadChanged();
this.loopChanged();
this.mutedChanged();
this.controlsbarChanged();
this.handleVolumeButtons();
},
// Handle volume buttons on Android
handleVolumeButtons: function() {
if (this.isCordova && !enyo.platform.iOS) {
// HACK: Need only on Android because Cordova intercept volume buttons
var emptyf = function() {};
document.addEventListener("volumeupbutton", function() {
cordova.plugins.VolumeControl.getVolume(function(value) {
var volume = parseInt(value);
if (volume < 100) {
cordova.plugins.VolumeControl.setVolume((volume+10), emptyf, emptyf);
}
}, emptyf);
}, false);
document.addEventListener("volumedownbutton", function() {
cordova.plugins.VolumeControl.getVolume(function(value) {
var volume = parseInt(value);
if (volume > 0) {
cordova.plugins.VolumeControl.setVolume((volume-1), emptyf, emptyf);
}
}, emptyf);
}, false);
}
},
// Render
rendered: function() {
this.inherited(arguments);
// Handle init
if (this.hasNode()) {
// Handle sound ended event
var audio = this;
enyo.dispatcher.listen(audio.hasNode(), "ended", function() {
audio.doSoundEnded();
});
enyo.dispatcher.listen(audio.hasNode(), "timeupdate", function(s) {
audio.doSoundTimeupdate({timeStamp: s.timeStamp});
});
}
},
// Property changed
srcChanged: function() {
this.setAttribute("src", this.src);
},
crossoriginChanged: function() {
this.setAttribute("crossorigin", this.crossorigin);
},
preloadChanged: function() {
this.setAttribute("preload", this.preload);
},
loopChanged: function() {
this.setAttribute("loop", this.loop);
},
mutedChanged: function() {
if (this.muted.length != 0)
this.setAttribute("muted", this.muted);
},
controlsbarChanged: function() {
this.setAttribute("controls", this.controlsbar);
},
// Test if component could play a file type
canPlayType: function(typename) {
var node = this.hasNode();
if (!node)
return false;
return node.canPlayType(typename);
},
// Play audio
play: function() {
// HACK: HTML5 Audio don't work in PhoneGap on Android < 4.4 and iOS, use Media PhoneGap component instead
if (this.isCordova) {
// Compute full path
var src = location.pathname.substring(0,1+location.pathname.lastIndexOf('/'))+this.src;
var that = this;
if (this.media) {
this.media.src = "";
this.media.pause();
this.media.release();
}
// Create the Media object
this.media = new Media(src, function() { }, function() { },
function(status) {
if (status == 4 && this.src != "") {
that.doSoundEnded();
}
}
);
// Play
this.media.play();
return;
}
var node = this.hasNode();
if (!node)
return;
this.started = false;
var promise = node.play();
if (promise) {
var that = this;
promise.then(function() {
that.started = true;
}).catch(function() {});
} else {
this.started = true;
}
},
// Pause audio
pause: function() {
// HACK: HTML5 Audio don't work in PhoneGap on Android and iOS, use Media PhoneGap component instead
if (this.isCordova) {
if (!this.media)
return;
this.media.src = "";
this.media.pause();
this.media.release();
return;
}
var node = this.hasNode();
if (!node)
return;
if (this.started) {
node.pause();
}
},
// Test if audio is paused
paused: function() {
var node = this.hasNode();
if (!node)
return false;
return node.paused;
},
// Test if audio is ended
ended: function() {
var node = this.hasNode();
if (!node)
return false;
return node.ended;
}
});
// FoodChain Audio engine
enyo.kind({
name: "FoodChain.Audio",
kind: enyo.Control,
components: [
{ name: "sound", kind: "HTML5.Audio", preload: "auto", autobuffer: true, controlsbar: false,
onSoundEnded: "broadcastEnd" }
],
// Constructor
create: function() {
this.inherited(arguments);
this.format = null;
},
// First render, test sound format supported
rendered: function() {
this.inherited(arguments);
this.format = ".mp3";
},
// Play a sound
play: function(sound) {
if (this.format == null)
return;
this.$.sound.setSrc(sound+this.format);
this.$.sound.play();
},
// Pause
pause: function() {
if (this.format == null)
return;
this.$.sound.pause();
},
// End of sound detected, broadcast the signal
broadcastEnd: function() {
enyo.Signals.send("onEndOfSound", {sound:this.$.sound.src.substring(0,this.$.sound.src.length-4)});
}
});
|
import t from 'tcomb-form'
import Dublincore from 'common/schemas/Dublincore'
import FVCore from 'common/schemas/FVCore'
import FVMedia from 'common/schemas/FVMedia'
// Very basic email validation
const Email = t.subtype(t.String, (email) => {
const reg =
/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
return reg.test(email)
})
const fields = {
FVWord: Object.assign({}, Dublincore, FVCore, {
'fv-word:categories': t.list(t.String),
'fv-word:pronunciation': t.maybe(t.String),
'fv-word:related_phrases': t.list(t.String),
'fv-word:part_of_speech': t.maybe(t.String),
'fv-word:available_in_games': t.Boolean,
'fv-word:acknowledgement': t.maybe(t.String),
'fv:related_audio': t.list(t.maybe(t.String)),
'fv:general_note': t.maybe(t.String),
'fv:related_assets': t.list(t.maybe(t.String)),
'fv:related_pictures': t.list(t.maybe(t.String)),
'fv:related_videos': t.list(t.maybe(t.String)),
}),
FVPhrase: Object.assign({}, Dublincore, FVCore, {
'fv:literal_translation': t.maybe(t.String),
'fv-phrase:phrase_books': t.list(t.String),
'fv-phrase:acknowledgement': t.maybe(t.String),
'fv:general_note': t.maybe(t.String),
'fv:related_audio': t.list(t.maybe(t.String)),
'fv:related_pictures': t.list(t.maybe(t.String)),
'fv:related_videos': t.list(t.maybe(t.String)),
}),
FVAudio: Object.assign({}, Dublincore, FVMedia),
FVPicture: Object.assign({}, Dublincore, FVMedia),
FVVideo: Object.assign({}, Dublincore, FVMedia),
FVBook: Object.assign({}, Dublincore, FVCore, {
'fv:definitions': t.maybe(t.String),
'fv:literal_translation': t.maybe(t.String),
'fvbook:title_literal_translation': t.list(
t.struct({
translation: t.String,
language: t.String,
})
),
'fvbook:introduction': t.maybe(t.String),
'fvbook:introduction_literal_translation': t.maybe(
t.list(
t.struct({
translation: t.String,
language: t.String,
})
)
),
'fvbook:author': t.list(t.String),
'fvbook:type': t.String,
'fv:related_audio': t.list(t.maybe(t.String)),
'fv:related_pictures': t.list(t.maybe(t.String)),
'fv:related_videos': t.list(t.maybe(t.String)),
}),
FVBookEntry: Object.assign({}, Dublincore, FVCore, {
'fv:definitions': t.maybe(t.String),
'fv:available_in_childrens_archive': t.maybe(t.String),
'fv:literal_translation': t.maybe(
t.list(
t.struct({
translation: t.String,
language: t.String,
})
)
),
'fvbookentry:dominant_language_text': t.list(
t.struct({
translation: t.String,
language: t.String,
})
),
'fv:related_audio': t.list(t.maybe(t.String)),
'fv:related_pictures': t.list(t.maybe(t.String)),
'fv:related_videos': t.list(t.maybe(t.String)),
}),
FVGallery: Object.assign({}, Dublincore, {
'fv:related_pictures': t.list(t.String),
}),
FVPhraseBook: Object.assign({}, Dublincore, {
'fvcategory:image': t.maybe(t.String),
}),
FVCategory: Object.assign({}, Dublincore, {
'fvcategory:parent_category': t.maybe(t.String),
'fvcategory:image': t.maybe(t.String),
}),
FVContributor: Object.assign({}, Dublincore),
FVDialect: {
'fvdialect:greeting': t.String,
'fvdialect:featured_audio': t.maybe(t.String),
'fvdialect:about_us': t.maybe(t.String),
'fvdialect:news': t.maybe(t.String),
'fvdialect:background_top_image': t.String,
'fvdialect:logo': t.String,
'fvdialect:featured_words': t.list(t.String),
'fvdialect:related_links': t.list(t.String),
'fvdialect:about_our_language': t.maybe(t.String),
'fvdialect:country': t.maybe(t.String),
'fvdialect:dominant_language': t.maybe(t.String),
'fvdialect:region': t.maybe(t.String),
'fvdialect:keyboards': t.list(t.String),
'fvdialect:language_resources': t.list(t.String),
'fvdialect:contact_information': t.String,
},
FVCharacter: Object.assign(
{},
{
'dc:title': t.String,
'fvcharacter:upper_case_character': t.maybe(t.String),
'fvcharacter:alphabet_order': t.maybe(t.Number),
'fvcharacter:related_words': t.list(t.String),
'fv:related_audio': t.list(t.maybe(t.String)),
'fv:related_videos': t.list(t.String),
}
),
FVRegistration: {
'fvuserinfo:traditionalName': t.maybe(t.String),
'userinfo:firstName': t.String,
'userinfo:lastName': t.String,
'userinfo:email': Email,
},
FVJoin: {
siteId: t.String,
interestReason: t.String,
comment: t.String,
communityMember: t.maybe(t.Boolean),
languageTeam: t.maybe(t.Boolean),
},
FVLink: Object.assign({}, Dublincore, {
'dc:description': t.maybe(t.String),
'fvlink:url': t.maybe(t.String),
}),
FVLabel: Object.assign(
{},
{
'fv:related_audio': t.list(t.maybe(t.String)),
}
),
}
export default fields
// Sample usage with tcomb
// const FVPortal = t.struct(selectn('FVPortal', fields));
|
function process_inline_macro_extension(obj) {
var attrs = obj["attrs"];
var parent = obj["parent"];
var self = obj["self"];
var nil = obj["nil"];
var name = obj["name"];
var target = obj["target"];
var title = (attrs.title),
alt = (attrs.alt),
caption = (attrs.caption),
width = (attrs.width),
height = (attrs.height),
scale = (attrs.scale),
align = (attrs.align),
type = (attrs.type),
cache = (attrs.cache),
role = (attrs.role),
link = (attrs.link),
float = (attrs.float),
imagesdir = parent.$document().$attr('imagesdir', '');
var filename = "";
//if (!attrs['$[]']("file")["$nil?"]()) {
// var extension = attrs['$[]']("extension")["$nil?"]() ? "" : "." + attrs['$[]']("extension");
// filename = "" + attrs['$[]']("file") + extension;
//}
var parts = target.split(",");
if (parts.length > 1) {
var extension = parts.length > 2 ? "." + parts[2] : "";
filename = "" + parts[1] + extension;
}
var normalName = name.toLowerCase();
var content = "" + parts[0];
var command = normalName;
if (filename != "") {
target = parent.$image_uri(filename);
} else {
target = cachedImageUri(content);
var host = ((typeof location) != "undefined") ? "http://" + location.host : "";
filename = host + target;
}
var stems = getMathExtensionNames();
if (stems.indexOf(name) != -1) {
content = parseStems(parent, content, name);
command = "math";
}
var parameters = [content, type, imagesdir, target, normalName].map(function (e) {
return e + "";
});
//afx[command].apply(afx,parameters);
postMessage(JSON.stringify({
type: "afx",
func: command,
parameters: parameters
}));
var attributes = {
"target": filename,
"title": title,
"alt": alt,
"caption": caption,
"width": width,
"height": height,
"scale": scale,
"align": align,
"role": role,
"link": link,
"float": float
};
var keys = Object.keys(attributes);
keys.forEach(function (key) {
if (attributes[key] == null) {
delete attributes[key];
}
});
attributes.alt = attributes.alt || "alt";
delete attributes.target;
return self.createInline(parent, "image", "", {target: filename, attributes: attributes});
}
function registerInlineMacroExtensions(name) {
asciidoctor.Extensions.register(function () {
this.inlineMacro(name, function () {
let self = this;
self.$match_format('short');
self.$name_positional_attributes("target", "file", "extension");
self.process(function (parent, target, attrs) {
return process_inline_macro_extension({
parent: parent,
attrs: attrs,
self: self,
nil: Opal.nil,
name: name,
target: target
});
});
});
});
}
// there is a bug for math asciimath:[] generates text + image ascii<img>
getMathExtensionNames()
.forEach(function (name) {
registerInlineMacroExtensions(name);
});
|
/*
* ../../../..//extensions/a11y/mathmaps/es/units/speed.js
*
* Copyright (c) 2009-2018 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 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.
*/
[
{ locale: "es" },
{ key: "kt", names: ["kt", "kt."], mappings: { default: { default: "nudo" } } },
{ key: "mph", names: ["mph"], mappings: { default: { default: "millas por hora" } } },
{ key: "rpm", names: ["rpm"], mappings: { default: { default: "revoluciones por minuto" } } },
{ key: "kmh", names: ["kmh"], mappings: { default: { default: "kilómetros por hora" } } }
];
|
/**
* @license Apache-2.0
*
* Copyright (c) 2021 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 tape = require( 'tape' );
var isMobile = require( './../lib/main.js' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.equal( typeof isMobile, 'function', 'main export is a function' );
t.end();
});
tape( 'the function returns `false`', function test( t ) {
t.strictEqual( isMobile(), false, 'returns false' );
t.end();
});
|
$(document).ready(function() {
// Any plugin buttons using pwg-icon class should also use glyphicon class for correct display
//$('.pwg-icon').addClass('glyphicon');
// Grid view button click
$('#btn-grid').click(function() {
if ($(this).hasClass('active')) {
return;
}
$.cookie('view', 'grid');
$('#btn-grid').addClass('active');
$('#btn-list').removeClass('active');
$('#content')
.removeClass('content-list')
.addClass('content-grid')
.height('auto')
.find('.col-outer').each(function() {
$(this).removeClass('col-lg-12 col-md-12 col-sm-12 col-xs-12')
.addClass($(this).data('grid-classes'))
.one(
'webkitTransitionEnd',
function () {
$('#content').find('.col-inner').equalHeights();
})
})
.find('.col-inner')
.height('auto');
});
// List view button click
$('#btn-list').click(function() {
if ($(this).hasClass('active')) {
return;
}
$.cookie('view', 'list');
$('#btn-list').addClass('active');
$('#btn-grid').removeClass('active');
$('#content')
.removeClass('content-grid')
.addClass('content-list')
.height('auto')
.find('.col-outer').each(function() {
$(this).removeClass($(this).data('grid-classes'))
.addClass('col-lg-12 col-md-12 col-sm-12 col-xs-12')
.one(
'webkitTransitionEnd',
function () {
$('#content').find('.col-inner').equalHeights();
})
})
.find('.col-inner')
.height('auto');
});
// Side bar
var sidebar = $("#sidebar");
var theImage = $('#theImage')
if (sidebar.length && theImage.length) {
$('#info-link').click(function () {
var sidebar = $('#sidebar');
if (parseInt(sidebar.css('right')) < 0) {
sidebar.animate({right: "+=250"}, 500);
} else {
sidebar.animate({right: "-=250"}, 500);
}
return false;
});
}
});
function bd_popup(url) {
window.open(url, 'bd_popup', 'alwaysRaised=yes,dependent=yes,toolbar=no,height=420,width=500,menubar=no,resizable=yes,scrollbars=yes,status=no');
}
|
function(doc) {
var ret = new Document();
if (doc.grouping) {
ret.add(doc.grouping);
ret.add(doc.grouping, {"field":"grouping", "store":"yes"});
};
if (doc.sample) {
ret.add(doc.sample.name);
ret.add(doc.sample.description);
ret.add(doc.sample.name, {"field":"name", "store":"yes"});
ret.add(doc.sample.description, {"field":"description", "store":"yes"});
};
if (doc.sort_indices) {
ret.add(doc.sort_indices.th);
};
if (doc.sort_indices) {
ret.add(doc.sort_indices.u);
};
if (doc.measurement) {
if (doc.measurement.results) {
if (doc.measurement.results.length > 0) {
for (var i=0; i<doc.measurement.results.length; i++) {
var value = doc.measurement.results[i];
var result1 = "", result2 = "";
if (value.type == "measurement") {
if (value.value.length == 1) {
result1 = value.value[0];
} else if (value.value.length == 2) { result1 = value.value[0];
result2 = "(" + value.value[1] + ")";
} else if (value.value.length == 3) {
result1 = value.value[0];
result2 = "(" + value.value[1] + "-" + value.value[2] + ")";
}
} else if (value.type == "limit") {
if (value.value.length == 1) {
result1 = value.value[0];
} else if (value.value.length == 2) {
result1 = value.value[0];
result2 = "(" + value.value[1] + "%)";
}
} else if (value.type == "range") {
if (value.value.length == 2) {
result1 = value.value[0] + " - " + value.value[1];
} else if (value.value.length == 3) {
result1 = value.value[0] + " - " + value.value[1];
result2 = "(" + value.value[2] + "%)";
}
}
ret.add(value.isotope, {"field":"isotope", "store":"yes"});
ret.add(value.unit, {"field":"unit", "store":"yes"});
ret.add(value.type, {"field":"type", "store":"yes"});
ret.add(result1, {"field":"result1", "store":"yes"});
ret.add(result2, {"field":"result2", "store":"yes"});
}
}
}
}
//index("isotope", "", {"store":"yes"});
//index("unit", "", {"store":"yes"});
//index("type", "", {"store":"yes"});
//index("result1", "", {"store":"yes"});
//index("result2","",{"store":"yes"});
return ret;
}
|
$(function() {
////////////////////////////////////////
// Bind function to buttons //
////////////////////////////////////////
$("button[name='add']").click(add);
$("button[name='personalS']").click(getPersonalStats);
$("button[name='generalS']").click(getGeneralStats);
$("button[name='otherS']").click(getOtherStats);
$("button[name='getReq']").click(getReq);
$("button[name='sendReq']").click(sendReq);
////////////////////////////////////////
// Dropbox Authentication //
////////////////////////////////////////
var client = new Dropbox.Client({ key: "75ozb45t6z1tq24" });
if (client.isAuthenticated()) {
// Cached credentials are available, make Dropbox API calls.
console.log("Auth cached")
} else {
client.authenticate(function(error, client) {
if (error) {
return;
console.log("Auth failed")
}
});
}
////////////////////////////////////////
// Add data //
////////////////////////////////////////
function add(){
var user = $('#user').val();
var myClass = $('input[name="myClass"]:checked').val();
var theirClass = $('input[name="theirClass"]:checked').val();
var result = $('input[name="result"]:checked').val();
var id = Math.random().toString(36).substr(2,5);
var pat = /^[a-zA-Z0-9-]+$/;
if(pat.test(user)){
client.writeFile("/space/Feed/"+user+"_"+myClass+"_"+theirClass+"_"+result+"."+id, "", function(error, stat) {
if (error) {
console.log("Error uploading");
return;
}
});
}
}
////////////////////////////////////////
// Get Personal Statistics //
////////////////////////////////////////
function getPersonalStats(){
var user = $('#login').val();
var pat = /^[a-zA-Z0-9-]+$/;
if(pat.test(user)){
fetchAndUpdate("/space/Users/"+user+"/Statistics/");
}
}
////////////////////////////////////////
// Get General Statistics //
////////////////////////////////////////
function getGeneralStats(){
fetchAndUpdate("/space/General/");
}
////////////////////////////////////////
// Get friends statistics //
////////////////////////////////////////
function getOtherStats(){
var user = $("#login").val();
var other = $('#otherI').val();
var pat = /^[a-zA-Z0-9-]+$/;
if(pat.test(user)&&pat.test(other)){
// Check if friends
client.readFile("/space/Users/"+user+"/Access/"+other,null,function(error,s,stat){
if(error){
$("#stats").removeClass("show").addClass("hide");
return;
}
// If friends, then update
fetchAndUpdate("/space/Users/"+other+"/Statistics/");
});
}
}
////////////////////////////////////////
// Request/Accept friendship //
////////////////////////////////////////
function sendReq(){
var user = $('#login').val();
var other = $('#friend').val();
var count = Math.random().toString(36).substr(2, 5);
var pat = /^[a-zA-Z0-9-]+$/;
if(pat.test(user)&&pat.test(other)){
client.writeFile("/space/Feed/"+"REQ_"+other+"_"+user+"."+count, "", function(error, stat) {
if (error) {
console.log("Error requesting");
return;
}
});
}
}
////////////////////////////////////////
// Get pending requests //
////////////////////////////////////////
function getReq(){
// Remove old data
var myNode = document.getElementById("pending");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
// Update with new data
var user = $('#login').val();
var pat = /^[a-zA-Z0-9-]+$/;
if(pat.test(user)){
client.stat("/space/Users/"+user+"/Request/",{"readDir":true},function(error,stat,cstats){
if (error){
console.log("Requests not found");
return;
}
var temp = [];
for (var i = cstats.length - 1; i >= 0; i--) {
$('#pending').append("<li>Pending Request From "+cstats[i].name);
};
});
}
}
////////////////////////////////////////
// Aux function for stat updating //
////////////////////////////////////////
function fetchAndUpdate(path){
client.stat(path,{"readDir":true},function(error,stat,cstats){
if (error){
console.log("Stats not found");
$("#stats").removeClass("show").addClass("hide");
return;
}
var temp = [];
var result = {Druid:NaN,Hunter:NaN,Mage:NaN,Paladin:NaN,
Priest:NaN,Rogue:NaN,Shaman:NaN,Warlock:NaN,Warrior:NaN};
for (var i = cstats.length - 1; i >= 0; i--) {
temp = cstats[i].name.split("_");
result[temp[0]] = (parseFloat(temp[1])/(parseFloat(temp[2])+parseFloat(temp[1])))*100;
};
$("#DruidS").html(result.Druid.toFixed(0)+" %");
$("#HunterS").html(result.Hunter.toFixed(0)+" %");
$("#MageS").html(result.Mage.toFixed(0)+" %");
$("#PaladinS").html(result.Paladin.toFixed(0)+" %");
$("#PriestS").html(result.Priest.toFixed(0)+" %");
$("#RogueS").html(result.Rogue.toFixed(0)+" %");
$("#ShamanS").html(result.Shaman.toFixed(0)+" %");
$("#WarlockS").html(result.Warlock.toFixed(0)+" %");
$("#WarriorS").html(result.Warrior.toFixed(0)+" %");
});
$("#stats").removeClass("hide").addClass("show");
}
});
|
var API = require('../api/api-helper'),
AppService = require('./cluster-apps.service');
module.exports = {
list: listApps,
get: getApp,
install: installApp,
uninstall: uninstallApp
};
function listApps(req, res) {
API.handle.service(req, res, AppService.list());
}
function getApp(req, res) {
API.handle.service(req, res, AppService.get(req.params.profileId, req.params.slug));
}
function installApp(req, res) {
API.handle.service(req, res, AppService.install(req.body));
}
function uninstallApp(req, res) {
API.handle.service(req, res, AppService.uninstall(req.params.profileId, req.params.slug));
}
|
/**
* @license Apache-2.0
*
* Copyright (c) 2021 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 tape = require( 'tape' );
var isnanf = require( '@stdlib/math/base/assert/is-nanf' );
var Complex64 = require( '@stdlib/complex/float32' );
var real = require( '@stdlib/complex/real' );
var imag = require( '@stdlib/complex/imag' );
var cmulf = require( './../lib' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.strictEqual( typeof cmulf, 'function', 'main export is a function' );
t.end();
});
tape( 'the function multiples two complex numbers', function test( t ) {
var z1;
var z2;
var v;
z1 = new Complex64( 5.0, 3.0 );
z2 = new Complex64( -2.0, 1.0 );
v = cmulf( z1, z2 );
t.strictEqual( real( v ), -13.0, 'returns expected value' );
t.strictEqual( imag( v ), -1.0, 'returns expected value' );
t.end();
});
tape( 'if a real or imaginary component is `NaN`, all components are `NaN`', function test( t ) {
var z1;
var z2;
var v;
z1 = new Complex64( NaN, 3.0 );
z2 = new Complex64( -2.0, 1.0 );
v = cmulf( z1, z2 );
t.strictEqual( isnanf( real( v ) ), true, 'returns expected value' );
t.strictEqual( isnanf( imag( v ) ), true, 'returns expected value' );
z1 = new Complex64( 5.0, 3.0 );
z2 = new Complex64( NaN, 1.0 );
v = cmulf( z1, z2 );
t.strictEqual( isnanf( real( v ) ), true, 'returns expected value' );
t.strictEqual( isnanf( imag( v ) ), true, 'returns expected value' );
z1 = new Complex64( NaN, 3.0 );
z2 = new Complex64( NaN, 1.0 );
v = cmulf( z1, z2 );
t.strictEqual( isnanf( real( v ) ), true, 'returns expected value' );
t.strictEqual( isnanf( imag( v ) ), true, 'returns expected value' );
z1 = new Complex64( 5.0, NaN );
z2 = new Complex64( -2.0, 1.0 );
v = cmulf( z1, z2 );
t.strictEqual( isnanf( real( v ) ), true, 'returns expected value' );
t.strictEqual( isnanf( imag( v ) ), true, 'returns expected value' );
z1 = new Complex64( 5.0, 3.0 );
z2 = new Complex64( -2.0, NaN );
v = cmulf( z1, z2 );
t.strictEqual( isnanf( real( v ) ), true, 'returns expected value' );
t.strictEqual( isnanf( imag( v ) ), true, 'returns expected value' );
z1 = new Complex64( 5.0, NaN );
z2 = new Complex64( -2.0, NaN );
v = cmulf( z1, z2 );
t.strictEqual( isnanf( real( v ) ), true, 'returns expected value' );
t.strictEqual( isnanf( imag( v ) ), true, 'returns expected value' );
z1 = new Complex64( NaN, NaN );
z2 = new Complex64( NaN, NaN );
v = cmulf( z1, z2 );
t.strictEqual( isnanf( real( v ) ), true, 'returns expected value' );
t.strictEqual( isnanf( imag( v ) ), true, 'returns expected value' );
t.end();
});
|
/**
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.
*/
var cordova_util = require('../util');
var Q = require('q');
var CordovaError = require('cordova-common').CordovaError;
var HooksRunner = require('../../hooks/HooksRunner');
module.exports = plugin;
module.exports.add = require('./add');
module.exports.remove = require('./remove');
module.exports.list = require('./list');
module.exports.save = require('./save');
function plugin (command, targets, opts) {
// CB-10519 wrap function code into promise so throwing error
// would result in promise rejection instead of uncaught exception
return Q().then(function () {
var projectRoot = cordova_util.cdProjectRoot();
// Dance with all the possible call signatures we've come up over the time. They can be:
// 1. plugin() -> list the plugins
// 2. plugin(command, Array of targets, maybe opts object)
// 3. plugin(command, target1, target2, target3 ... )
// The targets are not really targets, they can be a mixture of plugins and options to be passed to plugman.
command = command || 'ls';
targets = targets || [];
opts = opts || {};
if (opts.length) {
// This is the case with multiple targets as separate arguments and opts is not opts but another target.
targets = Array.prototype.slice.call(arguments, 1);
opts = {};
}
if (!Array.isArray(targets)) {
// This means we had a single target given as string.
targets = [targets];
}
opts.options = opts.options || [];
opts.plugins = [];
var hooksRunner = new HooksRunner(projectRoot);
// Massage plugin name(s) / path(s)
if (!targets || !targets.length) {
// TODO: what if command provided is 'remove' ? shouldnt search need a target too?
if (command === 'add' || command === 'rm') {
return Q.reject(new CordovaError('You need to qualify `' + cordova_util.binname + ' plugin add` or `' + cordova_util.binname + ' plugin remove` with one or more plugins!'));
} else {
targets = [];
}
}
// Split targets between plugins and options
// Assume everything after a token with a '-' is an option
for (var i = 0; i < targets.length; i++) {
if (targets[i].match(/^-/)) {
opts.options = targets.slice(i);
break;
} else {
opts.plugins.push(targets[i]);
}
}
switch (command) {
case 'add':
return module.exports.add(projectRoot, hooksRunner, opts);
case 'rm':
case 'remove':
return module.exports.remove(projectRoot, targets, hooksRunner, opts);
case 'search':
return module.exports.search(hooksRunner, opts);
case 'save':
// save the versions/folders/git-urls of currently installed plugins into config.xml
return module.exports.save(projectRoot, opts);
default:
return module.exports.list(projectRoot, hooksRunner);
}
});
}
|
/*
* Kendo UI v2014.2.731 (http://www.telerik.com/kendo-ui)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["kn-IN"] = {
name: "kn-IN",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,2],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,2],
symbol: "%"
},
currency: {
pattern: ["$ -n","$ n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,2],
symbol: "ರೂ"
}
},
calendars: {
standard: {
days: {
names: ["ಭಾನುವಾರ","ಸೋಮವಾರ","ಮಂಗಳವಾರ","ಬುಧವಾರ","ಗುರುವಾರ","ಶುಕ್ರವಾರ","ಶನಿವಾರ"],
namesAbbr: ["ಭಾನು.","ಸೋಮ.","ಮಂಗಳ.","ಬುಧ.","ಗುರು.","ಶುಕ್ರ.","ಶನಿ."],
namesShort: ["ರ","ಸ","ಮ","ಬ","ಗ","ಶ","ಶ"]
},
months: {
names: ["ಜನವರಿ","ಫೆಬ್ರವರಿ","ಮಾರ್ಚ್","ಎಪ್ರಿಲ್","ಮೇ","ಜೂನ್","ಜುಲೈ","ಆಗಸ್ಟ್","ಸೆಪ್ಟಂಬರ್","ಅಕ್ಟೋಬರ್","ನವೆಂಬರ್","ಡಿಸೆಂಬರ್",""],
namesAbbr: ["ಜನವರಿ","ಫೆಬ್ರವರಿ","ಮಾರ್ಚ್","ಎಪ್ರಿಲ್","ಮೇ","ಜೂನ್","ಜುಲೈ","ಆಗಸ್ಟ್","ಸೆಪ್ಟಂಬರ್","ಅಕ್ಟೋಬರ್","ನವೆಂಬರ್","ಡಿಸೆಂಬರ್",""]
},
AM: ["ಪೂರ್ವಾಹ್ನ","ಪೂರ್ವಾಹ್ನ","ಪೂರ್ವಾಹ್ನ"],
PM: ["ಅಪರಾಹ್ನ","ಅಪರಾಹ್ನ","ಅಪರಾಹ್ನ"],
patterns: {
d: "dd-MM-yy",
D: "dd MMMM yyyy",
F: "dd MMMM yyyy HH:mm:ss",
g: "dd-MM-yy HH:mm",
G: "dd-MM-yy HH:mm:ss",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM, yyyy",
Y: "MMMM, yyyy"
},
"/": "-",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
|
Clazz.declarePackage ("J.script");
Clazz.load (["J.thread.JmolThread"], "J.script.ScriptQueueThread", ["J.util.Logger"], function () {
c$ = Clazz.decorateAsClass (function () {
this.scriptManager = null;
this.startedByCommandThread = false;
this.pt = 0;
Clazz.instantialize (this, arguments);
}, J.script, "ScriptQueueThread", J.thread.JmolThread);
Clazz.makeConstructor (c$,
function (scriptManager, viewer, startedByCommandThread, pt) {
Clazz.superConstructor (this, J.script.ScriptQueueThread);
this.setViewer (viewer, "QueueThread" + pt);
this.scriptManager = scriptManager;
this.viewer = viewer;
this.startedByCommandThread = startedByCommandThread;
this.pt = pt;
}, "J.api.JmolScriptManager,J.viewer.Viewer,~B,~N");
Clazz.overrideMethod (c$, "run1",
function (mode) {
while (true) switch (mode) {
case -1:
mode = 0;
break;
case 0:
if (this.stopped || this.scriptManager.getScriptQueue ().size () == 0) {
mode = -2;
break;
}if (!this.runNextScript () && !this.runSleep (100, 0)) return;
break;
case -2:
this.scriptManager.queueThreadFinished (this.pt);
return;
}
}, "~N");
$_M(c$, "runNextScript",
($fz = function () {
var queue = this.scriptManager.getScriptQueue ();
if (queue.size () == 0) return false;
var scriptItem = this.scriptManager.getScriptItem (false, this.startedByCommandThread);
if (scriptItem == null) return false;
var script = scriptItem.get (0);
var statusList = scriptItem.get (1);
var returnType = scriptItem.get (2);
var isScriptFile = (scriptItem.get (3)).booleanValue ();
var isQuiet = (scriptItem.get (4)).booleanValue ();
if (J.util.Logger.debugging) {
J.util.Logger.debug ("Queue[" + this.pt + "][" + queue.size () + "] scripts; running: " + script);
}queue.remove (0);
this.viewer.evalStringWaitStatusQueued (returnType, script, statusList, isScriptFile, isQuiet, true);
if (queue.size () == 0) {
return false;
}return true;
}, $fz.isPrivate = true, $fz));
});
|
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'ui.bootstrap',
'myApp.view1',
'myApp.view2',
'myApp.utils'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
|
/*
* Copyright 2019 dialog LLC <info@dlg.im>
* @flow
*/
import type { Field } from '@dlghq/dialog-types';
import React, { Component } from 'react';
import classNames from 'classnames';
import { Text } from '@dlghq/react-l10n';
import Modal from '../Modal/Modal';
import Icon from '../Icon/Icon';
import ModalBody from '../Modal/ModalBody';
import Logo from '../Logo/Logo';
import ButtonNext from '../ButtonNext/ButtonNext';
import Button from '../Button/Button';
import AboutModalChangeLogItems, {
type AboutModalChangeLogItemProps,
} from './AboutModalChangeLogItems';
import styles from './AboutModal.css';
type AboutModalProps = {
className?: string,
appName: string,
appVersion: string,
updatesDisabled: boolean,
changeLog?: Array<AboutModalChangeLogItemProps>,
updateState: Field<'upToDate' | 'available'>,
onCheck: () => mixed,
onUpdate: () => mixed,
onClose: () => mixed,
onVersionClick: () => mixed,
};
type AboutModalState = {
changeLogExpanded: boolean,
};
class AboutModal extends Component<AboutModalProps, AboutModalState> {
state = {
changeLogExpanded: false,
};
handleToggleChangeLog = () => {
this.setState((prevState) => {
return {
changeLogExpanded: !prevState.changeLogExpanded,
};
});
};
renderState() {
const { appName, updateState, updatesDisabled } = this.props;
if (updatesDisabled) {
return null;
}
if (updateState.error) {
return (
<div className={styles.state}>
<div className={styles.error}>{updateState.error.message}</div>;
</div>
);
}
if (updateState.pending) {
return (
<div className={styles.state}>
<Text
id={`AboutModal.pending.${updateState.value}`}
values={{ appName }}
/>
</div>
);
}
return (
<div className={styles.state}>
<Text
id={`AboutModal.state.${updateState.value}`}
values={{ appName }}
/>
</div>
);
}
renderUpdateButton() {
const { updateState, updatesDisabled } = this.props;
if (updatesDisabled) {
return null;
}
if (!updateState.error && updateState.value === 'available') {
return (
<ButtonNext
size="small"
id="about_update_button"
loading={updateState.pending}
onClick={this.props.onUpdate}
className={styles.button}
>
<Text id="AboutModal.update" />
</ButtonNext>
);
}
return (
<ButtonNext
size="small"
id="about_check_button"
loading={updateState.pending}
onClick={this.props.onCheck}
className={styles.button}
>
<Text id="AboutModal.check" />
</ButtonNext>
);
}
renderChangeLogButton() {
const { changeLog } = this.props;
const { changeLogExpanded } = this.state;
if (!changeLog || changeLog.length === 0) {
return null;
}
return (
<Button
theme="default"
size="small"
view="link"
id="about_change_log_button"
onClick={this.handleToggleChangeLog}
className={styles.changeLogButton}
>
<Text
id={
changeLogExpanded
? 'AboutModal.hideChangeLog'
: 'AboutModal.showChangeLog'
}
/>
</Button>
);
}
renderChangeLogBlock() {
const { changeLogExpanded } = this.state;
const { changeLog } = this.props;
if (!changeLogExpanded) {
return null;
}
if (!changeLog || changeLog.length === 0) {
return null;
}
return (
<div className={styles.changeLogWrapper}>
{changeLog.map((log) => (
<AboutModalChangeLogItems
key={`${log.version}_${log.date.toString()}`}
version={log.version}
date={log.date}
changes={log.changes}
/>
))}
</div>
);
}
render() {
const { appName, appVersion } = this.props;
const className = classNames(styles.container, this.props.className);
return (
<Modal className={className} onClose={this.props.onClose}>
<ModalBody className={styles.body}>
<Icon
id="about_close_button"
size={20}
glyph="close"
onClick={this.props.onClose}
className={styles.close}
/>
<Logo className={styles.logo} />
<h1 className={styles.appName}>{appName}</h1>
<Text
id="AboutModal.version"
values={{ appVersion }}
tagName="div"
onClick={this.props.onVersionClick}
className={styles.version}
/>
{this.renderState()}
{this.renderUpdateButton()}
{this.renderChangeLogButton()}
{this.renderChangeLogBlock()}
</ModalBody>
</Modal>
);
}
}
export default AboutModal;
|
function loadKeyboards()
{
var kmw=keyman;
kmw.addKeyboards({id:'rac_balti',name:'RAC Balti',
languages:{
id:'en',name:'English',region:'North America'
},
filename:'rac_balti.js'
});
}
|
import {Brightcove} from './component';
import {VideoBaseElement} from '../../amp-video/1.0/video-base-element';
export class BaseElement extends VideoBaseElement {}
/** @override */
BaseElement['Component'] = Brightcove;
/** @override */
BaseElement['props'] = {
'account': {attr: 'data-account', type: 'string'},
'autoplay': {attr: 'autoplay', type: 'boolean'},
'embed': {attr: 'data-embed', type: 'string', default: 'default'},
'player': {
attrs: ['data-player', 'data-player-id'],
parseAttrs(element) {
const {'player': player, 'playerId': playerId} = element.dataset;
return player || playerId || 'default';
},
},
'playlistId': {attr: 'data-playlist-id', type: 'string'},
'referrer': {attr: 'data-referrer', type: 'string'},
'urlParams': {attrPrefix: 'data-param-', type: 'string'},
'videoId': {attr: 'data-video-id', type: 'string'},
// TODO(wg-bento): These props have no internal implementation yet.
'dock': {attr: 'dock', media: true},
};
/** @override */
BaseElement['layoutSizeDefined'] = true;
/** @override */
BaseElement['usesShadowDom'] = true;
|
// Copyright 2008 The Closure Library Authors. 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.
/**
* @fileoverview A simple plugin that inserts 'Hello World!' on command. This
* plugin is intended to be an example of a very simple plugin for plugin
* developers.
*
* @see helloworld.html
*/
goog.provide('goog.demos.editor.HelloWorld');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.editor.Plugin');
/**
* Plugin to insert 'Hello World!' into an editable field.
* @constructor
* @extends {goog.editor.Plugin}
* @final
*/
goog.demos.editor.HelloWorld = function() {
goog.editor.Plugin.call(this);
};
goog.inherits(goog.demos.editor.HelloWorld, goog.editor.Plugin);
/** @override */
goog.demos.editor.HelloWorld.prototype.getTrogClassId = function() {
return 'HelloWorld';
};
/**
* Commands implemented by this plugin.
* @enum {string}
*/
goog.demos.editor.HelloWorld.COMMAND = {
HELLO_WORLD: '+helloWorld'
};
/** @override */
goog.demos.editor.HelloWorld.prototype.isSupportedCommand = function(command) {
return command == goog.demos.editor.HelloWorld.COMMAND.HELLO_WORLD;
};
/**
* Executes a command. Does not fire any BEFORECHANGE, CHANGE, or
* SELECTIONCHANGE events (these are handled by the super class implementation
* of `execCommand`.
* @param {string} command Command to execute.
* @override
* @protected
*/
goog.demos.editor.HelloWorld.prototype.execCommandInternal = function(command) {
var domHelper = this.getFieldObject().getEditableDomHelper();
var range = this.getFieldObject().getRange();
range.removeContents();
var newNode =
domHelper.createDom(goog.dom.TagName.SPAN, null, 'Hello World!');
range.insertNode(newNode, false);
};
|
var searchData=
[
['addr',['addr',['../d5/d4c/namespaceadmin.html#a6320eb02d5f6324a82fe70a83901b014',1,'admin']]],
['admin',['admin',['../d5/d4c/namespaceadmin.html',1,'']]],
['admin_2epy',['admin.py',['../da/d7c/admin_8py.html',1,'']]],
['adminerror',['AdminError',['../df/dee/classadmin_1_1AdminError.html',1,'admin']]],
['app',['app',['../d5/d4c/namespaceadmin.html#a88f927a5e67d8ccf759fd256f58a9411',1,'admin']]],
['application',['application',['../d4/d9e/namespacehello__uwsgi__app.html#a87c20de7f6fcc1eaa1ba7b1e5fe061be',1,'hello_uwsgi_app']]]
];
|
/**
* Search Console module initialization.
*
* Site Kit by Google, Copyright 2021 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.
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import { SettingsEdit, SettingsView } from './components/settings';
import DashboardImpressionsWidget from './components/dashboard/DashboardImpressionsWidget';
import DashboardClicksWidget from './components/dashboard/DashboardClicksWidget';
import DashboardPopularKeywordsWidget from './components/dashboard/DashboardPopularKeywordsWidget';
import ModulePopularKeywordsWidget from './components/module/ModulePopularKeywordsWidget';
import ModuleOverviewWidget from './components/module/ModuleOverviewWidget';
import SearchFunnelWidget from './components/dashboard/SearchFunnelWidget';
import {
AREA_DASHBOARD_ACQUISITION,
AREA_DASHBOARD_SEARCH_FUNNEL,
AREA_ENTITY_DASHBOARD_CONTENT_PRIMARY,
AREA_MAIN_DASHBOARD_CONTENT_PRIMARY,
AREA_PAGE_DASHBOARD_ACQUISITION,
AREA_PAGE_DASHBOARD_SEARCH_FUNNEL,
AREA_MAIN_DASHBOARD_TRAFFIC_PRIMARY,
AREA_ENTITY_DASHBOARD_TRAFFIC_PRIMARY,
} from '../../googlesitekit/widgets/default-areas';
import SearchConsoleIcon from '../../../svg/graphics/search-console.svg';
import { MODULES_SEARCH_CONSOLE } from './datastore/constants';
import {
CONTEXT_MODULE_SEARCH_CONSOLE,
AREA_MODULE_SEARCH_CONSOLE_MAIN,
} from './constants';
import { WIDGET_AREA_STYLES } from '../../googlesitekit/widgets/datastore/constants';
import { isFeatureEnabled } from '../../features';
export { registerStore } from './datastore';
export const registerModule = ( modules ) => {
modules.registerModule( 'search-console', {
storeName: MODULES_SEARCH_CONSOLE,
SettingsEditComponent: SettingsEdit,
SettingsViewComponent: SettingsView,
Icon: SearchConsoleIcon,
screenWidgetContext: CONTEXT_MODULE_SEARCH_CONSOLE,
} );
};
export const registerWidgets = ( widgets ) => {
if ( ! isFeatureEnabled( 'unifiedDashboard' ) ) {
widgets.registerWidget(
'searchConsoleImpressions',
{
Component: DashboardImpressionsWidget,
width: widgets.WIDGET_WIDTHS.QUARTER,
priority: 1,
wrapWidget: true,
},
[ AREA_DASHBOARD_SEARCH_FUNNEL, AREA_PAGE_DASHBOARD_SEARCH_FUNNEL ]
);
widgets.registerWidget(
'searchConsoleClicks',
{
Component: DashboardClicksWidget,
width: widgets.WIDGET_WIDTHS.QUARTER,
priority: 2,
wrapWidget: true,
},
[ AREA_DASHBOARD_SEARCH_FUNNEL, AREA_PAGE_DASHBOARD_SEARCH_FUNNEL ]
);
widgets.registerWidget(
'searchConsolePopularKeywords',
{
Component: DashboardPopularKeywordsWidget,
width: [
widgets.WIDGET_WIDTHS.HALF,
widgets.WIDGET_WIDTHS.FULL,
],
priority: 1,
wrapWidget: false,
},
[ AREA_DASHBOARD_ACQUISITION, AREA_PAGE_DASHBOARD_ACQUISITION ]
);
widgets.registerWidget(
'searchConsoleModuleOverview',
{
Component: ModuleOverviewWidget,
width: widgets.WIDGET_WIDTHS.FULL,
priority: 1,
wrapWidget: false,
},
[ AREA_MODULE_SEARCH_CONSOLE_MAIN ]
);
widgets.registerWidgetArea(
AREA_MODULE_SEARCH_CONSOLE_MAIN,
{
priority: 1,
style: WIDGET_AREA_STYLES.BOXES,
title: __( 'Overview', 'google-site-kit' ),
},
CONTEXT_MODULE_SEARCH_CONSOLE
);
widgets.registerWidget(
'searchConsoleModulePopularKeywords',
{
Component: ModulePopularKeywordsWidget,
width: [ widgets.WIDGET_WIDTHS.FULL ],
priority: 2,
wrapWidget: false,
},
[ AREA_MODULE_SEARCH_CONSOLE_MAIN ]
);
}
if ( isFeatureEnabled( 'unifiedDashboard' ) ) {
widgets.registerWidget(
'searchConsolePopularKeywords',
{
Component: DashboardPopularKeywordsWidget,
width: [
widgets.WIDGET_WIDTHS.HALF,
widgets.WIDGET_WIDTHS.FULL,
],
priority: 1,
wrapWidget: false,
},
[
AREA_MAIN_DASHBOARD_CONTENT_PRIMARY,
AREA_ENTITY_DASHBOARD_CONTENT_PRIMARY,
]
);
widgets.registerWidget(
'searchFunnel',
{
Component: SearchFunnelWidget,
width: [ widgets.WIDGET_WIDTHS.FULL ],
priority: 3,
wrapWidget: false,
},
[
AREA_MAIN_DASHBOARD_TRAFFIC_PRIMARY,
AREA_ENTITY_DASHBOARD_TRAFFIC_PRIMARY,
]
);
}
};
|
/**
* Created by root on 20/11/15.
*/
var Backbone = require('backbone');
Subscriber = Backbone.Model.extend({
default: {
padron: '0000',
firstname: '',
lastname: ''
},
});
module.exports = Subscriber;
|
const csvMap = new Map();
var isNumeric = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
var formatJsonPropMappings = function(jsonparent, k, v) {
var jsonpath = formatJsonPath(jsonparent,k,v);
var mapping = {"json":jsonpath,"value":v};
const vtype = typeof v;
if(vtype === "string" || vtype === 'number'){
const values = csvMap.get(jsonpath) || [];
values.push(v);
csvMap.set(jsonpath, values);
}
return mapping;
};
var formatJsonPath = function (parent, k, v) {
var path = '';
if (parent) {
if (isNumeric(k)) {
path = parent + '_';
} else {
path = parent + '.' + k;
}
} else {
path = k;
}
return path;
};
var traverseBoth = function(jsonObj,parentJson, callback) {
if( typeof jsonObj == "object" ) {
$.each(jsonObj, function(k,v) {
// k is either an array index or object key
var mapping = callback(parentJson, k,v);
// console.log(JSON.stringify(mapping));
traverseBoth(v,mapping.json,callback);
});
}
else {
// jsonOb is a number or string
}
};
|
// µ¼º½À¸ÅäÖÃÎļþ
var outlookbar=new outlook();
var t;
t=outlookbar.addtitle('»ù±¾ÉèÖÃ','¹ÜÀíÊ×Ò³',1)
outlookbar.additem('²é¿´¸öÈË×ÊÁÏ',t,'adminLookSelf.action')
outlookbar.additem('Ð޸ĸöÈË×ÊÁÏ',t,'adminupdate.jsp')
outlookbar.additem('¸ü¸ÄµÇ¼ÃÜÂë',t,'adminmodifypassword.jsp')
t=outlookbar.addtitle('¹ã¸æÉèÖÃ','¹ÜÀíÊ×Ò³',1)
outlookbar.additem('µÇ¼ÎÄѧÂÛ̳',t,'../vbb/forumdisplay.php?s=320e689ffabc5daa0be8b02c284d9968&forumid=39')
outlookbar.additem('·¢³öµç×ÓÓʼþ',t,'mailto:wangyong31893189@163.com')
t=outlookbar.addtitle('ÐÂÎÅÉèÖÃ','¹ÜÀíÊ×Ò³',1)
outlookbar.additem('ÉÐδͨ¹ýÎÄÕÂ',t,'un_pass.php')
outlookbar.additem('ÒѾͨ¹ýÎÄÕÂ',t,'al_pass.php')
outlookbar.additem('ÐÞ¸ÄÏÖÓÐÎÄÕÂ',t,'modify.php')
outlookbar.additem('׫д×îÐÂÎÄÕÂ',t,'sub_new.php')
outlookbar.additem('Ͷ¸å¸øÎÄѧ±¨',t,'#')
t=outlookbar.addtitle('Í˳öϵͳ','¹ÜÀíÊ×Ò³',1)
outlookbar.additem('µã»÷Í˳öµÇ¼',t,'loginout.jsp')
t=outlookbar.addtitle('»ù±¾ÉèÖÃ','ϵͳÉèÖÃ',1)
outlookbar.additem('²é¿´¸öÈË×ÊÁÏ',t,'adminLookSelf.action')
outlookbar.additem('Ð޸ĸöÈË×ÊÁÏ',t,'adminupdate.jsp')
outlookbar.additem('¸ü¸ÄµÇ¼ÃÜÂë',t,'adminmodifypassword.jsp')
t=outlookbar.addtitle('Óû§¹ÜÀí','ϵͳÉèÖÃ',1)
outlookbar.additem('²é¿´ËùÓÐ(Âò¼Ò|Âô¼Ò)',t,'adminqueryUser.action')
outlookbar.additem('ɾ³ýÂô¼Ò',t,'userdelete.jsp')
outlookbar.additem('Ôö¼ÓÂò¼Ò|Âô¼Ò',t,'useradd.jsp')
t=outlookbar.addtitle('¹ã¸æÉèÖÃ','ϵͳÉèÖÃ',1)
outlookbar.additem('µÇ¼ÎÄѧÂÛ̳',t,'/bbs/index.jsp')
outlookbar.additem('·¢³öµç×ÓÓʼþ',t,'mailto:wangyong31893189@163.com')
|
/**
* Copyright 2013 Facebook, 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.
*
* @providesModule ReactInjection
*/
"use strict";
var DOMProperty = require('DOMProperty');
var EventPluginHub = require('EventPluginHub');
var ReactDOM = require('ReactDOM');
var ReactEventEmitter = require('ReactEventEmitter');
var ReactPerf = require('ReactPerf');
var ReactRootIndex = require('ReactRootIndex');
var ReactUpdates = require('ReactUpdates');
var ReactInjection = {
DOMProperty: DOMProperty.injection,
EventPluginHub: EventPluginHub.injection,
DOM: ReactDOM.injection,
EventEmitter: ReactEventEmitter.injection,
Perf: ReactPerf.injection,
RootIndex: ReactRootIndex.injection,
Updates: ReactUpdates.injection
};
module.exports = ReactInjection;
|
/*
* lib/parse.js
*
* David Janes
* IOTDB.org
* 2014-07-17
*
* Parse HTTP Link: value. Not quite finished, but
* good enough for show business.
*
* See:
* http://tools.ietf.org/html/rfc5988
*
* Copyright [2013-2016] [David P. Janes]
*
* 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"
const _see_link = text => {
const match = text.match(/^\s*<([^>]*)>/);
if (match) {
return {
url: match[1],
link: text.substring(match[0].length)
};
}
};
const _see_semicolon = text => {
const match = text.match(/^\s*;/);
if (match) {
return {
link: text.substring(match[0].length)
};
}
};
const _see_comma = text => {
const match = text.match(/^\s*,/);
if (match) {
return {
link: text.substring(match[0].length)
};
}
};
// XXX - missing \" handling
const _see_extension = text => {
const match = text.match(/^\s*([^=\s]*)\s*=\s*"([^"]*)"/) || text.match(/^\s*([^=\s]*)\s*=\s*([^,;]*)/);
if (match) {
return {
name: match[1],
value: match[2],
link: text.substring(match[0].length)
};
}
};
const parse_link = function (link) {
const rdd = {};
let d;
while (link.length > 0) {
// link
d = _see_link(link);
if (!d) {
break;
} else {
link = d.link;
}
const rd = {};
rdd[d.url] = rd;
while (true) {
d = _see_semicolon(link);
if (!d) {
break;
} else {
link = d.link;
}
d = _see_extension(link);
if (!d) {
break;
} else {
link = d.link;
}
rd[d.name] = d.value;
}
d = _see_comma(link);
if (!d) {
break;
} else {
link = d.link;
}
}
return rdd;
};
/**
*/
const flat = (link, _key) => {
const linkd = parse_link(link)
const urls = Object.keys(linkd)
return urls
.map(url => Object.assign({}, linkd[url], { [ _key || "url" ]: url }))
}
/**
* API
*/
exports.parse = parse_link
exports.parse.flat = flat
|
/*
* @KaiyiZhang Github
*/
var url = "$URL"; //The Target
var xhr = new XMLHttpRequest();
xhr.open("GET",url,"$IsAsync[True|False]"); // Ture: Async
xhr.onreadystatechange = function() {
if(xhr.readyState==4){
console.log('xhr:',xhr);
console.log('data:',xhr.responseText);
}
}
xhr.send();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.