hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3d83b766807da67334a60a39464ab6c38dad9e21 | 13,451 | js | JavaScript | src/main.js | abhobe/wrelks-quirk | be204db87be11f2c9a30d7b0d897baf7b0983c5c | [
"Apache-2.0"
] | 1 | 2020-10-28T23:58:29.000Z | 2020-10-28T23:58:29.000Z | src/main.js | abhobe/wrelks-quirk | be204db87be11f2c9a30d7b0d897baf7b0983c5c | [
"Apache-2.0"
] | null | null | null | src/main.js | abhobe/wrelks-quirk | be204db87be11f2c9a30d7b0d897baf7b0983c5c | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// It's important that the polyfills and error fallback get loaded first!
import {} from "src/browser/Polyfills.js"
import {hookErrorHandler} from "src/fallback.js"
hookErrorHandler();
import {doDetectIssues} from "src/issues.js"
doDetectIssues();
import {CircuitStats} from "src/circuit/CircuitStats.js"
import {CooldownThrottle} from "src/base/CooldownThrottle.js"
import {Config} from "src/Config.js"
import {DisplayedInspector} from "src/ui/DisplayedInspector.js"
import {Painter} from "src/draw/Painter.js"
import {Rect} from "src/math/Rect.js"
import {RestartableRng} from "src/base/RestartableRng.js"
import {Revision} from "src/base/Revision.js"
import {initSerializer, fromJsonText_CircuitDefinition} from "src/circuit/Serializer.js"
import {TouchScrollBlocker} from "src/browser/TouchScrollBlocker.js"
import {Util} from "src/base/Util.js"
import {initializedWglContext} from "src/webgl/WglContext.js"
import {watchDrags, isMiddleClicking, eventPosRelativeTo} from "src/browser/MouseWatcher.js"
import {ObservableValue, ObservableSource} from "src/base/Obs.js"
import {initExports, obsExportsIsShowing} from "src/ui/exports.js"
import {initForge, obsForgeIsShowing} from "src/ui/forge.js"
import {initMenu, obsMenuIsShowing, closeMenu} from "src/ui/menu.js"
import {initUndoRedo} from "src/ui/undo.js"
import {initClear} from "src/ui/clear.js"
import {initUrlCircuitSync} from "src/ui/url.js"
import {initTitleSync} from "src/ui/title.js"
import {simulate} from "src/ui/sim.js"
import {GatePainting} from "src/draw/GatePainting.js"
import {GATE_CIRCUIT_DRAWER} from "src/ui/DisplayedCircuit.js"
import {GateColumn} from "src/circuit/GateColumn.js";
import {Point} from "src/math/Point.js";
import {Serializer} from "src/circuit/Serializer.js"
initSerializer(
GatePainting.LABEL_DRAWER,
GatePainting.MATRIX_DRAWER,
GATE_CIRCUIT_DRAWER,
GatePainting.LOCATION_INDEPENDENT_GATE_DRAWER);
const canvasDiv = document.getElementById("canvasDiv");
//noinspection JSValidateTypes
/** @type {!HTMLCanvasElement} */
const canvas = document.getElementById("drawCanvas");
//noinspection JSValidateTypes
if (!canvas) {
throw new Error("Couldn't find 'drawCanvas'");
}
canvas.width = canvasDiv.clientWidth;
canvas.height = window.innerHeight*0.9;
let haveLoaded = false;
const semiStableRng = (() => {
const target = {cur: new RestartableRng()};
let cycleRng;
cycleRng = () => {
target.cur = new RestartableRng();
//noinspection DynamicallyGeneratedCodeJS
setTimeout(cycleRng, Config.SEMI_STABLE_RANDOM_VALUE_LIFETIME_MILLIS*0.99);
};
cycleRng();
return target;
})();
//noinspection JSValidateTypes
/** @type {!HTMLDivElement} */
const inspectorDiv = document.getElementById("inspectorDiv");
/** @type {ObservableValue.<!DisplayedInspector>} */
const displayed = new ObservableValue(
DisplayedInspector.empty(new Rect(0, 0, canvas.clientWidth, canvas.clientHeight)));
const mostRecentStats = new ObservableValue(CircuitStats.EMPTY);
/** @type {!Revision} */
let revision = Revision.startingAt(displayed.get().snapshot());
var hmatrix = "\\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1 & 1 \\\\ 1 & -1\\end{bmatrix}";
var ymatrix = "\\begin{bmatrix} 0 & -i \\\\ i & 0\\end{bmatrix}";
var xmatrix = "\\begin{bmatrix} 0 & 1 \\\\ 1 & 0\\end{bmatrix}";
var zmatrix = "\\begin{bmatrix} 1 & 0 \\\\ 0 & -1\\end{bmatrix}";
function convt(inp) {
let matrix = '\\times\\begin{pmatrix} 1 \\\\ 0\\end{pmatrix}$$'
let label = '\\times|0\\rangle$$'
let {cols} = JSON.parse(inp)
let matrixHTML = document.getElementById("matrix");
let labelHTML = document.getElementById("label");
let gateDict = {
'H': hmatrix,
'X': xmatrix,
'Y': ymatrix,
'Z': zmatrix
};
for (let i = 0;i < Object.keys(cols).length; i++) {
let key = String(cols[i]);
if (gateDict.hasOwnProperty(key)) {
if (i != 0){
matrix = ' \\times ' + matrix
label =' \\times ' + label
}
matrix = gateDict[key] + matrix;
label = key + label;
}
else {
console.warn(cols[i] + ' is not a gate.')
}
}
matrix ='$$' + matrix;
label = '$$' + label;
matrixHTML.innerHTML = matrix;
labelHTML.innerHTML = label;
}
revision.latestActiveCommit().subscribe(jsonText => {
let circuitDef = fromJsonText_CircuitDefinition(jsonText);
let newInspector = displayed.get().withCircuitDefinition(circuitDef);
let jsonInpText = JSON.stringify(Serializer.toJson(circuitDef));
if (document.readyState === 'complete') {
convt(jsonInpText);
}
displayed.set(newInspector);
});
/**
* @param {!DisplayedInspector} curInspector
* @returns {{w: number, h: !number}}
*/
let desiredCanvasSizeFor = curInspector => {
return {
w: Math.max(canvasDiv.clientWidth, curInspector.desiredWidth()),
h: curInspector.desiredHeight()
};
};
/**
* @param {!DisplayedInspector} ins
* @returns {!DisplayedInspector}
*/
const syncArea = ins => {
let size = desiredCanvasSizeFor(ins);
ins.updateArea(new Rect(0, 0, size.w, size.h));
return ins;
};
// Gradually fade out old errors as user manipulates circuit.
displayed.observable().
map(e => e.displayedCircuit.circuitDefinition).
whenDifferent(Util.CUSTOM_IS_EQUAL_TO_EQUALITY).
subscribe(() => {
let errDivStyle = document.getElementById('error-div').style;
errDivStyle.opacity *= 0.9;
if (errDivStyle.opacity < 0.06) {
errDivStyle.display = 'None'
}
});
/** @type {!CooldownThrottle} */
let redrawThrottle;
const scrollBlocker = new TouchScrollBlocker(canvasDiv);
const redrawNow = () => {
if (!haveLoaded) {
// Don't draw while loading. It's a huge source of false-positive circuit-load-failed errors during development.
return;
}
let shown = syncArea(displayed.get()).previewDrop();
if (displayed.get().hand.isHoldingSomething() && !shown.hand.isHoldingSomething()) {
shown = shown.withHand(shown.hand.withHeldGateColumn(new GateColumn([]), new Point(0, 0)))
}
let stats = simulate(shown.displayedCircuit.circuitDefinition);
mostRecentStats.set(stats);
let size = desiredCanvasSizeFor(shown);
canvas.width = size.w;
canvas.height = size.h;
let painter = new Painter(canvas, semiStableRng.cur.restarted());
shown.updateArea(painter.paintableArea());
shown.paint(painter, stats);
painter.paintDeferred();
displayed.get().hand.paintCursor(painter);
scrollBlocker.setBlockers(painter.touchBlockers, painter.desiredCursorStyle);
canvas.style.cursor = painter.desiredCursorStyle || 'auto';
let dt = displayed.get().stableDuration();
if (dt < Infinity) {
window.requestAnimationFrame(() => redrawThrottle.trigger());
}
};
redrawThrottle = new CooldownThrottle(redrawNow, Config.REDRAW_COOLDOWN_MILLIS, 0.1, true);
window.addEventListener('resize', () => redrawThrottle.trigger(), false);
displayed.observable().subscribe(() => redrawThrottle.trigger());
/** @type {undefined|!string} */
let clickDownGateButtonKey = undefined;
canvasDiv.addEventListener('click', ev => {
let pt = eventPosRelativeTo(ev, canvasDiv);
let curInspector = displayed.get();
if (curInspector.tryGetHandOverButtonKey() !== clickDownGateButtonKey) {
return;
}
let clicked = syncArea(curInspector.withHand(curInspector.hand.withPos(pt))).tryClick();
if (clicked !== undefined) {
revision.commit(clicked.afterTidyingUp().snapshot());
}
});
watchDrags(canvasDiv,
/**
* Grab
* @param {!Point} pt
* @param {!MouseEvent|!TouchEvent} ev
*/
(pt, ev) => {
let oldInspector = displayed.get();
let newHand = oldInspector.hand.withPos(pt);
let newInspector = syncArea(oldInspector.withHand(newHand));
clickDownGateButtonKey = (
ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.altKey ? undefined : newInspector.tryGetHandOverButtonKey());
if (clickDownGateButtonKey !== undefined) {
displayed.set(newInspector);
return;
}
newInspector = newInspector.afterGrabbing(ev.shiftKey, ev.ctrlKey || ev.metaKey);
if (displayed.get().isEqualTo(newInspector) || !newInspector.hand.isBusy()) {
return;
}
// Add extra wire temporarily.
revision.startedWorkingOnCommit();
displayed.set(
syncArea(oldInspector.withHand(newHand).withJustEnoughWires(newInspector.hand, 1)).
afterGrabbing(ev.shiftKey, ev.ctrlKey || ev.metaKey, false, ev.altKey));
ev.preventDefault();
},
/**
* Cancel
* @param {!MouseEvent|!TouchEvent} ev
*/
ev => {
revision.cancelCommitBeingWorkedOn();
ev.preventDefault();
},
/**
* Drag
* @param {undefined|!Point} pt
* @param {!MouseEvent|!TouchEvent} ev
*/
(pt, ev) => {
if (!displayed.get().hand.isBusy()) {
return;
}
let newHand = displayed.get().hand.withPos(pt);
let newInspector = displayed.get().withHand(newHand);
displayed.set(newInspector);
ev.preventDefault();
},
/**
* Drop
* @param {undefined|!Point} pt
* @param {!MouseEvent|!TouchEvent} ev
*/
(pt, ev) => {
if (!displayed.get().hand.isBusy()) {
return;
}
let newHand = displayed.get().hand.withPos(pt);
let newInspector = syncArea(displayed.get()).withHand(newHand).afterDropping().afterTidyingUp();
let clearHand = newInspector.hand.withPos(undefined);
let clearInspector = newInspector.withJustEnoughWires(clearHand, 0);
revision.commit(clearInspector.snapshot());
ev.preventDefault();
});
// Middle-click to delete a gate.
canvasDiv.addEventListener('mousedown', ev => {
if (!isMiddleClicking(ev)) {
return;
}
let cur = syncArea(displayed.get());
let initOver = cur.tryGetHandOverButtonKey();
let newHand = cur.hand.withPos(eventPosRelativeTo(ev, canvas));
let newInspector;
if (initOver !== undefined && initOver.startsWith('wire-init-')) {
let newCircuit = cur.displayedCircuit.circuitDefinition.withSwitchedInitialStateOn(
parseInt(initOver.substr(10)), 0);
newInspector = cur.withCircuitDefinition(newCircuit).withHand(newHand).afterTidyingUp();
} else {
newInspector = cur.
withHand(newHand).
afterGrabbing(false, false, true, false). // Grab the gate.
withHand(newHand). // Lose the gate.
afterTidyingUp().
withJustEnoughWires(newHand, 0);
}
if (!displayed.get().isEqualTo(newInspector)) {
revision.commit(newInspector.snapshot());
ev.preventDefault();
}
});
// When mouse moves without dragging, track it (for showing hints and things).
canvasDiv.addEventListener('mousemove', ev => {
if (!displayed.get().hand.isBusy()) {
let newHand = displayed.get().hand.withPos(eventPosRelativeTo(ev, canvas));
let newInspector = displayed.get().withHand(newHand);
displayed.set(newInspector);
}
});
canvasDiv.addEventListener('mouseleave', () => {
if (!displayed.get().hand.isBusy()) {
let newHand = displayed.get().hand.withPos(undefined);
let newInspector = displayed.get().withHand(newHand);
displayed.set(newInspector);
}
});
let obsIsAnyOverlayShowing = new ObservableSource();
initUrlCircuitSync(revision);
initExports(revision, mostRecentStats, obsIsAnyOverlayShowing.observable());
initForge(revision, obsIsAnyOverlayShowing.observable());
initUndoRedo(revision, obsIsAnyOverlayShowing.observable());
initClear(revision, obsIsAnyOverlayShowing.observable());
initMenu(revision, obsIsAnyOverlayShowing.observable());
initTitleSync(revision);
obsForgeIsShowing.
zipLatest(obsExportsIsShowing, (e1, e2) => e1 || e2).
zipLatest(obsMenuIsShowing, (e1, e2) => e1 || e2).
whenDifferent().
subscribe(e => {
obsIsAnyOverlayShowing.send(e);
canvasDiv.tabIndex = e ? -1 : 0;
});
// If the webgl initialization is going to fail, don't fail during the module loading phase.
haveLoaded = true;
setTimeout(() => {
inspectorDiv.style.display = 'block';
redrawNow();
document.getElementById("loading-div").style.display = 'none';
document.getElementById("close-menu-button").style.display = 'block';
if (!displayed.get().displayedCircuit.circuitDefinition.isEmpty()) {
closeMenu();
}
try {
initializedWglContext().onContextRestored = () => redrawThrottle.trigger();
} catch (ex) {
// If that faxiled, the user is already getting warnings about WebGL not being supported.
// Just silently log it.
console.error(ex);
}
}, 0);
| 35.584656 | 120 | 0.673258 |
3d83bb7983251862ce8aeff8782329804a887561 | 12,400 | js | JavaScript | src/nodes/trigger-state/controller.js | Hexagon/node-red-contrib-home-assistant-websocket | 59c5716bc9db21830dd4ddc0c08a96d4b2d81d3c | [
"MIT"
] | null | null | null | src/nodes/trigger-state/controller.js | Hexagon/node-red-contrib-home-assistant-websocket | 59c5716bc9db21830dd4ddc0c08a96d4b2d81d3c | [
"MIT"
] | null | null | null | src/nodes/trigger-state/controller.js | Hexagon/node-red-contrib-home-assistant-websocket | 59c5716bc9db21830dd4ddc0c08a96d4b2d81d3c | [
"MIT"
] | null | null | null | /* eslint-disable camelcase */
const cloneDeep = require('lodash.clonedeep');
const selectn = require('selectn');
const EventsHaNode = require('../EventsHaNode');
const { renderTemplate } = require('../../helpers/mustache');
const { shouldIncludeEvent } = require('../../helpers/utils');
const nodeOptions = {
debug: true,
config: {
entityid: {},
entityidfiltertype: {},
constraints: {},
customoutputs: {},
outputinitially: {},
state_type: { value: 'str' },
},
};
class TriggerState extends EventsHaNode {
constructor({ node, config, RED, status }) {
super({ node, config, RED, status, nodeOptions });
let eventTopic = 'ha_events:state_changed';
if (this.nodeConfig.entityidfiltertype === 'exact') {
eventTopic =
this.eventTopic = `ha_events:state_changed:${this.nodeConfig.entityid.trim()}`;
}
this.addEventClientListener(
eventTopic,
this.onEntityStateChanged.bind(this)
);
this.NUM_DEFAULT_MESSAGES = 2;
if (this.nodeConfig.outputinitially) {
// Here for when the node is deploy without the server config being deployed
if (this.isHomeAssistantRunning) {
this.onDeploy();
} else {
this.addEventClientListener(
'ha_client:initial_connection_ready',
this.onStatesLoaded.bind(this)
);
}
}
}
onInput({ message }) {
if (message === 'enable' || message.payload === 'enable') {
this.isEnabled = true;
this.storage.saveData('isEnabled', true);
this.updateHomeAssistant();
return;
}
if (message === 'disable' || message.payload === 'disable') {
this.isEnabled = false;
this.storage.saveData('isEnabled', false);
this.updateHomeAssistant();
return;
}
const { entity_id, new_state, old_state } = message.payload;
if (entity_id && new_state && old_state) {
const evt = {
event_type: 'state_changed',
entity_id: entity_id,
event: message.payload,
};
this.onEntityStateChanged(evt);
}
}
onDeploy() {
const entities = this.homeAssistant.getStates();
this.onStatesLoaded(entities);
}
onStatesLoaded(entities) {
for (const entityId in entities) {
const eventMessage = {
event_type: 'state_changed',
entity_id: entityId,
event: {
entity_id: entityId,
old_state: entities[entityId],
new_state: entities[entityId],
},
};
this.onEntityStateChanged(eventMessage);
}
}
onEntityStateChanged(evt) {
if (this.isEnabled === false) {
this.debugToClient(
'incoming: node is currently disabled, ignoring received event'
);
return;
}
if (!selectn('event.new_state', evt) || !this.isHomeAssistantRunning) {
return;
}
const eventMessage = cloneDeep(evt);
if (
!shouldIncludeEvent(
eventMessage.entity_id,
this.nodeConfig.entityid,
this.nodeConfig.entityidfiltertype
)
) {
return;
}
// Convert and save original state if needed
this.castState(
eventMessage.event.old_state,
this.nodeConfig.state_type
);
this.castState(
eventMessage.event.new_state,
this.nodeConfig.state_type
);
try {
eventMessage.event.new_state.timeSinceChangedMs =
Date.now() -
new Date(eventMessage.event.new_state.last_changed).getTime();
const constraintComparatorResults =
this.getConstraintComparatorResults(
this.nodeConfig.constraints,
eventMessage
);
const statusText = `${eventMessage.event.new_state.state}${
eventMessage.event_type === 'triggered' ? ' (triggered)' : ''
}`;
let outputs = this.getDefaultMessageOutputs(
constraintComparatorResults,
eventMessage
);
// If a constraint comparator failed we're done, also if no custom outputs to look at
if (
constraintComparatorResults.failed.length ||
!this.nodeConfig.customoutputs.length
) {
if (constraintComparatorResults.failed.length) {
this.status.setFailed(statusText);
} else {
this.status.setSuccess(statusText);
}
this.debugToClient(
'done processing sending messages: ',
outputs
);
this.send(outputs);
return;
}
const customOutputsComparatorResults =
this.getCustomOutputsComparatorResults(
this.nodeConfig.customoutputs,
eventMessage
);
const customOutputMessages = customOutputsComparatorResults.map(
(r) => r.message
);
outputs = outputs.concat(customOutputMessages);
this.debugToClient('done processing sending messages: ', outputs);
this.status.setSuccess(statusText);
this.send(outputs);
} catch (e) {
this.node.error(e);
}
}
getNodeEntityId() {
return (
this.nodeConfig.entityidfiltertype === 'exact' &&
this.nodeConfig.entityid
);
}
triggerNode(eventMessage) {
this.onEntityStateChanged(eventMessage);
}
getConstraintComparatorResults(constraints, eventMessage) {
const comparatorResults = [];
// Check constraints
for (const constraint of constraints) {
const {
comparatorType,
comparatorValue,
comparatorValueDatatype,
propertyValue,
} = constraint;
const constraintTarget = this.getConstraintTargetData(
constraint,
eventMessage.event
);
const actualValue = selectn(
constraint.propertyValue,
constraintTarget.state
);
const comparatorResult = this.getComparatorResult(
comparatorType,
comparatorValue,
actualValue,
comparatorValueDatatype,
{
entity: eventMessage.event.new_state,
prevEntity: eventMessage.event.old_state,
}
);
if (comparatorResult === false) {
this.debugToClient(
`constraint comparator: failed entity "${constraintTarget.entityid}" property "${propertyValue}" with value ${actualValue} failed "${comparatorType}" check against (${comparatorValueDatatype}) ${comparatorValue}`
);
}
comparatorResults.push({
constraint,
constraintTarget,
actualValue,
comparatorResult,
});
}
const failedComparators = comparatorResults.filter(
(res) => !res.comparatorResult
);
return {
all: comparatorResults || [],
failed: failedComparators || [],
};
}
getDefaultMessageOutputs(comparatorResults, eventMessage) {
const { entity_id, event } = eventMessage;
const msg = {
topic: entity_id,
payload: event.new_state.state,
data: eventMessage,
};
let outputs;
if (comparatorResults.failed.length) {
this.debugToClient(
'constraint comparator: one more more comparators failed to match constraints, message will send on the failed output'
);
msg.failedComparators = comparatorResults.failed;
outputs = [null, msg];
} else {
outputs = [msg, null];
}
return outputs;
}
getCustomOutputsComparatorResults(outputs, eventMessage) {
return outputs.reduce((acc, output) => {
const result = {
output,
comparatorMatched: true,
actualValue: null,
message: null,
};
if (output.comparatorPropertyType !== 'always') {
result.actualValue = selectn(
output.comparatorPropertyValue,
eventMessage.event
);
result.comparatorMatched = this.getComparatorResult(
output.comparatorType,
output.comparatorValue,
result.actualValue,
output.comparatorValueDataType,
{
entity: eventMessage.event.new_state,
prevEntity: eventMessage.event.old_state,
}
);
}
result.message = this.getOutputMessage(result, eventMessage);
acc.push(result);
return acc;
}, []);
}
getConstraintTargetData(constraint, triggerEvent) {
const targetData = {
entityid: null,
state: null,
};
try {
const isTargetThisEntity = constraint.targetType === 'this_entity';
targetData.entityid = isTargetThisEntity
? this.nodeConfig.entityid
: constraint.targetValue;
targetData.state = isTargetThisEntity
? triggerEvent
: this.homeAssistant.getStates(targetData.entityid);
if (
!isTargetThisEntity &&
constraint.propertyType === 'current_state'
) {
targetData.state = {
new_state: targetData.state,
};
}
} catch (e) {
this.node.debug(
'Error during trigger:state comparator evaluation: ',
e.stack
);
throw e;
}
return targetData;
}
getOutputMessage({ output, comparatorMatched, actualValue }, eventMessage) {
// If comparator did not match
if (!comparatorMatched) {
this.debugToClient(
`output comparator failed: property "${output.comparatorPropertyValue}" with value ${actualValue} failed "${output.comparatorType}" check against (${output.comparatorValueDataType}) ${output.comparatorValue}`
);
return null;
}
let payload = eventMessage.event.new_state.state;
if (
output.messageType === 'custom' ||
output.messageType === 'payload'
) {
// Render Template Variables
payload = renderTemplate(
output.messageValue,
eventMessage.event,
this.node.context(),
this.homeAssistant.getStates()
);
switch (output.messageValueType) {
case 'num':
payload = Number(payload);
break;
case 'bool':
payload = payload === 'true';
break;
case 'str':
break;
case 'json':
default:
try {
payload = JSON.parse(payload);
} catch (e) {}
break;
}
if (output.messageType === 'custom') {
return payload;
}
}
return {
topic: eventMessage.entity_id,
payload,
data: eventMessage,
};
}
}
module.exports = TriggerState;
| 31.392405 | 232 | 0.509113 |
3d83c5d168d345d2e649b885bd3129e117df38bf | 4,565 | js | JavaScript | 3. JS Advanced/Exam Preparation 2/03. Library/library.test.js | EdizOnFire/Softuni-JavaScript | 7e757dd36b04b3d1df7c00711194f59b0ef3e82f | [
"MIT"
] | null | null | null | 3. JS Advanced/Exam Preparation 2/03. Library/library.test.js | EdizOnFire/Softuni-JavaScript | 7e757dd36b04b3d1df7c00711194f59b0ef3e82f | [
"MIT"
] | null | null | null | 3. JS Advanced/Exam Preparation 2/03. Library/library.test.js | EdizOnFire/Softuni-JavaScript | 7e757dd36b04b3d1df7c00711194f59b0ef3e82f | [
"MIT"
] | null | null | null | const library = require("./library.js");
const { assert, expect } = require('chai');
describe("Library function tests", () => {
describe("Valid: Calculating a price for a book tests", () => {
it("Should show with normal price", () => {
assert(library.calcPriceOfBook('s', 1999) === "Price of s is 20.00")
});
it("Should show with normal price", () => {
assert(library.calcPriceOfBook('s', 1980) === "Price of s is 10.00")
});
it("Should show with half price", () => {
assert(library.calcPriceOfBook('s', 1979) === "Price of s is 10.00")
});
});
describe("Invalid: Calculating a price for a book tests", () => {
it("Should throw error with int and int", () => {
expect(() => library.calcPriceOfBook(1979, 19)).to.throw(Error, `Invalid input`);
});
it("Should throw error with obj and int", () => {
expect(() => library.calcPriceOfBook({}, 19)).to.throw(Error, `Invalid input`);
});
it("Should throw error with arr and int", () => {
expect(() => library.calcPriceOfBook([], 19)).to.throw(Error, `Invalid input`);
});
it("Should throw error with null and int", () => {
expect(() => library.calcPriceOfBook(null, 19)).to.throw(Error, `Invalid input`);
});
it("Should throw error with undefined and int", () => {
expect(() => library.calcPriceOfBook(undefined, 19)).to.throw(Error, `Invalid input`);
});
it("Should throw error with str and str", () => {
expect(() => library.calcPriceOfBook('s','s')).to.throw(Error, `Invalid input`);
});
it("Should throw error with str and obj", () => {
expect(() => library.calcPriceOfBook('s',{})).to.throw(Error, `Invalid input`);
});
it("Should throw error with str and arr", () => {
expect(() => library.calcPriceOfBook('s',[])).to.throw(Error, `Invalid input`);
});
it("Should throw error with null and str", () => {
expect(() => library.calcPriceOfBook(null, 's')).to.throw(Error, `Invalid input`);
});
it("Should throw error with undefined and str", () => {
expect(() => library.calcPriceOfBook(undefined, 's')).to.throw(Error, `Invalid input`);
});
});
describe("Valid: Finding a book tests", () => {
it("Should find book", () => {
assert(library.findBook(['book'], 'book') === "We found the book you want.")
});
it("Should not have the needed book", () => {
assert(library.findBook(['book'], 'notABook') === "The book you are looking for is not here!")
});
});
describe("Invalid: Finding a book tests", () => {
it("Should throw error if arr length 0", () => {
expect(() => library.findBook([], 's')).to.throw(Error, `No books currently available`);
});
});
describe("Valid: Arranging books tests", () => {
it("Should arrange the books", () => {
assert(library.arrangeTheBooks(39) === "Great job, the books are arranged.")
});
it("Should arrange the books with exact amount", () => {
assert(library.arrangeTheBooks(40) === "Great job, the books are arranged.")
});
it("Should return insufficient space", () => {
assert(library.arrangeTheBooks(41) === "Insufficient space, more shelves need to be purchased.")
});
});
describe("Invalid: Arranging books tests", () => {
it("Should throw error if input is negative int", () => {
expect(() => library.arrangeTheBooks(-1)).to.throw(Error, `Invalid input`);
});
it("Should throw error if input is str", () => {
expect(() => library.arrangeTheBooks('1')).to.throw(Error, `Invalid input`);
});
it("Should throw error if input is obj", () => {
expect(() => library.arrangeTheBooks({})).to.throw(Error, `Invalid input`);
});
it("Should throw error if input is arr", () => {
expect(() => library.arrangeTheBooks([])).to.throw(Error, `Invalid input`);
});
it("Should throw error if input is null", () => {
expect(() => library.arrangeTheBooks(null)).to.throw(Error, `Invalid input`);
});
it("Should throw error if input is undefined", () => {
expect(() => library.arrangeTheBooks(undefined)).to.throw(Error, `Invalid input`);
});
});
});
| 49.086022 | 108 | 0.539102 |
3d843a9d25d21a4acd634fdb621bd5537a740803 | 1,500 | js | JavaScript | src/main/webapp/widgets/Bookmark/nls/Widget_nl.js | emkgth/clean-water | d333aae1487fd7b620521038acee4590801f2c45 | [
"Apache-2.0"
] | null | null | null | src/main/webapp/widgets/Bookmark/nls/Widget_nl.js | emkgth/clean-water | d333aae1487fd7b620521038acee4590801f2c45 | [
"Apache-2.0"
] | null | null | null | src/main/webapp/widgets/Bookmark/nls/Widget_nl.js | emkgth/clean-water | d333aae1487fd7b620521038acee4590801f2c45 | [
"Apache-2.0"
] | null | null | null | // All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.15/esri/copyright.txt and http://www.arcgis.com/apps/webappbuilder/copyright.txt for details.
//>>built
define({"widgets/Bookmark/nls/strings":{labelBookmarkName:"Bladwijzer maken voor de huidige weergave",labelPlay:"Alles afspelen",labelStop:"Stoppen",labelDelete:"Verwijderen",placeholderBookmarkName:"Naam van bladwijzer",errorNameExist:"Bladwijzer bestaat al.",errorNameNull:"Ongeldige naam van bladwijzer.",editTip:"Bladwijzers bewerken",exitEditTip:"Bewerkingsmodus afsluiten",syncTip:"Synchroniseren",cardsTips:"Rasterweergave",listTips:"Lijstweergave",addBtn:"Toevoegen",deleteBtn:"Verwijderen",changeThumbnailTip:"Miniatuur wijzigen",
dragReorderTip:"Vasthouden en slepen om opnieuw te rangschikken",deleteBtnTip:"De bladwijzer verwijderen",editBtnTip:"De bladwijzer bewerken",withVisibility:"Met laagzichtbaarheid",searchBookmark:"Zoeken",bookmarksFromConfig:"Voorgeconfigureerde bladwijzers",bookmarksFromCache:"Plaatselijke tijdelijke bladwijzers",notice:"Mededeling",changeNoticeTips:"Wijzigingen worden alleen opgeslagen in de cache van uw browser. Synchronisatie tussen de widget en de configuratie ervan is losgekoppeld zodra u wijzigingen aanbrengt.",
syncNoticeTips:"Dit zal alle wijzigingen wissen en de geconfigureerde bladwijzers herstellen.",dontShowAgain:"Niet meer weergeven",saveVisibility:"Laagzichtbaarheid opslaan",_widgetLabel:"Bladwijzer",_localized:{}}}); | 250 | 539 | 0.831333 |
3d8500c3dde558898d84ae014344b87cd876ff77 | 6,158 | js | JavaScript | renderer/components/Home/Home.js | otech47/zap-desktop | 2ad4ea9fb609a76b5cb91cae794f314a1e4d83ba | [
"MIT"
] | null | null | null | renderer/components/Home/Home.js | otech47/zap-desktop | 2ad4ea9fb609a76b5cb91cae794f314a1e4d83ba | [
"MIT"
] | null | null | null | renderer/components/Home/Home.js | otech47/zap-desktop | 2ad4ea9fb609a76b5cb91cae794f314a1e4d83ba | [
"MIT"
] | null | null | null | import React from 'react'
import PropTypes from 'prop-types'
import { Redirect, Route, Switch, withRouter } from 'react-router-dom'
import { Box, Flex } from 'rebass/styled-components'
import { Bar, MainContent, Panel, Sidebar } from 'components/UI'
import ZapLogo from 'components/Icon/ZapLogo'
import CreateWalletButton from './CreateWalletButton'
import NoWallets from './NoWallets'
import WalletLauncher from './WalletLauncher'
import WalletsMenu from './WalletsMenu'
import WalletUnlocker from './WalletUnlocker'
const NoMatch = ({ history, wallets }) => (
<Flex alignItems="center" flexDirection="column" height="100%" justifyContent="center">
<NoWallets history={history} wallets={wallets} />
</Flex>
)
NoMatch.propTypes = {
history: PropTypes.object.isRequired,
wallets: PropTypes.array.isRequired,
}
class Home extends React.Component {
static propTypes = {
activeWallet: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
activeWalletSettings: PropTypes.object,
clearStartLndError: PropTypes.func.isRequired,
deleteWallet: PropTypes.func.isRequired,
generateLndConfigFromWallet: PropTypes.func.isRequired,
history: PropTypes.object.isRequired,
isLightningGrpcActive: PropTypes.bool.isRequired,
isNeutrinoRunning: PropTypes.bool.isRequired,
isStartingLnd: PropTypes.bool,
isUnlockingWallet: PropTypes.bool,
isWalletUnlockerGrpcActive: PropTypes.bool.isRequired,
lndConnect: PropTypes.string,
putWallet: PropTypes.func.isRequired,
setActiveWallet: PropTypes.func.isRequired,
setIsWalletOpen: PropTypes.func.isRequired,
setUnlockWalletError: PropTypes.func.isRequired,
showError: PropTypes.func.isRequired,
showNotification: PropTypes.func.isRequired,
startLnd: PropTypes.func.isRequired,
startLndError: PropTypes.object,
stopLnd: PropTypes.func.isRequired,
unlockWallet: PropTypes.func.isRequired,
unlockWalletError: PropTypes.string,
wallets: PropTypes.array.isRequired,
}
// If there is an active wallet ensure it is selected on mount.
componentDidMount() {
const { activeWallet, activeWalletSettings, history, setIsWalletOpen } = this.props
if (activeWallet && activeWalletSettings && history.location.pathname === '/home') {
history.push(`/home/wallet/${activeWallet}`)
}
setIsWalletOpen(false)
}
componentDidUpdate(prevProps) {
const { lndConnect, history } = this.props
if (lndConnect && lndConnect !== prevProps.lndConnect) {
history.push(`/onboarding`)
}
}
render() {
const {
history,
activeWallet,
deleteWallet,
startLnd,
startLndError,
isStartingLnd,
unlockWallet,
wallets,
setActiveWallet,
clearStartLndError,
showError,
stopLnd,
isNeutrinoRunning,
isLightningGrpcActive,
isWalletUnlockerGrpcActive,
setUnlockWalletError,
isUnlockingWallet,
unlockWalletError,
putWallet,
showNotification,
generateLndConfigFromWallet,
} = this.props
return (
<>
<Sidebar.medium pt={40}>
<Panel>
<Panel.Header mb={40} px={4}>
<ZapLogo height={28} width={28} />
</Panel.Header>
<Panel.Body sx={{ overflowY: 'overlay' }}>
<WalletsMenu
activeWallet={activeWallet}
setActiveWallet={setActiveWallet}
wallets={wallets}
/>
</Panel.Body>
<Panel.Footer>
<Bar variant="light" />
<Box px={4} py={2}>
<CreateWalletButton history={history} width={1} />
</Box>
</Panel.Footer>
</Panel>
</Sidebar.medium>
<MainContent pb={2} pl={5} pr={6} pt={4}>
<Switch>
<Route
exact
path="/home/wallet/:walletId"
render={({ match: { params } }) => {
const walletId = parseInt(params.walletId, 10)
const wallet = wallets.find(w => w.id === walletId)
if (!wallet) {
return <Redirect to="/home" />
}
return (
<WalletLauncher
key={wallet.id}
clearStartLndError={clearStartLndError}
deleteWallet={deleteWallet}
generateLndConfigFromWallet={generateLndConfigFromWallet}
isLightningGrpcActive={isLightningGrpcActive}
isNeutrinoRunning={isNeutrinoRunning}
isStartingLnd={isStartingLnd}
isWalletUnlockerGrpcActive={isWalletUnlockerGrpcActive}
putWallet={putWallet}
showError={showError}
showNotification={showNotification}
startLnd={startLnd}
startLndError={startLndError}
stopLnd={stopLnd}
wallet={wallet}
/>
)
}}
/>
<Route
exact
path="/home/wallet/:walletId/unlock"
render={({ match: { params } }) => {
const walletId = parseInt(params.walletId, 10)
const wallet = wallets.find(w => w.id === walletId)
if (!wallet) {
return <Redirect to="/home" />
}
return (
<WalletUnlocker
key={wallet.id}
isLightningGrpcActive={isLightningGrpcActive}
isUnlockingWallet={isUnlockingWallet}
setUnlockWalletError={setUnlockWalletError}
unlockWallet={unlockWallet}
unlockWalletError={unlockWalletError}
wallet={wallet}
/>
)
}}
/>
<Route render={() => <NoMatch history={history} wallets={wallets} />} />
</Switch>
</MainContent>
</>
)
}
}
export default withRouter(Home)
| 34.402235 | 89 | 0.585417 |
3d85191035a16a11c30bb7d9db9ef532c49406ec | 975 | js | JavaScript | src/components/icons/solid/VenusMars.js | MythicalFish/mythical.fish | c99209b42183a7e65d5c7384706838b925a8db0d | [
"MIT"
] | 2 | 2019-04-10T01:46:31.000Z | 2020-05-02T14:29:56.000Z | src/components/icons/solid/VenusMars.js | MythicalFish/mythical.fish | c99209b42183a7e65d5c7384706838b925a8db0d | [
"MIT"
] | null | null | null | src/components/icons/solid/VenusMars.js | MythicalFish/mythical.fish | c99209b42183a7e65d5c7384706838b925a8db0d | [
"MIT"
] | null | null | null | import React from 'react'
const VenusMars = props => (
<svg
fill='currentColor'
viewBox='0 0 576 512'
width='1em'
height='1em'
{...props}
>
<path d='M564 0h-79c-10.7 0-16 12.9-8.5 20.5l16.9 16.9-48.7 48.7C422.5 72.1 396.2 64 368 64c-33.7 0-64.6 11.6-89.2 30.9 14 16.7 25 36 32.1 57.1 14.5-14.8 34.7-24 57.1-24 44.1 0 80 35.9 80 80s-35.9 80-80 80c-22.3 0-42.6-9.2-57.1-24-7.1 21.1-18 40.4-32.1 57.1 24.5 19.4 55.5 30.9 89.2 30.9 79.5 0 144-64.5 144-144 0-28.2-8.1-54.5-22.1-76.7l48.7-48.7 16.9 16.9c2.4 2.4 5.4 3.5 8.4 3.5 6.2 0 12.1-4.8 12.1-12V12c0-6.6-5.4-12-12-12zM144 64C64.5 64 0 128.5 0 208c0 68.5 47.9 125.9 112 140.4V400H76c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h36v36c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12v-36h36c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12h-36v-51.6c64.1-14.6 112-71.9 112-140.4 0-79.5-64.5-144-144-144zm0 224c-44.1 0-80-35.9-80-80s35.9-80 80-80 80 35.9 80 80-35.9 80-80 80z' />
</svg>
)
export default VenusMars
| 60.9375 | 772 | 0.633846 |
3d8559cd2136c95cca047cc9789aa3e8252897fc | 15,122 | js | JavaScript | platforms/ios/eeuiApp/bundlejs/eeui/pages/module_ad_dialog.js | youngchou1997/department | 77bf1107912ae4e51e7042e88aed2f1ee95308b2 | [
"MIT"
] | null | null | null | platforms/ios/eeuiApp/bundlejs/eeui/pages/module_ad_dialog.js | youngchou1997/department | 77bf1107912ae4e51e7042e88aed2f1ee95308b2 | [
"MIT"
] | null | null | null | platforms/ios/eeuiApp/bundlejs/eeui/pages/module_ad_dialog.js | youngchou1997/department | 77bf1107912ae4e51e7042e88aed2f1ee95308b2 | [
"MIT"
] | null | null | null | // { "framework": "Vue"}
if(typeof app=="undefined"){app=weex}
if(typeof eeuiLog=="undefined"){var eeuiLog={_:function(t,e){var s=e.map(function(e){return e="[object object]"===Object.prototype.toString.call(e).toLowerCase()?JSON.stringify(e):e});if(typeof this.__m==='undefined'){this.__m=app.requireModule('debug')}this.__m.addLog(t,s)},debug:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("debug",e)},log:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("log",e)},info:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("info",e)},warn:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("warn",e)},error:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("error",e)}}}
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/pages/module_ad_dialog.vue?entry=true");
/******/ })
/************************************************************************/
/******/ ({
/***/ "../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/script-loader.js!../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/node_modules/babel-loader/lib/index.js!../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=script&index=0!./src/pages/module_ad_dialog.vue":
/*!****************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** /usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/script-loader.js!/usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/node_modules/babel-loader/lib!/usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=script&index=0!./src/pages/module_ad_dialog.vue ***!
\****************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var eeui = app.requireModule('eeui');
/* harmony default export */ __webpack_exports__["default"] = ({
methods: {
viewCode: function viewCode(str) {
this.openViewCode(str);
},
openAdDialog: function openAdDialog() {
eeui.adDialog("https://eeui.app/assets/images/testImage1.png", function (res) {
eeui.toast("状态:" + res.status);
});
}
}
});
/***/ }),
/***/ "../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-loader.js!../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-rewriter.js?id=data-v-ab7a3a56!../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=styles&index=0!./src/pages/module_ad_dialog.vue":
/*!**************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** /usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-loader.js!/usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-rewriter.js?id=data-v-ab7a3a56!/usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=styles&index=0!./src/pages/module_ad_dialog.vue ***!
\**************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = {
"app": {
"width": "750",
"flex": 1
},
"navbar": {
"width": "750",
"height": "100"
},
"title": {
"fontSize": "28",
"color": "#ffffff"
},
"iconr": {
"width": "100",
"height": "100",
"color": "#ffffff"
},
"content": {
"flex": 1,
"justifyContent": "center",
"alignItems": "center"
},
"button": {
"fontSize": "24",
"textAlign": "center",
"marginTop": "20",
"marginBottom": "20",
"paddingTop": "20",
"paddingBottom": "20",
"paddingLeft": "30",
"paddingRight": "30",
"color": "#ffffff",
"backgroundColor": "#00B4FF"
}
}
/***/ }),
/***/ "../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/template-compiler.js?id=data-v-ab7a3a56!../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=template&index=0!./src/pages/module_ad_dialog.vue":
/*!************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** /usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/template-compiler.js?id=data-v-ab7a3a56!/usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=template&index=0!./src/pages/module_ad_dialog.vue ***!
\************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('div', {
staticClass: ["app"]
}, [_c('navbar', {
staticClass: ["navbar"]
}, [_c('navbar-item', {
attrs: {
"type": "back"
}
}), _c('navbar-item', {
attrs: {
"type": "title"
}
}, [_c('text', {
staticClass: ["title"]
}, [_vm._v("广告弹窗")])]), _c('navbar-item', {
attrs: {
"type": "right"
},
on: {
"click": function($event) {
_vm.viewCode('module/adDialog')
}
}
}, [_c('icon', {
staticClass: ["iconr"],
attrs: {
"content": "md-code-working"
}
})], 1)], 1), _c('div', {
staticClass: ["content"]
}, [_c('text', {
staticClass: ["button"],
on: {
"click": _vm.openAdDialog
}
}, [_vm._v("打开广告弹窗")])])], 1)
},staticRenderFns: []}
module.exports.render._withStripped = true
/***/ }),
/***/ "./src/pages/module_ad_dialog.vue?entry=true":
/*!***************************************************!*\
!*** ./src/pages/module_ad_dialog.vue?entry=true ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var __vue_exports__, __vue_options__
var __vue_styles__ = []
/* styles */
__vue_styles__.push(__webpack_require__(/*! !../../../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-loader!../../../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-rewriter?id=data-v-ab7a3a56!../../../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector?type=styles&index=0!./module_ad_dialog.vue */ "../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-loader.js!../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-rewriter.js?id=data-v-ab7a3a56!../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=styles&index=0!./src/pages/module_ad_dialog.vue")
)
/* script */
__vue_exports__ = __webpack_require__(/*! !../../../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/script-loader!babel-loader!../../../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector?type=script&index=0!./module_ad_dialog.vue */ "../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/script-loader.js!../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/node_modules/babel-loader/lib/index.js!../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=script&index=0!./src/pages/module_ad_dialog.vue")
/* template */
var __vue_template__ = __webpack_require__(/*! !../../../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/template-compiler?id=data-v-ab7a3a56!../../../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector?type=template&index=0!./module_ad_dialog.vue */ "../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/template-compiler.js?id=data-v-ab7a3a56!../../../../../../usr/local/lib/node_modules/node/lib/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=template&index=0!./src/pages/module_ad_dialog.vue")
__vue_options__ = __vue_exports__ = __vue_exports__ || {}
if (
typeof __vue_exports__.default === "object" ||
typeof __vue_exports__.default === "function"
) {
if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {eeuiLog.error("named exports are not supported in *.vue files.")}
__vue_options__ = __vue_exports__ = __vue_exports__.default
}
if (typeof __vue_options__ === "function") {
__vue_options__ = __vue_options__.options
}
__vue_options__.__file = "/Users/zhouyang/study/android/weex/findfang/src/pages/module_ad_dialog.vue"
__vue_options__.render = __vue_template__.render
__vue_options__.staticRenderFns = __vue_template__.staticRenderFns
__vue_options__._scopeId = "data-v-ab7a3a56"
__vue_options__.style = __vue_options__.style || {}
__vue_styles__.forEach(function (module) {
for (var name in module) {
__vue_options__.style[name] = module[name]
}
})
if (typeof __register_static_styles__ === "function") {
__register_static_styles__(__vue_options__._scopeId, __vue_styles__)
}
module.exports = __vue_exports__
module.exports.el = 'true'
new Vue(module.exports)
/***/ })
/******/ }); | 46.529231 | 909 | 0.538751 |
3d85b880c75b0833183a9469bb30204704eeaf3c | 4,095 | js | JavaScript | frontend/src/core/editor/components/EditorMenu.js | Tratty/pontoon | ecb903d72f9274f02137b16669cc3c5859f6329c | [
"BSD-3-Clause"
] | 3 | 2020-01-27T12:26:20.000Z | 2022-02-03T09:56:02.000Z | frontend/src/core/editor/components/EditorMenu.js | texnoman/pontoon-src | 6b40ac229605e99966c3bdd1510b772c89d4de24 | [
"BSD-3-Clause"
] | 1 | 2021-03-24T12:33:03.000Z | 2021-03-24T12:50:19.000Z | frontend/src/core/editor/components/EditorMenu.js | texnoman/pontoon-src | 6b40ac229605e99966c3bdd1510b772c89d4de24 | [
"BSD-3-Clause"
] | 4 | 2020-01-26T21:28:43.000Z | 2021-06-10T15:25:19.000Z | /* @flow */
import * as React from 'react';
import { Localized } from '@fluent/react';
import './EditorMenu.css';
import * as editor from 'core/editor';
import * as user from 'core/user';
import * as unsavedchanges from 'modules/unsavedchanges';
import EditorMainAction from './EditorMainAction';
import type { EditorProps } from 'core/editor';
type Props = {
...EditorProps,
firstItemHook?: React.Node,
translationLengthHook?: React.Node,
};
/**
* Render the options to control an Editor.
*/
export default class EditorMenu extends React.Component<Props> {
render() {
const props = this.props;
return <menu className='editor-menu'>
{ props.firstItemHook }
<editor.FailedChecks
source={ props.editor.source }
user={ props.user }
isTranslator={ props.isTranslator }
errors={ props.editor.errors }
warnings={ props.editor.warnings }
resetFailedChecks={ props.resetFailedChecks }
sendTranslation={ props.sendTranslation }
updateTranslationStatus={ props.updateTranslationStatus }
/>
<unsavedchanges.UnsavedChanges />
{ !props.user.isAuthenticated ?
<Localized
id="editor-EditorMenu--sign-in-to-translate"
a={
<user.SignInLink url={ props.user.signInURL }></user.SignInLink>
}
>
<p className='banner'>
{ '<a>Sign in</a> to translate.' }
</p>
</Localized>
: (props.entity && props.entity.readonly) ?
<Localized
id="editor-EditorMenu--read-only-localization"
>
<p className='banner'>This is a read-only localization.</p>
</Localized>
:
<React.Fragment>
<editor.EditorSettings
settings={ props.user.settings }
updateSetting={ props.updateSetting }
/>
<editor.KeyboardShortcuts />
{ props.translationLengthHook }
<div className="actions">
<Localized
id="editor-EditorMenu--button-copy"
attrs={{ title: true }}
>
<button
className="action-copy"
onClick={ props.copyOriginalIntoEditor }
title="Copy From Source (Ctrl + Shift + C)"
>
Copy
</button>
</Localized>
<Localized
id="editor-EditorMenu--button-clear"
attrs={{ title: true }}
>
<button
className="action-clear"
onClick={ props.clearEditor }
title="Clear Translation (Ctrl + Shift + Backspace)"
>
Clear
</button>
</Localized>
<EditorMainAction
isRunningRequest={ props.editor.isRunningRequest }
isTranslator={ props.isTranslator }
forceSuggestions={ props.user.settings.forceSuggestions }
sameExistingTranslation={ props.sameExistingTranslation }
sendTranslation={ props.sendTranslation }
updateTranslationStatus={ props.updateTranslationStatus }
/>
</div>
</React.Fragment>
}
</menu>;
}
}
| 38.271028 | 88 | 0.446886 |
3d8731c2323e30472796a5301a74908d2c296df8 | 2,384 | js | JavaScript | Drive/resources/sap/ui/codeeditor/js/ace/snippets/coffee.js | jojeda10/ndoxx3 | 990b700c54692e79c55f3e9d57155e80fb47318a | [
"Apache-2.0"
] | 1 | 2019-10-28T13:47:53.000Z | 2019-10-28T13:47:53.000Z | Drive/resources/sap/ui/codeeditor/js/ace/snippets/coffee.js | jojeda10/ndoxx3 | 990b700c54692e79c55f3e9d57155e80fb47318a | [
"Apache-2.0"
] | 82 | 2020-06-25T09:45:01.000Z | 2022-03-31T09:35:31.000Z | Drive/resources/sap/ui/codeeditor/js/ace/snippets/coffee.js | jojeda10/ndoxx3 | 990b700c54692e79c55f3e9d57155e80fb47318a | [
"Apache-2.0"
] | null | null | null | ace.define("ace/snippets/coffee",["require","exports","module"],function(r,e,m){"use strict";e.snippetText="# Closure loop\nsnippet forindo\n for ${1:name} in ${2:array}\n do ($1) ->\n ${3:// body}\n# Array comprehension\nsnippet fora\n for ${1:name} in ${2:array}\n ${3:// body...}\n# Object comprehension\nsnippet foro\n for ${1:key}, ${2:value} of ${3:object}\n ${4:// body...}\n# Range comprehension (inclusive)\nsnippet forr\n for ${1:name} in [${2:start}..${3:finish}]\n ${4:// body...}\nsnippet forrb\n for ${1:name} in [${2:start}..${3:finish}] by ${4:step}\n ${5:// body...}\n# Range comprehension (exclusive)\nsnippet forrex\n for ${1:name} in [${2:start}...${3:finish}]\n ${4:// body...}\nsnippet forrexb\n for ${1:name} in [${2:start}...${3:finish}] by ${4:step}\n ${5:// body...}\n# Function\nsnippet fun\n (${1:args}) ->\n ${2:// body...}\n# Function (bound)\nsnippet bfun\n (${1:args}) =>\n ${2:// body...}\n# Class\nsnippet cla class ..\n class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`}\n ${2}\nsnippet cla class .. constructor: ..\n class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`}\n constructor: (${2:args}) ->\n ${3}\n\n ${4}\nsnippet cla class .. extends ..\n class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`} extends ${2:ParentClass}\n ${3}\nsnippet cla class .. extends .. constructor: ..\n class ${1:`substitute(Filename(), '\\(_\\|^\\)\\(.\\)', '\\u\\2', 'g')`} extends ${2:ParentClass}\n constructor: (${3:args}) ->\n ${4}\n\n ${5}\n# If\nsnippet if\n if ${1:condition}\n ${2:// body...}\n# If __ Else\nsnippet ife\n if ${1:condition}\n ${2:// body...}\n else\n ${3:// body...}\n# Else if\nsnippet elif\n else if ${1:condition}\n ${2:// body...}\n# Ternary If\nsnippet ifte\n if ${1:condition} then ${2:value} else ${3:other}\n# Unless\nsnippet unl\n ${1:action} unless ${2:condition}\n# Switch\nsnippet swi\n switch ${1:object}\n when ${2:value}\n ${3:// body...}\n\n# Log\nsnippet log\n console.log ${1}\n# Try __ Catch\nsnippet try\n try\n ${1}\n catch ${2:error}\n ${3}\n# Require\nsnippet req\n ${2:$1} = require '${1:sys}'${3}\n# Export\nsnippet exp\n ${1:root} = exports ? this\n";e.scope="coffee";});(function(){ace.require(["ace/snippets/coffee"],function(m){if(typeof module=="object"&&typeof exports=="object"&&module){module.exports=m;}});})();
| 1,192 | 2,383 | 0.584312 |
3d890bd43712b009bcd25756ebad63ee53b130b2 | 15,120 | js | JavaScript | learningmachines/searcher/static/searcher/dfr-browser/src/view/topic.js | ucdscenter/learning_machines_app | 0d4802f23db637b498c148828817421964821603 | [
"MIT"
] | null | null | null | learningmachines/searcher/static/searcher/dfr-browser/src/view/topic.js | ucdscenter/learning_machines_app | 0d4802f23db637b498c148828817421964821603 | [
"MIT"
] | null | null | null | learningmachines/searcher/static/searcher/dfr-browser/src/view/topic.js | ucdscenter/learning_machines_app | 0d4802f23db637b498c148828817421964821603 | [
"MIT"
] | null | null | null | /*global view, VIS, utils, d3 */
"use strict";
view.topic = function (p) {
var div = d3.select("div#topic_view");
// heading information
// -------------------
div.select("#topic_header").text(p.label);
// (later: nearby topics by J-S div or cor on log probs)
};
view.topic.remark = function (p) {
d3.select("#topic_view #topic_remark")
.text(VIS.percent_format(p.col_sum / p.total_tokens)
+ " of corpus");
};
view.topic.words = function (words) {
var trs, trs_enter;
trs = d3.select("table#topic_words tbody")
.selectAll("tr")
.data(words);
trs_enter = trs.enter().append("tr");
trs.exit().remove();
trs.on("click", function (w) {
view.dfb().set_view("/word/" + w.word);
});
trs_enter.append("td").classed("topic_word", true)
.append("a");
trs.select("td.topic_word a")
.attr("href", function (w) {
return "#/word/" + w.word;
})
.text(function (w) { return w.word + ": " + w.weight; });
view.weight_tds({
sel: trs,
enter: trs_enter,
w: function (w) { return w.weight / words[0].weight; }
});
};
view.topic.docs = function (p) {
var header_text, trs, trs_enter,
docs = p.docs;
if (p.condition !== undefined) {
header_text = ": ";
if (p.type !== "time") {
header_text += p.condition_name + " ";
}
header_text += p.key.display(p.condition);
// the clear-selected-condition button
d3.select("#topic_condition_clear")
.classed("disabled", false)
.on("click", function () {
d3.select(".selected_condition")
.classed("selected_condition", false);
view.dfb().set_view(view.topic.hash(p.t));
})
.classed("hidden", false);
} else {
header_text = "";
d3.select("#topic_condition_clear")
.classed("disabled", true);
}
d3.selectAll("#topic_docs span.topic_condition")
.text(header_text);
if (docs === undefined || docs.length === 0) {
d3.selectAll("#topic_docs .none")
.classed("hidden", false);
d3.select("#topic_docs table")
.classed("hidden", true);
return true;
}
d3.selectAll("#topic_docs .none")
.classed("hidden", true);
d3.select("#topic_docs table")
.classed("hidden", false);
trs = d3.select("#topic_docs tbody")
.selectAll("tr")
.data(docs);
trs_enter = trs.enter().append("tr");
trs.exit().remove();
trs_enter.append("td")
.append("a").classed("citation", true);
trs.select("a.citation")
.html(function (d, j) {
return p.citations[j];
});
trs.on("click", function (d) {
view.dfb().set_view("/doc/" + d.doc);
});
view.weight_tds({
sel: trs,
enter: trs_enter,
w: function (d) { return d.frac; },
frac: function (d) { return VIS.percent_format(d.frac); },
raw: p.proper ? undefined : function (d) { return d.weight; }
});
};
view.topic.conditional = function (p) {
var spec = utils.clone(VIS.topic_view);
spec.m.left = 90
spec.w = d3.select("#topic_conditional").node().clientWidth - 30 || spec.w;
spec.w = Math.max(spec.w, VIS.topic_view.w); // set a min. width
spec.w -= spec.m.left + spec.m.right;
spec.h = Math.floor(spec.w / VIS.topic_view.aspect)
- spec.m.top - spec.m.bottom;
// copy over conditional variable information to bar-step spec
spec.time.step = VIS.condition.spec;
p.svg = view.plot_svg("div#topic_plot", spec);
p.axes = true;
p.clickable = true;
p.spec = spec;
//console.log(p)
view.topic.conditional_barplot(p);
};
view.topic.conditional_barplot = function (param) {
if(Object.keys(param.data).length > 0){
var series,
step, w, w_click,
bar_offset, bar_offset_click,
scale_x,
scale_y,
bars, bars_enter,
bars_click,
axes, ax_label, tick_padding,
tip_text,
tx_duration = param.transition ? param.spec.tx_duration: 0,
svg = param.svg,
spec = param.spec;
series = param.data.keys().sort().map(function (y) {
return {
key: y,
x: param.key.invert(y),
y: param.data.get(y)
};
});
// roll-your-own rangeBands for time and continuous variables
if (param.type === "continuous") {
// find minimum-width step in domain series
series[0].w = Infinity;
step = series.reduce(function (acc, d) {
return {
x: d.x,
w: Math.min(d.x - acc.x, acc.w)
};
}).w;
delete series[0].w;
scale_x = d3.scale.linear()
.domain([series[0].x,
series[series.length - 1].x + step * spec.continuous.bar.w])
.range([0, spec.w]);
// .nice();
w = scale_x(series[0].x + step * spec.continuous.bar.w)
- scale_x(series[0].x);
bar_offset = -w / 2;
w_click = scale_x(series[0].x + step) - scale_x(series[0].x);
bar_offset_click = -w_click / 2;
tick_padding = w_click / 2;
} else if (param.type === "time") {
//.nice();
series = series.filter(function(d){
if(isNaN(parseInt(d.key))){
return false
}
if(parseInt(d.key) == 0){
return false
}
return true
})
scale_x = d3.time.scale.utc()
.domain([series[0].x,
d3.time[spec.time.bar.unit].utc.offset(
series[series.length - 1].x, spec.time.bar.w)
])
.range([0, spec.w]);
//console.log(d3.time[spec.time.bar.unit].utc.offset(series[0].x, spec.time.bar.w))
w = scale_x(d3.time[spec.time.bar.unit].utc.offset(
series[0].x, spec.time.bar.w))
- scale_x(series[0].x);
bar_offset = -w / 2;
w_click = scale_x(
d3.time[spec.time.step.unit].utc.offset(
series[0].x, spec.time.step.n))
- scale_x(series[0].x);
bar_offset_click = -w_click / 2;
tick_padding = w_click / 2;
} else {
// assume ordinal
scale_x = d3.scale.ordinal()
.domain(series.map(function (d) { return d.x; }))
.rangeRoundBands([0, spec.w], spec.ordinal.bar.w,
spec.ordinal.bar.w);
w = scale_x.rangeBand();
bar_offset = 0;
w_click = scale_x(series[1].x) - scale_x(series[0].x);
bar_offset_click = (w - w_click) / 2;
tick_padding = 3; // the d3 default
}
scale_y = d3.scale.linear()
.domain([0, d3.max(series, function (d) {
return d.y;
})])
.range([spec.h, 0])
.nice();
// axes
// ----
if (param.axes) {
axes = svg.selectAll("g.axis")
.data(["x", "y"]);
axes.enter().append("g").classed("axis", true)
.classed("x", function (v) {
return v === "x";
})
.classed("y", function (v) {
return v === "y";
})
.attr("transform", function (v) {
return v === "x" ? "translate(0," + spec.h + ")"
: "translate(-5, 0)";
});
axes.transition()
.duration(tx_duration)
.attr("transform", function (v) {
return v === "x" ? "translate(0," + spec.h + ")"
: undefined;
})
.each(function (v) {
var sel = d3.select(this),
ax = d3.svg.axis()
.scale(v === "x" ? scale_x : scale_y)
.orient(v === "x" ? "bottom" : "left");
if (v === "x") { // x axis
if (param.type === "time") {
if (spec.time.ticks.unit) {
ax.ticks(d3.time[spec.time.ticks.unit].utc,
spec.time.ticks.n);
} else if (typeof spec.time.ticks === "number") {
ax.ticks(spec.time.ticks);
}
} else {
ax.ticks(spec[param.type].ticks);
}
} else { // y axis
ax.tickSize(-spec.w)
.outerTickSize(0)
.tickFormat(VIS.percent_format)
.tickPadding(tick_padding)
.ticks(spec.ticks_y);
}
// redraw axis
sel.call(ax);
// set all y gridlines to minor except baseline
if (v === "y") {
sel.selectAll("g")
.filter(function (d) { return d > 0; })
.classed("minor", true);
}
});
ax_label = svg.selectAll("text.axis_label")
.data([1]);
ax_label.enter().append("text");
ax_label.classed("axis_label", true)
.attr("x", spec.w / 2)
.attr("y", spec.h + spec.m.bottom)
.attr("text-anchor", "middle")
.text(param.condition_name);
}
// bars
// ----
bars = svg.selectAll("g.topic_proportion")
.data(series, function (s) { return s.key; }); // keyed for txns
// for each x value, we will have two rects in a g: one showing the topic
// proportion and an invisible one for mouse interaction,
// following the example of http://bl.ocks.org/milroc/9842512
bars_enter = bars.enter().append("g")
.classed("topic_proportion", true)
.attr("transform", function (d) {
// new bars shouldn't transition out from the left,
// so preempt that
return "translate(" + scale_x(d.x) + ",0)";
});
bars.exit().remove(); // also removes child display and interact rects
if (param.clickable) {
// add the clickable bars, which are as high as the plot
// and a full step wide
bars_enter.append("rect").classed("interact", true);
bars_click = bars.select("rect.interact");
bars_click.transition()
.duration(tx_duration)
.attr("x", bar_offset_click)
.attr("y", 0)
.attr("width", w_click)
.attr("height", spec.h);
}
// set a selected bar if any
bars.classed("selected_condition", function (d) {
return d.key === param.condition;
});
// add the visible bars
bars_enter.append("rect").classed("display", true)
.style("fill", param.color)
.style("stroke", param.color);
// the g sets the x position of each pair of bars
bars.transition()
.duration(tx_duration)
.attr("transform", function (d) {
return "translate(" + scale_x(d.x) + ",0)";
})
.select("rect.display")
.attr("x", bar_offset)
.attr("y", function (d) {
return scale_y(d.y);
})
.attr("width", w)
.attr("height", function (d) {
return spec.h - scale_y(d.y);
});
if (param.clickable) {
bars.on("mouseover", function (d) {
d3.select(this).classed("hover", true);
})
.on("mouseout", function (d) {
d3.select(this).classed("hover", false);
});
// interactivity for the bars
// tooltip text
tip_text = function (d) { return param.key.display(d.key) + " : " + d3.format(",.2%")(d.y); };
// now set mouse event handlers
bars_click.on("mouseover", function (d) {
var g = d3.select(this.parentNode);
g.select(".display").classed("hover", true); // display bar
view.tooltip().text(tip_text(d));
view.tooltip().update_pos();
view.tooltip().show();
})
.on("mousemove", function (d) {
view.tooltip().update_pos();
})
.on("mouseout", function (d) {
d3.select(this.parentNode).select(".display") // display bar
.classed("hover", false);
view.tooltip().hide();
})
.on("click", function (d) {
if(d3.select(this.parentNode).classed("selected_condition")) {
d3.select(this.parentNode)
.classed("selected_condition", false);
view.tooltip().text(tip_text(d));
view.dfb().set_view(view.topic.hash(param.t));
} else {
// TODO selection of multiple conditions
// should use a brush http://bl.ocks.org/mbostock/6232537
d3.selectAll(".selected_condition")
.classed("selected_condition", false);
d3.select(this.parentNode)
.classed("selected_condition", true);
view.tooltip().text(tip_text(d));
view.dfb().set_view(
view.topic.hash(param.t) + "/" + d.key
);
}
});
}
}//ifthing
};
// Topic sorting rule: explicit labels over default "Topic NNN"
// achieved by ugly kludge
view.topic.sort_name = function (label) {
var nn = label.match(/^Topic\s(\d+)$/);
if (nn) {
return "zzz" + d3.format("05d")(+(nn[1]));
}
return label.replace(/^(the|a|an) /i, "").toLowerCase();
};
view.topic.dropdown = function (topics) {
var lis;
// Set up topic menu: remove loading message
d3.select("ul#topic_dropdown").selectAll("li.loading_message").remove();
// Add menu items
lis = d3.select("ul#topic_dropdown")
.selectAll("li")
.data(topics, function (t) {
return t.topic;
});
lis.enter().append("li").append("a")
.text(function (t) {
var words = t.words
.slice(0, VIS.overview_words)
.map(function (w) { return w.word; })
.join(" ");
return t.label + ": " + words;
})
.attr("href", function (t) {
return view.topic.link(t.topic);
});
lis.sort(function (a, b) {
return d3.ascending(view.topic.sort_name(a.label),
view.topic.sort_name(b.label));
});
lis.classed("hidden_topic", function (t) {
return t.hidden;
});
};
// Here we encode the fact that user-facing topic-view links use the 1-based
// topic index. dfb().topic_view() also expects the 1-based index.
view.topic.link = function (t) {
return "#" + view.topic.hash(t);
};
view.topic.hash = function (t) {
return "/topic/" + String(t + 1);
};
| 31.565762 | 102 | 0.49332 |
3d89288204f8fd3d36ea34667f70bdd4799d9d29 | 462 | js | JavaScript | src/components/IconManager/Icons/List.js | mindlab-vojo/vojo-component-library | 870198fdabd9aa95a689b9f0f2762fb776530fa9 | [
"MIT"
] | null | null | null | src/components/IconManager/Icons/List.js | mindlab-vojo/vojo-component-library | 870198fdabd9aa95a689b9f0f2762fb776530fa9 | [
"MIT"
] | 22 | 2021-05-31T16:56:05.000Z | 2021-06-29T21:12:46.000Z | src/components/IconManager/Icons/List.js | mindlab-vojo/vojo-component-library | 870198fdabd9aa95a689b9f0f2762fb776530fa9 | [
"MIT"
] | 1 | 2021-01-22T21:22:24.000Z | 2021-01-22T21:22:24.000Z | import React from 'react'
import PropTypes from 'prop-types'
const List = ({
width = "24",
height = "24",
fill
}) => {
return (
<svg width={width} height={height} viewBox="0 0 18 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7 12H11V10H7V12ZM0 0V2H18V0H0ZM3 7H15V5H3V7Z" fill={fill} />
</svg>
)
}
List.propTypes = {
width: PropTypes.string,
height: PropTypes.string,
fill: PropTypes.string
}
export default List
| 19.25 | 106 | 0.649351 |
3d8948f0155421247e6537b567f15d44d9c68f9e | 1,520 | js | JavaScript | js/performance.js | AcademyRS/Study | aba0f1de0c89c6e14d97b572b52eff144326a6fd | [
"MIT"
] | null | null | null | js/performance.js | AcademyRS/Study | aba0f1de0c89c6e14d97b572b52eff144326a6fd | [
"MIT"
] | null | null | null | js/performance.js | AcademyRS/Study | aba0f1de0c89c6e14d97b572b52eff144326a6fd | [
"MIT"
] | 3 | 2018-05-27T04:11:29.000Z | 2018-07-20T22:17:27.000Z | let tablegrade = document.querySelector('#table-grade');
if (localStorage['grade_table'] === undefined) {
save();
}
if (localStorage['grade_table'] !== undefined) {
window.onload = load();
}
tablegrade.addEventListener('click', function(e) {
let td = e.target;
if (td.tagName.toLowerCase() === 'td' && td.className === '') {
createinput(td);
}
});
function createinput(td) {
let input = document.createElement('input');
input.classList.add('input-grade');
input.type = 'number';
input.step = '0.1';
input.min = '0';
input.max = '10';
input.value = td.innerText;
td.innerText = '';
td.appendChild(input);
input.focus();
input.addEventListener('blur', function(e) {
if ((input.value >= 0 && input.value <= 10) || input.value == '') {
td.innerText = input.value;
save();
} else {
td.innerText = 10;
save();
}
input.remove();
});
}
function save() {
let tdlist = document.querySelectorAll('#table-grade tbody tr td');
let info = [];
for (let cont = 0; cont < tdlist.length; cont++) {
info[cont] = tdlist[cont].innerText;
}
localStorage['grade_table'] = JSON.stringify(info);
}
function load() {
let tdlist = document.querySelectorAll('#table-grade tbody tr td');
let localS = JSON.parse(localStorage['grade_table']);
for (let cont = 0; cont < tdlist.length; cont++) {
tdlist[cont].innerText = localS[cont];
}
}
| 27.142857 | 75 | 0.578289 |
3d89c147ba3d58a8be05cbe7507d08830a523855 | 502 | js | JavaScript | www/js/build/html.build.js | xudexa/code-editor | f847777dafa026e6ace9ad688ace1e77c7ec76e6 | [
"MIT"
] | null | null | null | www/js/build/html.build.js | xudexa/code-editor | f847777dafa026e6ace9ad688ace1e77c7ec76e6 | [
"MIT"
] | null | null | null | www/js/build/html.build.js | xudexa/code-editor | f847777dafa026e6ace9ad688ace1e77c7ec76e6 | [
"MIT"
] | null | null | null | (window.webpackJsonp=window.webpackJsonp||[]).push([[10],{544:function(n,e,t){"use strict";t.r(e),e.default={"index.html":'<!DOCTYPE html>\r\n<html lang="en">\r\n<head>\r\n <meta charset="UTF-8">\r\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\r\n <link rel="stylesheet" href="css/index.css">\r\n <script src="js/index.js"><\/script>\r\n <title><%name%></title>\r\n</head>\r\n<body>\r\n\t<h1><%name%></h1>\r\n</body>\r\n</html>',"css/index.css":"","js/index.js":""}}}]); | 502 | 502 | 0.631474 |
3d8a36497172295350740935e27cb3c1ec93d70a | 6,680 | js | JavaScript | src/js/models/v2/award/BaseContract.js | millerjoey975/usaspending-website | 30716dfe2796d725ccc24c421104e61cc7826127 | [
"CC0-1.0"
] | 152 | 2016-08-17T14:45:54.000Z | 2022-03-10T03:54:37.000Z | src/js/models/v2/award/BaseContract.js | millerjoey975/usaspending-website | 30716dfe2796d725ccc24c421104e61cc7826127 | [
"CC0-1.0"
] | 478 | 2016-10-17T19:44:46.000Z | 2022-03-31T14:23:30.000Z | src/js/models/v2/award/BaseContract.js | millerjoey975/usaspending-website | 30716dfe2796d725ccc24c421104e61cc7826127 | [
"CC0-1.0"
] | 49 | 2016-12-17T22:24:23.000Z | 2022-03-06T22:08:19.000Z | /**
* BaseContract.js
* Created by David Trinh 10/9/18
*/
import * as MoneyFormatter from 'helpers/moneyFormatter';
import * as pscHelper from 'helpers/pscHelper';
import CoreLocation from 'models/v2/CoreLocation';
import BaseAwardRecipient from './BaseAwardRecipient';
import BaseParentAwardDetails from './BaseParentAwardDetails';
import CoreAwardAgency from './CoreAwardAgency';
import BaseContractAdditionalDetails from './additionalDetails/BaseContractAdditionalDetails';
import CoreAward from './CoreAward';
import CoreExecutiveDetails from './CoreExecutiveDetails';
import CorePeriodOfPerformance from './CorePeriodOfPerformance';
const BaseContract = Object.create(CoreAward);
BaseContract.populate = function populate(data) {
// reformat some fields that are required by the CoreAward
const coreData = {
id: data.id,
generatedId: data.generated_unique_award_id,
type: data.type,
typeDescription: data.type_description,
description: data.description,
category: data.category,
subawardTotal: data.total_subaward_amount,
subawardCount: data.subaward_count,
totalObligation: data.total_obligation,
baseExercisedOptions: data.base_exercised_options,
dateSigned: data.date_signed,
baseAndAllOptions: data.base_and_all_options,
naics: data.naics_hierarchy,
psc: Object.entries(data.psc_hierarchy).reduce(pscHelper.deducePscType, pscHelper.emptyHierarchy),
fileC: {
obligations: data.account_obligations_by_defc,
outlays: data.account_outlays_by_defc
}
};
this.populateCore(coreData);
if (data.recipient) {
const recipient = Object.create(BaseAwardRecipient);
recipient.populate(data.recipient);
this.recipient = recipient;
}
if (data.place_of_performance) {
const placeOfPerformanceData = {
city: data.place_of_performance.city_name,
county: data.place_of_performance.county_name,
stateCode: data.place_of_performance.state_code,
state: data.place_of_performance.state_code,
province: data.place_of_performance.foreign_province,
zip5: data.place_of_performance.zip5,
zip4: data.place_of_performance.zip4,
congressionalDistrict: data.place_of_performance.congressional_code,
country: data.place_of_performance.country_name,
countryCode: data.place_of_performance.location_country_code
};
const placeOfPerformance = Object.create(CoreLocation);
placeOfPerformance.populateCore(placeOfPerformanceData);
this.placeOfPerformance = placeOfPerformance;
}
if (data.period_of_performance) {
const periodOfPerformanceData = {
startDate: data.period_of_performance.start_date,
endDate: data.period_of_performance.end_date,
lastModifiedDate: data.period_of_performance.last_modified_date,
potentialEndDate: data.period_of_performance.potential_end_date
};
const periodOfPerformance = Object.create(CorePeriodOfPerformance);
periodOfPerformance.populateCore(periodOfPerformanceData);
this.periodOfPerformance = periodOfPerformance;
}
if (data.awarding_agency) {
const awardingAgencyData = {
id: data.awarding_agency.id,
hasAgencyPage: data.awarding_agency.has_agency_page,
toptierName: data.awarding_agency.toptier_agency.name,
toptierAbbr: data.awarding_agency.toptier_agency.abbreviation || '',
subtierName: data.awarding_agency.subtier_agency.name,
subtierAbbr: data.awarding_agency.subtier_agency.abbreviation || '',
officeName: data.awarding_agency.office_agency_name
};
const awardingAgency = Object.create(CoreAwardAgency);
awardingAgency.populateCore(awardingAgencyData);
this.awardingAgency = awardingAgency;
}
else {
this.awardingAgency = {};
}
if (data.funding_agency) {
const fundingAgencyData = {
id: data.funding_agency.id,
hasAgencyPage: data.funding_agency.has_agency_page,
toptierName: data.funding_agency.toptier_agency.name,
toptierAbbr: data.funding_agency.toptier_agency.abbreviation || '',
subtierName: data.funding_agency.subtier_agency.name,
subtierAbbr: data.funding_agency.subtier_agency.abbreviation || '',
officeName: data.funding_agency.office_agency_name
};
const fundingAgency = Object.create(CoreAwardAgency);
fundingAgency.populateCore(fundingAgencyData);
this.fundingAgency = fundingAgency;
}
else {
this.fundingAgency = {};
}
if (data.latest_transaction_contract_data) {
const additionalDetails = Object.create(BaseContractAdditionalDetails);
additionalDetails.populate(data.latest_transaction_contract_data);
this.additionalDetails = additionalDetails;
}
const parentAwardDetails = Object.create(BaseParentAwardDetails);
parentAwardDetails.populateCore(data.parent_award || {});
this.parentAwardDetails = parentAwardDetails;
const executiveDetails = Object.create(CoreExecutiveDetails);
executiveDetails.populateCore(data.executive_details);
this.executiveDetails = executiveDetails;
this.pricing = data.latest_transaction_contract_data || '--';
this._amount = parseFloat(data.base_and_all_options) || 0;
this.piid = data.piid || '';
};
// getter functions
Object.defineProperty(BaseContract, 'amount', {
get() {
if (this._obligation >= MoneyFormatter.unitValues.MILLION) {
const units = MoneyFormatter.calculateUnitForSingleValue(this._amount);
return `${MoneyFormatter.formatMoneyWithPrecision(this._amount / units.unit, 2)} ${units.longLabel}`;
}
return MoneyFormatter.formatMoneyWithPrecision(this._amount, 0);
}
});
Object.defineProperty(BaseContract, 'amountFormatted', {
get() {
return MoneyFormatter.formatMoney(this._amount);
}
});
Object.defineProperty(BaseContract, 'remaining', {
get() {
const remaining = this._amount - this._obligation;
if (remaining >= MoneyFormatter.unitValues.MILLION) {
const units = MoneyFormatter.calculateUnitForSingleValue(remaining);
return `${MoneyFormatter.formatMoneyWithPrecision(remaining / units.unit, 2)} ${units.longLabel}`;
}
return MoneyFormatter.formatMoneyWithPrecision(remaining, 0);
}
});
export default BaseContract;
| 40.981595 | 113 | 0.705988 |
3d8a74aec90c2c2fdbc822fc38fd5cde0c2939c0 | 863 | js | JavaScript | app/features/config/index.js | digitalterrorist/_meet-electron | 92d9082a32812e59de9fe51e0559ca0725d4178a | [
"Apache-2.0"
] | 1 | 2020-04-20T17:49:47.000Z | 2020-04-20T17:49:47.000Z | app/features/config/index.js | digitalterrorist/_meet-electron | 92d9082a32812e59de9fe51e0559ca0725d4178a | [
"Apache-2.0"
] | null | null | null | app/features/config/index.js | digitalterrorist/_meet-electron | 92d9082a32812e59de9fe51e0559ca0725d4178a | [
"Apache-2.0"
] | null | null | null |
export default {
/**
* The URL with extra information about the app / service.
*/
aboutURL: 'https://meet.digitalterrorist.de/what-is-_meet/',
/**
* The URL to the source code repository.
*/
sourceURL: 'https://github.com/digitalterrorist/_meet-electron',
/**
* Application name.
*/
appName: '_meet',
/**
* The default server URL of Jitsi Meet Deployment that will be used.
*/
defaultServerURL: 'https://meet.digitalterrorist.de',
/**
* URL to send feedback.
*/
feedbackURL: 'mailto:noreply@digitalterrorist.de',
/**
* The URL of Privacy Policy Page.
*/
privacyPolicyURL: 'https://meet.digitalterrorist.de/privacy',
/**
* The URL of Terms and Conditions Page.
*/
termsAndConditionsURL: 'https://meet.digitalterrorist.de/terms'
};
| 22.710526 | 73 | 0.61066 |
3d8a98e56f239bcc21c63a84f45b8b9df907c123 | 2,133 | js | JavaScript | src/v1/endpoints/items/index.js | ekpo-d/cp-api-javascript-client | 061496cb14e8d989d0b886ed2393874918303a30 | [
"MIT"
] | 1 | 2020-10-12T19:00:26.000Z | 2020-10-12T19:00:26.000Z | src/v1/endpoints/items/index.js | ekpo-d/cp-api-javascript-client | 061496cb14e8d989d0b886ed2393874918303a30 | [
"MIT"
] | null | null | null | src/v1/endpoints/items/index.js | ekpo-d/cp-api-javascript-client | 061496cb14e8d989d0b886ed2393874918303a30 | [
"MIT"
] | null | null | null | import express from 'express';
import validate from 'is-express-schema-valid';
import Item from '../../models/Item';
import errors from '../../../utils/errors';
import validateAccessToken from '../../../middleware/validateAccessToken';
import validateUserRole from '../../../middleware/validateUserRole';
import { itemSchema } from './schemas';
export default function () {
var router = express.Router();
router.post('/',
validateAccessToken,
validateUserRole('artist'),
validate(itemSchema),
createItem,
returnItem
);
router.get('/:id',
validateAccessToken,
findItemById,
returnItem
);
router.put('/:id',
validateAccessToken,
validateUserRole('artist'),
validate(itemSchema),
findItemById,
updateItem,
returnItem
);
router.delete('/:id',
validateAccessToken,
validateUserRole('artist'),
findItemById,
deleteItem
);
async function createItem (req, res, next) {
try {
const itemData = Object.assign({}, req.body, {owner: req.email});
req.item = await Item.create(itemData);
next();
} catch (err) {
next(err);
}
}
async function findItemById (req, res, next) {
try {
req.item = await Item.findById(req.params.id);
if (!req.item) {
return next(new errors.NotFound('Item not found'));
}
next();
} catch (err) {
next(err);
}
}
async function updateItem (req, res, next) {
try {
req.item = await Item.update(req.item, req.body);
next();
} catch (err) {
next(err);
}
}
async function deleteItem (req, res, next) {
try {
await Item.remove(req.params.id);
res.sendStatus(204);
} catch (err) {
next(err);
}
}
function returnItem (req, res) {
res.json(Item.transformResponse(req.item));
}
return router;
}
| 23.43956 | 77 | 0.533521 |
3d8ac5e7d91e0ea1fb95c24c7abf074dd4dfa471 | 41 | js | JavaScript | database/l2/s0-stop.js | vladikoff/snippets | 573ec4c2760fdb7f2af60f39f3b521da8416fbf8 | [
"Apache-2.0",
"MIT"
] | 2 | 2015-03-04T06:42:20.000Z | 2015-11-09T00:49:45.000Z | database/l2/s0-stop.js | vladikoff/snippets | 573ec4c2760fdb7f2af60f39f3b521da8416fbf8 | [
"Apache-2.0",
"MIT"
] | null | null | null | database/l2/s0-stop.js | vladikoff/snippets | 573ec4c2760fdb7f2af60f39f3b521da8416fbf8 | [
"Apache-2.0",
"MIT"
] | null | null | null | $( "xoxo xoxo-l8s0" ).levelApp80("stop"); | 41 | 41 | 0.634146 |
3d8ba879b934bee0be67295bca20b1b5480355b1 | 291 | js | JavaScript | packages/material-ui-icons/src/HeadphonesBatterySharp.js | silver-snoopy/material-ui | 917a3ddb8c72651fdbd4d35b1cd48ce9a06f8139 | [
"MIT"
] | 8 | 2021-03-18T08:41:32.000Z | 2021-04-19T10:24:50.000Z | packages/material-ui-icons/src/HeadphonesBatterySharp.js | Hypermona/material-ui | 9ff8d1627016ee2eb3bded3dd55bccebe8f3a306 | [
"MIT"
] | 129 | 2021-05-05T15:07:04.000Z | 2022-03-27T02:51:27.000Z | packages/material-ui-icons/src/HeadphonesBatterySharp.js | danncortes/material-ui | 1eea9427971f716bd7fd17401d918841a9bd749e | [
"MIT"
] | 1 | 2021-03-25T23:57:05.000Z | 2021-03-25T23:57:05.000Z | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M20 7V6h-2v1h-2v11h6V7zM8 6c-3.31 0-6 2.69-6 6v6h4v-5H3.5v-1c0-2.48 2.02-4.5 4.5-4.5s4.5 2.02 4.5 4.5v1H10v5h4v-6c0-3.31-2.69-6-6-6z" />
, 'HeadphonesBatterySharp');
| 41.571429 | 147 | 0.714777 |
3d8bddd655d5d20ee4899b0571059c97e7170437 | 3,374 | js | JavaScript | clientB.js | SamDecrock/node-tcp-hole-punching | ace5311e92eb2e20fcb2106148b7455638249d91 | [
"MIT"
] | 60 | 2016-04-06T06:03:03.000Z | 2022-01-03T15:31:24.000Z | clientB.js | SamDecrock/node-tcp-hole-punching | ace5311e92eb2e20fcb2106148b7455638249d91 | [
"MIT"
] | 9 | 2016-04-15T16:39:38.000Z | 2021-07-14T10:39:58.000Z | clientB.js | SamDecrock/node-tcp-hole-punching | ace5311e92eb2e20fcb2106148b7455638249d91 | [
"MIT"
] | 26 | 2016-03-27T16:51:56.000Z | 2021-12-11T05:32:26.000Z | #!/usr/bin/env node
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// based on http://www.bford.info/pub/net/p2pnat/index.html
var addressOfS = 'x.x.x.x'; // replace this with the IP of the server running publicserver.js
var portOfS = 9999;
var socketToS;
var tunnelEstablished = false;
function connectToS () {
console.log('> (B->S) connecting to S');
socketToS = require('net').createConnection({host : addressOfS, port : portOfS}, function () {
console.log('> (B->S) connected to S via', socketToS.localAddress, socketToS.localPort);
// letting local address and port know to S so it can be can be sent to client A:
socketToS.write(JSON.stringify({
name: 'B',
localAddress: socketToS.localAddress,
localPort: socketToS.localPort
}));
});
socketToS.on('data', function (data) {
console.log('> (B->S) response from S:', data.toString());
var connectionDetails = JSON.parse(data.toString());
if(connectionDetails.name == 'B') {
// own connection details, only used to display the connection to the server in console:
console.log("");
console.log('> (B)', socketToS.localAddress + ':' + socketToS.localPort, '===> (NAT of B)', connectionDetails.remoteAddress + ':' + connectionDetails.remotePort, '===> (S)', socketToS.remoteAddress + ':' + socketToS.remotePort);
console.log("");
}
if(connectionDetails.name == 'A') {
console.log('> (B) time to listen on port used to connect to S ('+socketToS.localPort+')');
listen(socketToS.localAddress, socketToS.localPort);
// try connecting to A directly:
connectTo(connectionDetails.remoteAddress, connectionDetails.remotePort);
}
});
socketToS.on('end', function () {
console.log('> (B->S) connection closed.');
});
socketToS.on('error', function (err) {
console.log('> (B->S) connection closed with err:', err.code);
});
}
connectToS();
function connectTo (ip, port) {
if(tunnelEstablished) return;
console.log('> (B->A) connecting to A: ===> (A)', ip + ":" + port);
var c = require('net').createConnection({host : ip, port : port}, function () {
console.log('> (B->A) Connected to A via', ip + ":" + port);
tunnelEstablished = true;
});
c.on('data', function (data) {
console.log('> (B->A) data from A:', data.toString());
});
c.on('end', function () {
console.log('> (B->A) connection closed.');
});
c.on('error', function (err) {
console.log('> (B->A) connection closed with err:', err.code);
setTimeout(function () {
connectTo(ip, port);
},500);
});
}
var tunnelSocket = null;
function listen (ip, port) {
var server = require('net').createServer(function (socket) {
tunnelSocket = socket;
console.log('> (B) someone connected, it\s:', socket.remoteAddress, socket.remotePort);
socket.write("Hello there NAT traversal man, you are connected to B!");
tunnelEstablished = true;
readStuffFromCommandLineAndSendToA();
});
server.listen(port, ip, function (err) {
if(err) return console.log(err);
console.log('> (B) listening on ', ip + ":" + port);
});
}
function readStuffFromCommandLineAndSendToA () {
if(!tunnelSocket) return;
rl.question('Say something to A:', function (stuff) {
tunnelSocket.write(stuff);
readStuffFromCommandLineAndSendToA();
});
}
| 28.352941 | 231 | 0.655305 |
3d8c1e9ca17ed2a0385cc9da449101cb71386731 | 101 | js | JavaScript | resources/lang/en/error.js | jcmlumacad/oxford-app | 8faf68dbc4be9101a70b2b3c9a49f480b03bb17a | [
"MIT"
] | 2 | 2017-10-26T02:29:00.000Z | 2017-11-24T08:41:44.000Z | resources/lang/en/error.js | TMJPEngineering/mevn-stack-framework | 5214937ae3d13d492ea78c7d38e948b3629b34fb | [
"MIT"
] | 16 | 2017-12-04T05:24:14.000Z | 2018-05-21T01:35:45.000Z | resources/lang/en/error.js | jcmlumacad/oxford-app | 8faf68dbc4be9101a70b2b3c9a49f480b03bb17a | [
"MIT"
] | 1 | 2017-10-26T02:29:03.000Z | 2017-10-26T02:29:03.000Z | module.exports = {
400: 'Bad request',
403: 'Forbidden',
500: 'Internal server error'
};
| 16.833333 | 32 | 0.594059 |
3d8c41855093a6fd8ad58cac4ff0301eeafc91f6 | 602 | js | JavaScript | test/Manager.test.js | ramandeeppatwar/team-profile-generator | a7a09854a5f00a005c9095bdc21d3612f837d036 | [
"MIT"
] | null | null | null | test/Manager.test.js | ramandeeppatwar/team-profile-generator | a7a09854a5f00a005c9095bdc21d3612f837d036 | [
"MIT"
] | null | null | null | test/Manager.test.js | ramandeeppatwar/team-profile-generator | a7a09854a5f00a005c9095bdc21d3612f837d036 | [
"MIT"
] | null | null | null | const Manager = require("../lib/Manager");
test("Can set office number using constructor argument", () => {
const testValue = 100;
const e = new Manager("officeNum", 1, "test@test.com", testValue);
});
test('getRole() should return "Manager"', () => {
const testValue = "Manager";
const e = new Manager("John Doe", 1, "test@test.com", 100);
expect(e.getRole()).toBe(testValue);
});
test("Can get office number using getOffice() method", () => {
const testValue = 100;
const e = new Manager("John Doe", 1, "test@test.com", testValue);
expect(e.getOfficeNumber()).toBe(testValue);
});
| 31.684211 | 68 | 0.651163 |
3d8c448ce1976014728326d408327e8dc995f704 | 416 | js | JavaScript | test/mjsunit/lazy-inner-functions.js | isabella232/v8 | 30ef8e33f3a199a27ca8512bcee314c9522d03f6 | [
"BSD-3-Clause"
] | 22 | 2016-07-28T03:25:31.000Z | 2022-02-19T02:51:14.000Z | test/mjsunit/lazy-inner-functions.js | nodejs/v8 | 30ef8e33f3a199a27ca8512bcee314c9522d03f6 | [
"BSD-3-Clause"
] | 10 | 2016-09-30T14:57:49.000Z | 2017-06-30T12:56:01.000Z | test/mjsunit/lazy-inner-functions.js | isabella232/v8 | 30ef8e33f3a199a27ca8512bcee314c9522d03f6 | [
"BSD-3-Clause"
] | 23 | 2016-08-03T17:43:32.000Z | 2021-03-04T17:09:00.000Z | // Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(function TestLazyInnerFunctionCallsEval() {
var i = (function eager_outer() {
var a = 41; // Should be context-allocated
function lazy_inner() {
return eval("a");
}
return lazy_inner;
})();
assertEquals(41, i());
})();
| 27.733333 | 73 | 0.665865 |
3d8c6b061f544170f66b1c2a064c8b7251d73064 | 386 | js | JavaScript | server/graphs.js | adrienbrault/boardee | 0d634254ee014a5a4e271299b120d21fd9e280be | [
"MIT"
] | 2 | 2016-08-07T07:14:49.000Z | 2016-12-02T19:48:44.000Z | server/graphs.js | adrienbrault/boardee | 0d634254ee014a5a4e271299b120d21fd9e280be | [
"MIT"
] | null | null | null | server/graphs.js | adrienbrault/boardee | 0d634254ee014a5a4e271299b120d21fd9e280be | [
"MIT"
] | null | null | null | Meteor.methods({
graphDelete: function (_id) {
if (!isAdmin()) {
throw new Meteor.Error(403, 'You need to be an admin to delete graphs.');
}
Graphs.remove({_id: _id});
Dashboards.update({}, {
$pull: {
graphs: {
_id: _id
}
}
}, {multi: true});
}
});
| 22.705882 | 85 | 0.406736 |
3d8c8ace6d48946c8021c82914f436f7c5e90a14 | 7,497 | js | JavaScript | releases/0.12.1/docs/reference/models/bokeh-plot-ab20050bb9c716648ad6cef0f1de50e1.js | Daniel-Mietchen/docs.bokeh.org | 5aab9ea64e7b6f9267e356bb6920e0342260444d | [
"BSD-3-Clause"
] | null | null | null | releases/0.12.1/docs/reference/models/bokeh-plot-ab20050bb9c716648ad6cef0f1de50e1.js | Daniel-Mietchen/docs.bokeh.org | 5aab9ea64e7b6f9267e356bb6920e0342260444d | [
"BSD-3-Clause"
] | null | null | null | releases/0.12.1/docs/reference/models/bokeh-plot-ab20050bb9c716648ad6cef0f1de50e1.js | Daniel-Mietchen/docs.bokeh.org | 5aab9ea64e7b6f9267e356bb6920e0342260444d | [
"BSD-3-Clause"
] | null | null | null | document.addEventListener("DOMContentLoaded", function(event) {
(function(global) {
function now() {
return new Date();
}
var force = "";
if (typeof (window._bokeh_onload_callbacks) === "undefined" || force !== "") {
window._bokeh_onload_callbacks = [];
window._bokeh_is_loading = undefined;
}
function run_callbacks() {
window._bokeh_onload_callbacks.forEach(function(callback) { callback() });
delete window._bokeh_onload_callbacks
console.info("Bokeh: all callbacks have finished");
}
function load_libs(js_urls, callback) {
window._bokeh_onload_callbacks.push(callback);
if (window._bokeh_is_loading > 0) {
console.log("Bokeh: BokehJS is being loaded, scheduling callback at", now());
return null;
}
if (js_urls == null || js_urls.length === 0) {
run_callbacks();
return null;
}
console.log("Bokeh: BokehJS not loaded, scheduling load and callback at", now());
window._bokeh_is_loading = js_urls.length;
for (var i = 0; i < js_urls.length; i++) {
var url = js_urls[i];
var s = document.createElement('script');
s.src = url;
s.async = false;
s.onreadystatechange = s.onload = function() {
window._bokeh_is_loading--;
if (window._bokeh_is_loading === 0) {
console.log("Bokeh: all BokehJS libraries loaded");
run_callbacks()
}
};
s.onerror = function() {
console.warn("failed to load library " + url);
};
console.log("Bokeh: injecting script tag for BokehJS library: ", url);
document.getElementsByTagName("head")[0].appendChild(s);
}
};var element = document.getElementById("c126e29c-be83-48cb-a14d-6ce708c79f77");
if (element == null) {
console.log("Bokeh: ERROR: autoload.js configured with elementid 'c126e29c-be83-48cb-a14d-6ce708c79f77' but no matching script tag was found. ")
return false;
}
var js_urls = ['https://cdn.bokeh.org/bokeh/release/bokeh-0.12.1.min.js', 'https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.1.min.js', 'https://cdn.bokeh.org/bokeh/release/bokeh-compiler-0.12.1.min.js'];
var inline_js = [
function(Bokeh) {
Bokeh.set_log_level("info");
},
function(Bokeh) {
Bokeh.$(function() {
var docs_json = {"57f42173-7e02-406c-b448-1d12d768f56d":{"roots":{"references":[{"attributes":{},"id":"0507c0f9-837f-4856-8846-e9e700dd8b14","type":"BasicTickFormatter"},{"attributes":{"dimension":1,"plot":{"id":"04dde09d-3705-4bde-8cb7-bdb336ad5d03","type":"Plot"},"ticker":{"id":"16c854ec-2a5f-4b5d-9d24-5ef77b71f56f","type":"BasicTicker"}},"id":"2d6c1738-c7f2-4caa-9fff-9ba52c59dc2a","type":"Grid"},{"attributes":{"formatter":{"id":"0507c0f9-837f-4856-8846-e9e700dd8b14","type":"BasicTickFormatter"},"plot":{"id":"04dde09d-3705-4bde-8cb7-bdb336ad5d03","type":"Plot"},"ticker":{"id":"16c854ec-2a5f-4b5d-9d24-5ef77b71f56f","type":"BasicTicker"}},"id":"401d3009-f24b-4842-acb7-f4af3fb0875f","type":"LinearAxis"},{"attributes":{},"id":"57e8afb3-5ae0-4fc4-9162-bffc9af039be","type":"ToolEvents"},{"attributes":{},"id":"e5c958c0-3823-4fa3-9393-2929af011db3","type":"BasicTicker"},{"attributes":{"below":[{"id":"e8fc3491-5af0-471e-80e9-51a3e57f11a4","type":"LinearAxis"}],"h_symmetry":false,"left":[{"id":"401d3009-f24b-4842-acb7-f4af3fb0875f","type":"LinearAxis"}],"min_border":0,"plot_height":300,"plot_width":300,"renderers":[{"id":"4bafdfae-7d5f-4b42-94e1-51f0f56b31d7","type":"GlyphRenderer"},{"id":"e8fc3491-5af0-471e-80e9-51a3e57f11a4","type":"LinearAxis"},{"id":"401d3009-f24b-4842-acb7-f4af3fb0875f","type":"LinearAxis"},{"id":"61f988b7-3a8f-4786-bed7-ac3ba55c66d2","type":"Grid"},{"id":"2d6c1738-c7f2-4caa-9fff-9ba52c59dc2a","type":"Grid"}],"title":null,"tool_events":{"id":"57e8afb3-5ae0-4fc4-9162-bffc9af039be","type":"ToolEvents"},"toolbar":{"id":"02f0c4a0-0798-4b8a-8e02-54730cb2fd0d","type":"Toolbar"},"toolbar_location":null,"x_range":{"id":"df55a7d8-446d-482d-a32b-f6f02e165e7d","type":"DataRange1d"},"y_range":{"id":"4474c76c-8082-4d79-ab9f-008f5a42f42c","type":"DataRange1d"}},"id":"04dde09d-3705-4bde-8cb7-bdb336ad5d03","type":"Plot"},{"attributes":{"fill_color":{"value":"#b3de69"},"top":{"field":"top"},"width":{"value":0.5},"x":{"field":"x"}},"id":"7906132f-3f7b-4a62-b870-6ebc07e76f3c","type":"VBar"},{"attributes":{"active_drag":"auto","active_scroll":"auto","active_tap":"auto"},"id":"02f0c4a0-0798-4b8a-8e02-54730cb2fd0d","type":"Toolbar"},{"attributes":{},"id":"16c854ec-2a5f-4b5d-9d24-5ef77b71f56f","type":"BasicTicker"},{"attributes":{"callback":null,"column_names":["x","top"],"data":{"top":[4.0,2.25,1.0,0.25,0.0,0.25,1.0,2.25,4.0],"x":[-2.0,-1.5,-1.0,-0.5,0.0,0.5,1.0,1.5,2.0]}},"id":"921ccb44-59e4-4121-978f-28d7b464b578","type":"ColumnDataSource"},{"attributes":{"callback":null},"id":"df55a7d8-446d-482d-a32b-f6f02e165e7d","type":"DataRange1d"},{"attributes":{},"id":"d72c0b44-55f4-41ca-8744-7040c070e77e","type":"BasicTickFormatter"},{"attributes":{"formatter":{"id":"d72c0b44-55f4-41ca-8744-7040c070e77e","type":"BasicTickFormatter"},"plot":{"id":"04dde09d-3705-4bde-8cb7-bdb336ad5d03","type":"Plot"},"ticker":{"id":"e5c958c0-3823-4fa3-9393-2929af011db3","type":"BasicTicker"}},"id":"e8fc3491-5af0-471e-80e9-51a3e57f11a4","type":"LinearAxis"},{"attributes":{"plot":{"id":"04dde09d-3705-4bde-8cb7-bdb336ad5d03","type":"Plot"},"ticker":{"id":"e5c958c0-3823-4fa3-9393-2929af011db3","type":"BasicTicker"}},"id":"61f988b7-3a8f-4786-bed7-ac3ba55c66d2","type":"Grid"},{"attributes":{"data_source":{"id":"921ccb44-59e4-4121-978f-28d7b464b578","type":"ColumnDataSource"},"glyph":{"id":"7906132f-3f7b-4a62-b870-6ebc07e76f3c","type":"VBar"},"hover_glyph":null,"nonselection_glyph":null,"selection_glyph":null},"id":"4bafdfae-7d5f-4b42-94e1-51f0f56b31d7","type":"GlyphRenderer"},{"attributes":{"callback":null},"id":"4474c76c-8082-4d79-ab9f-008f5a42f42c","type":"DataRange1d"}],"root_ids":["04dde09d-3705-4bde-8cb7-bdb336ad5d03"]},"title":"Bokeh Application","version":"0.12.1.9393"}};
var render_items = [{"docid":"57f42173-7e02-406c-b448-1d12d768f56d","elementid":"c126e29c-be83-48cb-a14d-6ce708c79f77","modelid":"04dde09d-3705-4bde-8cb7-bdb336ad5d03"}];
Bokeh.embed.embed_items(docs_json, render_items);
});
},
function(Bokeh) {
console.log("Bokeh: injecting CSS: https://cdn.bokeh.org/bokeh/release/bokeh-0.12.1.min.css");
Bokeh.embed.inject_css("https://cdn.bokeh.org/bokeh/release/bokeh-0.12.1.min.css");
console.log("Bokeh: injecting CSS: https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.1.min.css");
Bokeh.embed.inject_css("https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.1.min.css");
}
];
function run_inline_js() {
for (var i = 0; i < inline_js.length; i++) {
inline_js[i](window.Bokeh);
}
}
if (window._bokeh_is_loading === 0) {
console.log("Bokeh: BokehJS loaded, going straight to plotting");
run_inline_js();
} else {
load_libs(js_urls, function() {
console.log("Bokeh: BokehJS plotting callback run at", now());
run_inline_js();
});
}
}(this));
}); | 78.09375 | 3,721 | 0.64239 |
3d8cdc3869f614822e9bd5fd1e76d5cfd43dabce | 290 | js | JavaScript | node_modules/@patternfly/react-tokens/dist/esm/c_notification_badge_m_read_after_BorderColor.js | jeffpuzzo/jp-rosa-react-form-wizard | fa565d0dddd5310ed3eb7c31bff4abee870bf266 | [
"MIT"
] | null | null | null | node_modules/@patternfly/react-tokens/dist/esm/c_notification_badge_m_read_after_BorderColor.js | jeffpuzzo/jp-rosa-react-form-wizard | fa565d0dddd5310ed3eb7c31bff4abee870bf266 | [
"MIT"
] | 5 | 2021-08-31T22:44:01.000Z | 2022-02-27T12:47:44.000Z | node_modules/@patternfly/react-tokens/dist/esm/c_notification_badge_m_read_after_BorderColor.js | jeffpuzzo/jp-rosa-react-form-wizard | fa565d0dddd5310ed3eb7c31bff4abee870bf266 | [
"MIT"
] | 1 | 2021-08-22T16:13:36.000Z | 2021-08-22T16:13:36.000Z | export const c_notification_badge_m_read_after_BorderColor = {
"name": "--pf-c-notification-badge--m-read--after--BorderColor",
"value": "transparent",
"var": "var(--pf-c-notification-badge--m-read--after--BorderColor)"
};
export default c_notification_badge_m_read_after_BorderColor; | 48.333333 | 69 | 0.765517 |
3d8ceab17e74ab0600824483c0fbd94c6f882b0a | 1,613 | js | JavaScript | src/stories/common/Wizard.stories.js | xantorres/pf9-ui-plugin | 57ad8b95608c76dbc66c596831b5b0d36d7d16f7 | [
"Apache-2.0"
] | null | null | null | src/stories/common/Wizard.stories.js | xantorres/pf9-ui-plugin | 57ad8b95608c76dbc66c596831b5b0d36d7d16f7 | [
"Apache-2.0"
] | null | null | null | src/stories/common/Wizard.stories.js | xantorres/pf9-ui-plugin | 57ad8b95608c76dbc66c596831b5b0d36d7d16f7 | [
"Apache-2.0"
] | null | null | null | import React from 'react'
import { addStoriesFromModule } from '../helpers'
import WizardStep from 'core/components/wizard/WizardStep'
import Wizard from 'core/components/wizard/Wizard'
import { action } from '@storybook/addon-actions'
const addStories = addStoriesFromModule(module)
addStories('Wizard', {
'Default': () => (
<Wizard onComplete={action('Submit action')}>
{[
<WizardStep key="first" stepId="first" label="First" info="This is the first">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Risus
pretium quam vulputate dignissim suspendisse in. Scelerisque in
dictum non consectetur a erat. Sagittis id consectetur purus ut
faucibus pulvinar elementum integer.
</WizardStep>,
<WizardStep key="second" stepId="second" label="Second" info="This is the second">
Pretium nibh ipsum consequat nisl vel pretium lectus quam. Curabitur vitae
nunc sed velit dignissim sodales ut eu. Leo in vitae turpis massa sed
elementum tempus. Vulputate dignissim suspendisse in est. Nisi est sit
amet facilisis magna etiam tempor. Convallis aenean et tortor at risus
viverra adipiscing at.
</WizardStep>,
<WizardStep key="third" stepId="third" label="Third" info="This is the third">
Dolor magna eget est lorem ipsum dolor sit amet. Velit euismod in pellentesque
massa. Porttitor lacus luctus accumsan tortor posuere.
</WizardStep>,
]}
</Wizard>
),
})
| 46.085714 | 90 | 0.687539 |
3d8cf2b7011c757b4dcc2cbc4de75ab0e0593fbb | 12,660 | js | JavaScript | Simlyn Node App/IOTAFlashLibs/transfer.js | christopher-wilke/Simlyn | 6cf7e6ad6286deb4d4eb8547d97ba742ba98474e | [
"MIT"
] | null | null | null | Simlyn Node App/IOTAFlashLibs/transfer.js | christopher-wilke/Simlyn | 6cf7e6ad6286deb4d4eb8547d97ba742ba98474e | [
"MIT"
] | null | null | null | Simlyn Node App/IOTAFlashLibs/transfer.js | christopher-wilke/Simlyn | 6cf7e6ad6286deb4d4eb8547d97ba742ba98474e | [
"MIT"
] | 1 | 2019-08-14T04:41:50.000Z | 2019-08-14T04:41:50.000Z | const IOTACrypto = require('iota.crypto.js');
const MAX_USES = require('./constants').MAX_USES;
const helpers = require('./helpers');
const getLastBranch = require('./multisig').getLastBranch;
const getMinimumBranch = require('./multisig').getMinimumBranch;
const TransferErrors = {
NULL_VALUE: -1,
REMAINDER_INCREASED: 0,
INVALID_TRANSFER_OBJECT: 1,
INSUFFICIENT_FUNDS: 2,
INVALID_TRANSFERS_ARRAY: 3,
INVALID_SIGNATURES: 4,
ADDRESS_OVERUSE: 5,
ADDRESS_NOT_FOUND: 6,
INPUT_UNDEFINED: 7,
INVALID_INPUT: 8,
BALANCE_NOT_PASSED: 9
};
/**
* Prepare transfers object
*
* @method prepare
* @param {array} settlement the settlement addresses for each user
* @param {array} deposits the amount each user can still spend
* @param {number} fromIndex the index of the user used as an input
* @param {destinations} the `{value, address}` destination of the output bundle (excluding remainder)
* @returns {array} transfers
*/
function prepare(settlement, deposits, fromIndex, destinations) {
const total = destinations.reduce((acc, tx) => acc + tx.value, 0);
if(total > deposits[fromIndex]) {
throw new Error(TransferErrors.INSUFFICIENT_FUNDS);
}
const transfer = helpers.deepClone(destinations);
settlement.map((s,i) => {
if(i != fromIndex) {
const current = transfer.find(tx => tx.address == s);
const stake = total * deposits[i] / deposits.filter((e,i) => i != fromIndex).reduce((acc, s) => acc + s, 0);
if(current) {
current.value += stake;
current.obsoleteTag = ''
} else {
transfer.push({ address: s, value: stake, obsoleteTag: ''
})
}
}
})
return transfer.filter(tx => tx.value > 0);
}
/**
* Composes a Transfer
*
* @method compose
* @param {number} balance The total amount of iotas in the channel
* @param {array<number>} deposit the amount of iotas still available to each user to spend from
* @param {array<string>} outputs the accrued outputs through the channel
* @param {array<bundles>} history the leaf bundles
* @param {array<{addy, val}>} transfers the array of outputs for the transfer
* @param {bool} close whether to use the minimum tree or not
* @return {array<bundle>} prepared bundles
*/
function compose(balance, deposit, outputs, root, remainder, history, transfers, close) {
const valueTransfersLength = transfers.filter( transfer => transfer.value < 0 ).length;
if (valueTransfersLength != 0 && valueTransfersLength > deposit.length) {
throw new Error(TransferErrors.INVALID_TRANSFER_OBJECT);
}
const amount = transfers.reduce((a,b) => a + b.value, 0);
const deposits = deposit.reduce((a,b) => a + b, 0);
if( amount > deposits || deposits < 0) {
throw new Error(TransferErrors.INSUFFICIENT_FUNDS);
}
transfers = transfers.map( transfer => {
if (transfer.address in outputs) {
transfer.value += outputs[transfer.address];
}
return transfer;
});
for(const addy in outputs) {
if (!transfers.find(tx => tx.address == addy)) {
transfers.push ({address: addy, value: outputs[addy]});
}
}
const bundles = [];
let multisigs = close ? getMinimumBranch(root) : getLastBranch(root);
if(multisigs[0].bundles.length == MAX_USES) {
throw new Error(TransferErrors.ADDRESS_OVERUSE);
}
for(let i = 0; i < multisigs.length - 1; i++) {
if(multisigs[i].bundles.find(bundle => bundle.find(tx => tx.value > 0 && tx.address == remainder))) {
multisigs = multisigs.slice(i+1);
} else {
break;
}
}
if(multisigs.length == 0) {
throw new Error(TransferErrors.ADDRESS_OVERUSE);
}
multisigs.slice(0,multisigs.length-1).map((multisig, i) => {
const input = {
address: multisig.address,
securitySum: multisig.securitySum,
balance: balance
};
const remainderAddress = remainder.address
const transfers = [{
address: multisigs[i + 1].address,
value: balance,
obsoleteTag: ''
}];
IOTACrypto.multisig.initiateTransfer(
input,
remainder.address,
transfers,
(err, success) => {
bundles.push(success)
}
)
})
const multisig = multisigs[multisigs.length - 1];
const input = {
address: multisig.address,
securitySum: multisig.securitySum,
balance: balance
};
IOTACrypto.multisig.initiateTransfer(
input,
remainder.address,
transfers,
(err, success) => {
bundles.push(success)
}
)
return bundles;
}
/**
* creates transactions to close the channel
*
* @method close
* @param {array} settlement the settlement addresses for each user
* @param {array} deposits the amount each user can still spend
* @returns {array} transfers
*/
function close(settlement, deposits) {
return settlement.filter(tx => tx).map((s, i) => {
return { address: s, value: deposits[i] };
}).filter(tx => tx.value > 0);
}
/**
* Applies Transfers to State
*
* @method apply
* @param {object} state
* @param {array} transfers
*/
function applyTransfers(root, deposit, outputs, remainder, history, transfers) {
if (transfers.filter(transfer =>
transfer.filter(tx => tx.value < 0)
.filter(tx => !IOTACrypto.utils.validateSignatures(transfer, tx.address))
.length != 0).length != 0) {
throw new Error(TransferErrors.INVALID_SIGNATURES);
}
let multisigs = getMultisigs(root, transfers);
if(multisigs.filter(node => node.bundles.length == 3).length != 0) {
//throw new Error(TransferErrors.ADDRESS_OVERUSE);
}
if(multisigs.length != transfers.length ) {
throw new Error(TransferErrors.ADDRESS_NOT_FOUND);
}
try {
let diff = getDiff(root, remainder, history, transfers);
let remaining = deposit.reduce((a,b) => a+b, 0);
let total = diff.filter(v => v.value > 0).reduce((acc,tx) => acc + tx.value, 0);
if (total > remaining) {
throw new Error(TransferErrors.INSUFFICIENT_FUNDS);
}
const depositTotal = deposit.reduce((acc, d) => acc + d, 0);
const depositDiff = deposit.map((d) => total * d / depositTotal);
for(const i in deposit) {
deposit[i] -= depositDiff[i];
}
for(let i = 0; i < diff.length; i++) {
if(diff[i].address in outputs) {
outputs[diff[i].address] += diff[i].value;
} else {
outputs[diff[i].address] = diff[i].value;
}
}
transfers.map((transfer, i) => {
multisigs[i].bundles.push(transfer);
});
history.push(transfers[transfers.length - 1]);
} catch (e) {
throw e;
}
}
function getMultisigs(root, transfers) {
let node = root;
let firstTransfer = transfers[0].find(tx => tx.value < 0)
while(node.address != firstTransfer.address && node.children.length != 0) {
node = node.children[node.children.length - 1];
}
if(node.address != firstTransfer.address) {
throw new Error(TransferErrors.ADDRESS_NOT_FOUND);
}
let multisigs = [];
let i = 0;
multisigs.push(node)
while (node.children.length != 0 && ++i < transfers.length) {
node = node.children.find(m => m.address == transfers[i].find(tx => tx.value < 0).address);
if(node.bundles.length == MAX_USES) {
throw new Error(TransferErrors.ADDRESS_OVERUSE);
}
if(!node) {
throw new Error(TransferErrors.ADDRESS_NOT_FOUND);
}
multisigs.push(node);
}
return multisigs;
}
/**
*
* @return {[{object}]} signatures
*/
function sign(root, seed, bundles) {
const multisigs = getMultisigs(root, bundles);
return helpers.deepClone(bundles).map((bundle, i) => {
const multisig = multisigs[i];
// multisig has member signingIndex
bundle
.filter(tx => tx.address == multisig.address)
.slice(0,multisig.signingIndex)
.map(tx => {
if(
IOTACrypto
.utils
.inputValidator
.isNinesTrytes(tx.signatureMessageFragment)
) {
tx.signatureMessageFragment =
tx.signatureMessageFragment.replace(/^9/,'A');
}
});
var sigs = []
IOTACrypto.multisig.addSignature(bundle, multisig.address, IOTACrypto.multisig.getKey(seed, multisig.index, multisig.security), (err, suc) => {
sigs = { bundle: bundle[0].bundle,
address: multisig.address,
index: multisig.signingIndex,
signatureFragments: suc
.filter(tx => tx.address == multisig.address)
.map(tx => tx.signatureMessageFragment)
.slice(multisig.signingIndex, multisig.signingIndex + multisig.security)
}
})
return sigs
});
}
/**
* signatures is an array of signatures for this bundle
*/
function appliedSignatures(bundles, signatures) {
return helpers.deepClone(bundles).map((bundle, i) => {
let userSignature = signatures[i];//.find(s => s.bundle == bundle[0].bundle);
if (userSignature) {
let addy = bundle.find(tx => tx.value < 0 ).address;
bundle
.filter(tx => tx.address == addy)
.slice(userSignature.index, userSignature.index + userSignature.signatureFragments.length)
.map((tx,j) => tx.signatureMessageFragment = userSignature.signatureFragments[j]);
// add signature
}
return bundle;
});
}
/**
* Adds signatures to bundles
*
* @param {object} bundle the bundle to add signatures to
* @param {string} address the address for the signatures
* @param {array} signatures a 2d array of signatures for each bundle
*
* example usage:
* bundles.map((bundle, i) =>
* addSignatures(
* bundle,
* bundle.find(tx => tx.value < 0).address,
* signatures[i]
* )
* )
*/
function addSignatures(bundle, address, signatures) {
bundle.filter(tx => tx.address == address).map((tx, i) => {
tx.signatureMessageFragment = signatures[i];
});
}
function getDiff(root, remainder, history, bundles) {
if(!root) {
throw new Error(TransferErrors.NULL_VALUE);
}
if(!remainder) {
throw new Error(TransferErrors.NULL_VALUE);
}
if(!history) {
throw new Error(TransferErrors.NULL_VALUE);
}
if(!bundles) {
throw new Error(TransferErrors.NULL_VALUE);
}
const initialInputTransaction = bundles[0].filter(bundle => bundle.value < 0)[0];
if (!initialInputTransaction) {
throw new Error(TransferErrors.INPUT_UNDEFINED);
}
const multisigs = getMultisigs(root, bundles);
if (bundles.length != multisigs.length) {
throw new Error(TransferErrors.TOO_MANY_BUNDLES);
}
const initialIndex = multisigs.filter(m => m.address == initialInputTransaction.address).map((m,i) => i)[0];
for(let i = initialIndex; i < multisigs.length - 1 && (i - initialIndex) < bundles.length - 1; i++) {
const bundle = bundles[i - initialIndex];
const inputTransaction = bundle.filter(tx => tx.value < 0)[0];
if(!inputTransaction || inputTransaction.address != multisigs[i].address) {
throw new Error(TransferErrors.INVALID_INPUT);
}
// TODO
// Check if entire amount is being passed to next multisig
if(bundle.find(tx => tx.value > 0 && tx.address != multisigs[i + 1].address)) {
throw new Error(TransferErrors.BALANCE_NOT_PASSED);
}
}
let previousTransfer = history.length == 0 ? []: history[history.length - 1];
const lastTransfer = bundles[bundles.length - 1];
const previousRemainder = previousTransfer.filter(tx => tx.address == remainder.address && tx.value > 0).reduce((acc, v) => acc + v.value, 0);
const newRemainder = lastTransfer.filter(tx => tx.address == remainder.address)
.map(tx => tx.value )
.reduce((acc, v) => acc + v, 0)
if(newRemainder.value > previousRemainder.value) {
throw new Error(TransferErrors.REMAINDER_INCREASED);
}
const newCopy = helpers.deepClone(lastTransfer
.filter(tx => tx.value > 0)
.map(tx => Object({address: tx.address, value: tx.value})))
.filter(tx => tx.address !== remainder.address)
for(const tx of previousTransfer.filter(tx => tx.value > 0)) {
const existing = newCopy.find(t => t.address == tx.address);
if(existing) {
existing.value -= tx.value;
} else {
newCopy.push({address: tx.address, value: tx.value});
}
}
var negatives = newCopy.filter(tx => tx.value < 0);
if(negatives.length != 0 ) {
throw new Error(TransferErrors.INVALID_INPUT);
}
var minusRemainder = newCopy.filter(tx => tx.address !== remainder.address)
return minusRemainder;
}
module.exports = {
'prepare' : prepare,
'compose' : compose,
'close' : close,
'getDiff' : getDiff,
'sign' : sign,
'appliedSignatures': appliedSignatures,
'applyTransfers' : applyTransfers,
'TransferErrors' : TransferErrors
} | 33.05483 | 149 | 0.648499 |
3d8d325ad7b0d1d91ba17e674b16d6475d1913a5 | 1,462 | js | JavaScript | src/test/parallel/test-http-same-map.js | odant/conan-jscript | 0e7433ebe9e5ebf331a47c8b2d01a510c7f53952 | [
"MIT"
] | null | null | null | src/test/parallel/test-http-same-map.js | odant/conan-jscript | 0e7433ebe9e5ebf331a47c8b2d01a510c7f53952 | [
"MIT"
] | 5 | 2021-02-13T18:06:42.000Z | 2021-02-13T18:06:44.000Z | src/test/parallel/test-http-same-map.js | odant/conan-jscript | 0e7433ebe9e5ebf331a47c8b2d01a510c7f53952 | [
"MIT"
] | 3 | 2019-03-25T23:01:31.000Z | 2020-05-19T01:17:27.000Z | // Flags: --allow_natives_syntax
'use strict';
const common = require('../common');
const assert = require('assert');
const http = require('http');
const server =
http.createServer(onrequest).listen(0, common.localhostIPv4, () => next(0));
function onrequest(req, res) {
res.end('ok');
onrequest.requests.push(req);
onrequest.responses.push(res);
}
onrequest.requests = [];
onrequest.responses = [];
function next(n) {
const { address: host, port } = server.address();
const req = http.get({ host, port });
req.once('response', (res) => onresponse(n, req, res));
}
function onresponse(n, req, res) {
res.resume();
if (n < 3) {
res.once('end', () => next(n + 1));
} else {
server.close();
}
onresponse.requests.push(req);
onresponse.responses.push(res);
}
onresponse.requests = [];
onresponse.responses = [];
function allSame(list) {
assert(list.length >= 2);
// eslint-disable-next-line no-unused-vars
for (const elt of list) eval('%DebugPrint(elt)');
// eslint-disable-next-line no-unused-vars
for (const elt of list) assert(eval('%HaveSameMap(list[0], elt)'));
}
process.on('exit', () => {
eval('%CollectGarbage(0)');
// TODO(bnoordhuis) Investigate why the first IncomingMessage ends up
// with a deprecated map. The map is stable after the first request.
allSame(onrequest.requests.slice(1));
allSame(onrequest.responses);
allSame(onresponse.requests);
allSame(onresponse.responses);
});
| 25.649123 | 80 | 0.666211 |
3d8d754c3d7f6c3a035b6db109379806610ba62d | 499 | js | JavaScript | node_modules/@compodoc/compodoc/dist/utils/index.js | rameezcm/rameez_poc | faa5be299e19c6bbcca65418adc0a29af3254714 | [
"MIT"
] | 3 | 2019-02-16T02:35:04.000Z | 2020-10-30T11:55:42.000Z | node_modules/@compodoc/compodoc/dist/utils/index.js | rameezcm/rameez_poc | faa5be299e19c6bbcca65418adc0a29af3254714 | [
"MIT"
] | 5 | 2020-05-11T20:36:15.000Z | 2021-11-02T15:48:30.000Z | node_modules/@compodoc/compodoc/dist/utils/index.js | prasadrao82/angular-test | 6017bbe06b59a0133a1614f274d6e4a913c20bd9 | [
"MIT"
] | 1 | 2018-04-21T17:51:57.000Z | 2018-04-21T17:51:57.000Z | "use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./angular-api.util"));
__export(require("./angular-version.util"));
__export(require("./basic-type.util"));
__export(require("./jsdoc-parser.util"));
__export(require("./exclude-parser.util"));
__export(require("./router-parser.util"));
__export(require("./imports.util"));
//# sourceMappingURL=index.js.map | 38.384615 | 71 | 0.703407 |
3d8d8d4206b067c8f5a135afa900536c4b1c635d | 2,100 | js | JavaScript | js/introHCI.js | rahulramath/project | 931da412d34884b759e7ded5fe9c54d4e4fc34a0 | [
"MIT"
] | null | null | null | js/introHCI.js | rahulramath/project | 931da412d34884b759e7ded5fe9c54d4e4fc34a0 | [
"MIT"
] | null | null | null | js/introHCI.js | rahulramath/project | 931da412d34884b759e7ded5fe9c54d4e4fc34a0 | [
"MIT"
] | null | null | null | 'use strict';
// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
initializePage();
})
/*
* Function that is called when the document is ready.
*/
function initializePage() {
$("#testjs").click(function(e) {
$('.jumbotron h1').text("Javascript is connected");
$("#testjs").text("Please wait...");
$(".jumbotron p").toggleClass("active");
});
// Add any additional listeners here
// example: $("#div-id").click(functionToCall);
$("a.thumbnail").click(projectClick);
$("#submitBtn").click(submitClick);
}
function projectClick(e) {
e.preventDefault();
var projectTitle = $(this).find("p").text();
var jumbotronHeader = $(".jumbotron h1");
jumbotronHeader.text(projectTitle);
//$(this).css("background-color","#7fff00");
var containingProject = $(this).closest(".project");
var description = $(containingProject).find(".project-description");
if (description.length == 0) {
$(containingProject).append("<div class='project-description'><p>Description of the project.</p></div>");
} else {
description.html("<p>Stop clicking on me! You just did it at " + (new Date()) + "</p>");
}
$(".project-description").toggle();
$(".img").toggle();
}
function submitClick(e) {
var projectName = $("#project").val();
$(projectName).animate({
width: $("#width").val()
});
var newText = $('#description').val();
$(projectName + " .project-description").text(newText);
}
$(function() {
var $document = $(document),
$inputRange = $('input[type="range"]');
// Example functionality to demonstrate a value feedback
function valueOutput(element) {
var value = element.value,
output = element.parentNode.getElementsByTagName('output')[0];
output.innerHTML = value;
}
for (var i = $inputRange.length - 1; i >= 0; i--) {
valueOutput($inputRange[i]);
};
$document.on('input', 'input[type="range"]', function(e) {
valueOutput(e.target);
});
// end
$inputRange.rangeslider({
polyfill: false
});
}); | 28.378378 | 112 | 0.61619 |
3d8d9d0292a9676ffb41deb879eff8bbffd44ee4 | 2,308 | js | JavaScript | slidewiki/libraries/frontend/MathJax/unpacked/jax/output/HTML-CSS/fonts/TeX/WinIE6/Regular/AMS.js | fzdabc/SlideWiki | ba0c5cfbaed919c4e5437bfbe00dcce77c33e1e5 | [
"Apache-2.0"
] | null | null | null | slidewiki/libraries/frontend/MathJax/unpacked/jax/output/HTML-CSS/fonts/TeX/WinIE6/Regular/AMS.js | fzdabc/SlideWiki | ba0c5cfbaed919c4e5437bfbe00dcce77c33e1e5 | [
"Apache-2.0"
] | null | null | null | slidewiki/libraries/frontend/MathJax/unpacked/jax/output/HTML-CSS/fonts/TeX/WinIE6/Regular/AMS.js | fzdabc/SlideWiki | ba0c5cfbaed919c4e5437bfbe00dcce77c33e1e5 | [
"Apache-2.0"
] | null | null | null | /*************************************************************
*
* MathJax/jax/output/HTML-CSS/fonts/TeX/WinIE6/Regular/AMS.js
*
* Copyright (c) 2009-2010 Design Science, 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.
*
*/
MathJax.Hub.Insert(
MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['MathJax_WinIE6'],
{
0xE2C0: [438,-63,500,57,417], // ??
0xE2C1: [438,-63,500,64,422], // ??
0xE2C2: [430,23,222,91,131], // ??
0xE2C3: [431,23,389,55,331], // ??
0xE2C4: [365,-132,778,55,719], // ??
0xE2C5: [753,175,778,83,694], // ??
0xE2C6: [753,175,778,82,694], // ??
0xE2C7: [708,209,778,82,693], // ??
0xE2C8: [708,209,778,82,694], // ??
0xE2CA: [694,-306,500,54,444], // ??
0xE2CB: [695,-306,500,55,444], // ??
0xE2CC: [367,23,500,54,444], // ??
0xE2CD: [366,22,500,55,445], // ??
0xE2CE: [694,195,889,0,860], // ??
0xE2CF: [694,195,889,0,860], // ??
0xE2D0: [689,0,778,55,722], // ??
0xE2D1: [689,0,778,55,722], // ??
0xE2D2: [575,20,722,84,637], // ??
0xE2D3: [575,20,722,84,637], // ??
0xE2D4: [539,41,778,83,694], // ??
0xE2D5: [576,20,722,84,638], // ??
0xE2D6: [576,20,722,84,638], // ??
0xE2D7: [539,41,778,83,694], // ??
0xE2D8: [716,132,667,56,612], // ??
0xE2D9: [471,82,667,24,643], // ??
0xE2DA: [471,82,667,23,643], // ??
0xE2DB: [601,101,778,15,762], // ??
0xE2DC: [695,111,944,49,896], // ??
0xE2DD: [367,-133,778,56,722] // ??
}
);
MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/WinIE6/Regular/AMS.js");
| 40.491228 | 93 | 0.518198 |
3d8e21281191d64db1f7e111d248a4b7b89e50f6 | 1,163 | js | JavaScript | src/utilities/fuzzyStringMatch.js | hsimah/eslint-plugin-ft-flow | 7786e3b9828b92896481c038d508d0aa11aadc04 | [
"BSD-3-Clause"
] | 6 | 2021-12-13T18:59:35.000Z | 2022-01-11T14:03:26.000Z | src/utilities/fuzzyStringMatch.js | hsimah/eslint-plugin-ft-flow | 7786e3b9828b92896481c038d508d0aa11aadc04 | [
"BSD-3-Clause"
] | 15 | 2021-12-13T21:14:49.000Z | 2022-02-04T09:06:02.000Z | src/utilities/fuzzyStringMatch.js | hsimah/eslint-plugin-ft-flow | 7786e3b9828b92896481c038d508d0aa11aadc04 | [
"BSD-3-Clause"
] | 2 | 2022-01-05T18:22:02.000Z | 2022-01-18T11:29:26.000Z | import _ from 'lodash';
// Creates an array of letter pairs from a given array
// origin: https://github.com/d3/d3-array/blob/master/src/pairs.js
const arrayPairs = (array) => {
let ii = 0;
const length = array.length - 1;
let letter = array[0];
const pairs = Array.from({ length: length < 0 ? 0 : length });
while (ii < length) {
// Not entirely sure what ++ii does yet
// eslint-disable-next-line no-plusplus
pairs[ii] = [letter, letter = array[++ii]];
}
return pairs;
};
// Based on http://stackoverflow.com/a/23305385
const stringSimilarity = (str1, str2) => {
if (str1.length > 0 && str2.length > 0) {
const pairs1 = arrayPairs(str1);
const pairs2 = arrayPairs(str2);
const unionLen = pairs1.length + pairs2.length;
let hitCount;
hitCount = 0;
_.forIn(pairs1, (val1) => {
_.forIn(pairs2, (val2) => {
if (_.isEqual(val1, val2)) {
hitCount += 1;
}
});
});
if (hitCount > 0) {
return (2 * hitCount) / unionLen;
}
}
return 0;
};
export default (needle, haystack, weight = 0.5) => (
stringSimilarity(needle, haystack) >= Number(weight)
);
| 23.26 | 66 | 0.595873 |
3d8ec53d4c3b18b5cd796819175b0e5390da9a22 | 3,715 | js | JavaScript | forms-flow-web/src/components/ServiceFlow/constants/taskConstants.js | gitter-badger/forms-flow-ai | d012566902120a24d02a7c1dad9053fefd17d24d | [
"Apache-2.0"
] | null | null | null | forms-flow-web/src/components/ServiceFlow/constants/taskConstants.js | gitter-badger/forms-flow-ai | d012566902120a24d02a7c1dad9053fefd17d24d | [
"Apache-2.0"
] | 11 | 2021-06-02T04:42:50.000Z | 2022-02-14T07:24:15.000Z | forms-flow-web/src/components/ServiceFlow/constants/taskConstants.js | gitter-badger/forms-flow-ai | d012566902120a24d02a7c1dad9053fefd17d24d | [
"Apache-2.0"
] | null | null | null | export const sortingList = [
{sortBy:"created",label:"Created", sortOrder:"asc"},
{sortBy:"priority",label:"Priority", sortOrder:"asc"},
{sortBy:"dueDate",label:"Due date", sortOrder:"asc"},
{sortBy:"assignee",label:"Assignee", sortOrder:"asc"},
{sortBy:"name",label:"Task name", sortOrder:"asc"},
{sortBy:"followUpDate",label:"Follow-up date", sortOrder:"asc"},
];
export const searchData = [
{"label": "Task Variables", "compares": [">", ">=", "=","!=", "<", "<="]},
{"label": "Process Variables", "compares": [">", ">=", "=","!=", "<", "<="]},
{"label": "Process Definition Name", "compares": ["like", "="], "values": ["processDefinitionNameLike", "processDefinitionName"]},
{"label": "Assignee", "compares": ["like", "="], "values": ["assigneeLike", "assignee"]},
{"label":"Candidate Group", "compares": ["="], "values": ["candidateGroup"]},
{"label":"Candidate User", "compares": ["="], "values": ["candidateUser"]},
{"label":"Name", "compares": ["like", "="], "values": ["nameLike", "name"]},
{"label": "Description","compares": ["like", "="], "values": ["descriptionLike", "description"] },
{"label":"Priority", "compares": ["="], "values": ["priority"]},
{"label":"Due Date", "compares": ["before", "after"], "values": ["due"]},
{"label":"Follow up Date", "compares": ["before", "after"], "values": ["followUp"]},
{"label":"Created", "compares": ["before", "after"], "values": ["created"]},
]
export const Filter_Search_Types = {
VARIABLES:"variables",
STRING:"string",
DATE:"date",
NORMAL:"normal"
}
export const FILTER_OPERATOR_TYPES = {
EQUAL:"=",
LIKE:"like",
BEFORE:"before",
AFTER:"after"
}
//TODO update to further constants
export const FILTER_COMPARE_OPTIONS = {
[Filter_Search_Types.VARIABLES]:[">", ">=", FILTER_OPERATOR_TYPES.EQUAL ,"!=", "<", "<=",FILTER_OPERATOR_TYPES.LIKE],
[Filter_Search_Types.DATE]:[FILTER_OPERATOR_TYPES.BEFORE, FILTER_OPERATOR_TYPES.AFTER],
[Filter_Search_Types.STRING]:[FILTER_OPERATOR_TYPES.EQUAL,FILTER_OPERATOR_TYPES.LIKE],
[Filter_Search_Types.NORMAL]:[FILTER_OPERATOR_TYPES.EQUAL]
};
export const taskFilters = [
{label:"Process Variables",key:"processVariables", operator:FILTER_OPERATOR_TYPES.EQUAL, type:Filter_Search_Types.VARIABLES, value:"", name:""},
{label:"Task Variables", key:"taskVariables",operator:FILTER_OPERATOR_TYPES.EQUAL, type:Filter_Search_Types.VARIABLES, value:"", name:""},
{label:"Process Definition Name",key:"processDefinitionName", operator:FILTER_OPERATOR_TYPES.LIKE, type:Filter_Search_Types.STRING, value:"" },
{label:"Assignee",key:"assignee",operator:FILTER_OPERATOR_TYPES.LIKE, type:Filter_Search_Types.STRING,value:"", },
{label:"Candidate Group",key:"candidateGroup",operator:FILTER_OPERATOR_TYPES.EQUAL,type:Filter_Search_Types.NORMAL, value:""},
{label:"Candidate User",key:"candidateUser",operator:FILTER_OPERATOR_TYPES.EQUAL,type:Filter_Search_Types.NORMAL, value:""},
{label:"Name",key:"name",operator:FILTER_OPERATOR_TYPES.LIKE,type:Filter_Search_Types.STRING,value:""},
{label:"Description",key:"description",operator:FILTER_OPERATOR_TYPES.LIKE,type:Filter_Search_Types.STRING, value:""},
{label:"Priority",key:"priority",operator:FILTER_OPERATOR_TYPES.EQUAL,type:Filter_Search_Types.NORMAL, value:""},
{label:"Due Date",key:"due",operator:FILTER_OPERATOR_TYPES.BEFORE, type:Filter_Search_Types.DATE, value:""},
{label:"Follow up Date",key:"followUp",operator:FILTER_OPERATOR_TYPES.BEFORE, type:Filter_Search_Types.DATE, value:""},
{label:"Created",key:"created",operator:FILTER_OPERATOR_TYPES.BEFORE,type:Filter_Search_Types.DATE, value:"" },
];
export const ALL_TASKS="All tasks"
export const QUERY_TYPES= {ANY:"ANY",ALL:"ALL"};
| 57.153846 | 146 | 0.696097 |
3d8ed5657c729d7ddaccbac85124d88a0f29e8ab | 37,287 | js | JavaScript | lib/serializer/src/operations.js | Whitecoin-XWC/xwc.js | 315c0557482142f871df1bcc73814592a784dd6c | [
"MIT"
] | null | null | null | lib/serializer/src/operations.js | Whitecoin-XWC/xwc.js | 315c0557482142f871df1bcc73814592a784dd6c | [
"MIT"
] | null | null | null | lib/serializer/src/operations.js | Whitecoin-XWC/xwc.js | 315c0557482142f871df1bcc73814592a784dd6c | [
"MIT"
] | null | null | null | import types from "./types";
import SerializerImpl from "./serializer";
var {
//id_type,
varint32,
uint8,
uint16,
uint32,
int64,
uint64,
string,
bytes,
bool,
tuple,
codeBytes,
array,
protocol_id_type,
object_id_type,
vote_id,
future_extensions,
static_variant,
map,
set,
public_key,
public_key_bytes,
address,
time_point_sec,
time_point,
optional
} = types;
future_extensions = types.void;
/*
When updating generated code
Replace: operation = static_variant [
with: operation.st_operations = [
Delete:
public_key = new Serializer(
"public_key"
key_data: bytes 33
)
*/
// Place-holder, their are dependencies on "operation" .. The final list of
// operations is not avialble until the very end of the generated code.
// See: operation.st_operations = ...
var operation = static_variant();
// module.exports["operation"] = operation;
export {operation};
// For module.exports
var Serializer = function(operation_name, serilization_types_object) {
return new SerializerImpl(operation_name, serilization_types_object);
// return module.exports[operation_name] = s;
};
// Custom-types follow Generated code:
// ## Generated code follows
// # programs/js_operation_serializer > npm i -g decaffeinate
// ## -------------------------------
export const transfer_operation_fee_parameters = new Serializer(
"transfer_operation_fee_parameters",
{
fee: uint64,
price_per_kbyte: uint32
}
);
export const contract_register_operation_fee_parameters = new Serializer(
"contract_register_operation_fee_parameters",
{
fee: uint64,
price_per_kbyte: uint32
}
);
export const contract_invoke_operation_fee_parameters = new Serializer(
"contract_invoke_operation_fee_parameters",
{
fee: uint64,
price_per_kbyte: uint32
}
);
export const lockbalance_operation_fee_parameters = new Serializer(
"lockbalance_operation_fee_parameters",
{
fee: uint64
}
);
export const foreclose_balance_operation_fee_parameters = new Serializer(
"foreclose_balance_operation_fee_parameters",
{
fee: uint64
}
);
export const pay_back_operation_fee_parameters = new Serializer(
"pay_back_operation_fee_parameters",
{
fee: uint64
}
);
export const limit_order_create_operation_fee_parameters = new Serializer(
"limit_order_create_operation_fee_parameters",
{fee: uint64}
);
export const limit_order_cancel_operation_fee_parameters = new Serializer(
"limit_order_cancel_operation_fee_parameters",
{fee: uint64}
);
export const call_order_update_operation_fee_parameters = new Serializer(
"call_order_update_operation_fee_parameters",
{fee: uint64}
);
export const fill_order_operation_fee_parameters = new Serializer(
"fill_order_operation_fee_parameters"
);
export const account_create_operation_fee_parameters = new Serializer(
"account_create_operation_fee_parameters",
{
basic_fee: uint64,
premium_fee: uint64,
price_per_kbyte: uint32
}
);
export const account_update_operation_fee_parameters = new Serializer(
"account_update_operation_fee_parameters",
{
fee: int64,
price_per_kbyte: uint32
}
);
export const account_whitelist_operation_fee_parameters = new Serializer(
"account_whitelist_operation_fee_parameters",
{fee: int64}
);
export const account_upgrade_operation_fee_parameters = new Serializer(
"account_upgrade_operation_fee_parameters",
{
membership_annual_fee: uint64,
membership_lifetime_fee: uint64
}
);
export const account_transfer_operation_fee_parameters = new Serializer(
"account_transfer_operation_fee_parameters",
{fee: uint64}
);
export const asset_create_operation_fee_parameters = new Serializer(
"asset_create_operation_fee_parameters",
{
symbol3: uint64,
symbol4: uint64,
long_symbol: uint64,
price_per_kbyte: uint32
}
);
export const asset_update_operation_fee_parameters = new Serializer(
"asset_update_operation_fee_parameters",
{
fee: uint64,
price_per_kbyte: uint32
}
);
export const asset_update_bitasset_operation_fee_parameters = new Serializer(
"asset_update_bitasset_operation_fee_parameters",
{fee: uint64}
);
export const asset_update_feed_producers_operation_fee_parameters = new Serializer(
"asset_update_feed_producers_operation_fee_parameters",
{fee: uint64}
);
export const asset_issue_operation_fee_parameters = new Serializer(
"asset_issue_operation_fee_parameters",
{
fee: uint64,
price_per_kbyte: uint32
}
);
export const asset_reserve_operation_fee_parameters = new Serializer(
"asset_reserve_operation_fee_parameters",
{fee: uint64}
);
export const asset_fund_fee_pool_operation_fee_parameters = new Serializer(
"asset_fund_fee_pool_operation_fee_parameters",
{fee: uint64}
);
export const asset_settle_operation_fee_parameters = new Serializer(
"asset_settle_operation_fee_parameters",
{fee: uint64}
);
export const asset_global_settle_operation_fee_parameters = new Serializer(
"asset_global_settle_operation_fee_parameters",
{fee: uint64}
);
export const asset_publish_feed_operation_fee_parameters = new Serializer(
"asset_publish_feed_operation_fee_parameters",
{fee: uint64}
);
export const witness_create_operation_fee_parameters = new Serializer(
"witness_create_operation_fee_parameters",
{fee: uint64}
);
export const witness_update_operation_fee_parameters = new Serializer(
"witness_update_operation_fee_parameters",
{fee: int64}
);
export const proposal_create_operation_fee_parameters = new Serializer(
"proposal_create_operation_fee_parameters",
{
fee: uint64,
price_per_kbyte: uint32
}
);
export const proposal_update_operation_fee_parameters = new Serializer(
"proposal_update_operation_fee_parameters",
{
fee: uint64,
price_per_kbyte: uint32
}
);
export const proposal_delete_operation_fee_parameters = new Serializer(
"proposal_delete_operation_fee_parameters",
{fee: uint64}
);
export const withdraw_permission_create_operation_fee_parameters = new Serializer(
"withdraw_permission_create_operation_fee_parameters",
{fee: uint64}
);
export const withdraw_permission_update_operation_fee_parameters = new Serializer(
"withdraw_permission_update_operation_fee_parameters",
{fee: uint64}
);
export const withdraw_permission_claim_operation_fee_parameters = new Serializer(
"withdraw_permission_claim_operation_fee_parameters",
{
fee: uint64,
price_per_kbyte: uint32
}
);
export const withdraw_permission_delete_operation_fee_parameters = new Serializer(
"withdraw_permission_delete_operation_fee_parameters",
{fee: uint64}
);
export const committee_member_create_operation_fee_parameters = new Serializer(
"committee_member_create_operation_fee_parameters",
{fee: uint64}
);
export const committee_member_update_operation_fee_parameters = new Serializer(
"committee_member_update_operation_fee_parameters",
{fee: uint64}
);
export const committee_member_update_global_parameters_operation_fee_parameters = new Serializer(
"committee_member_update_global_parameters_operation_fee_parameters",
{fee: uint64}
);
export const vesting_balance_create_operation_fee_parameters = new Serializer(
"vesting_balance_create_operation_fee_parameters",
{fee: uint64}
);
export const vesting_balance_withdraw_operation_fee_parameters = new Serializer(
"vesting_balance_withdraw_operation_fee_parameters",
{fee: uint64}
);
export const worker_create_operation_fee_parameters = new Serializer(
"worker_create_operation_fee_parameters",
{fee: uint64}
);
export const custom_operation_fee_parameters = new Serializer(
"custom_operation_fee_parameters",
{
fee: uint64,
price_per_kbyte: uint32
}
);
export const assert_operation_fee_parameters = new Serializer(
"assert_operation_fee_parameters",
{fee: uint64}
);
export const balance_claim_operation_fee_parameters = new Serializer(
"balance_claim_operation_fee_parameters"
);
export const override_transfer_operation_fee_parameters = new Serializer(
"override_transfer_operation_fee_parameters",
{
fee: uint64,
price_per_kbyte: uint32
}
);
export const transfer_to_blind_operation_fee_parameters = new Serializer(
"transfer_to_blind_operation_fee_parameters",
{
fee: uint64,
price_per_output: uint32
}
);
export const blind_transfer_operation_fee_parameters = new Serializer(
"blind_transfer_operation_fee_parameters",
{
fee: uint64,
price_per_output: uint32
}
);
export const transfer_from_blind_operation_fee_parameters = new Serializer(
"transfer_from_blind_operation_fee_parameters",
{fee: uint64}
);
export const asset_settle_cancel_operation_fee_parameters = new Serializer(
"asset_settle_cancel_operation_fee_parameters"
);
export const asset_claim_fees_operation_fee_parameters = new Serializer(
"asset_claim_fees_operation_fee_parameters",
{fee: uint64}
);
export const fba_distribute_operation_fee_parameters = new Serializer(
"fba_distribute_operation_fee_parameters"
);
export const bid_collateral_operation_fee_parameters = new Serializer(
"bid_collateral_operation_fee_parameters",
{
fee: uint64
}
);
export const execute_bid_operation_fee_parameters = new Serializer(
"execute_bid_operation_fee_parameters"
);
export const asset_claim_pool_operation_fee_parameters = new Serializer(
"asset_claim_pool_operation_fee_parameters",
{
fee: uint64
}
);
export const asset_update_issuer_operation_fee_parameters = new Serializer(
"asset_update_issuer_operation_fee_parameters",
{
fee: uint64
}
);
var fee_parameters = static_variant([
transfer_operation_fee_parameters,
contract_register_operation_fee_parameters,
contract_invoke_operation_fee_parameters,
limit_order_create_operation_fee_parameters,
limit_order_cancel_operation_fee_parameters,
call_order_update_operation_fee_parameters,
fill_order_operation_fee_parameters,
account_create_operation_fee_parameters,
account_update_operation_fee_parameters,
account_whitelist_operation_fee_parameters,
account_upgrade_operation_fee_parameters,
account_transfer_operation_fee_parameters,
asset_create_operation_fee_parameters,
asset_update_operation_fee_parameters,
asset_update_bitasset_operation_fee_parameters,
asset_update_feed_producers_operation_fee_parameters,
asset_issue_operation_fee_parameters,
asset_reserve_operation_fee_parameters,
asset_fund_fee_pool_operation_fee_parameters,
asset_settle_operation_fee_parameters,
asset_global_settle_operation_fee_parameters,
asset_publish_feed_operation_fee_parameters,
witness_create_operation_fee_parameters,
witness_update_operation_fee_parameters,
proposal_create_operation_fee_parameters,
proposal_update_operation_fee_parameters,
proposal_delete_operation_fee_parameters,
withdraw_permission_create_operation_fee_parameters,
withdraw_permission_update_operation_fee_parameters,
withdraw_permission_claim_operation_fee_parameters,
withdraw_permission_delete_operation_fee_parameters,
committee_member_create_operation_fee_parameters,
committee_member_update_operation_fee_parameters,
committee_member_update_global_parameters_operation_fee_parameters,
vesting_balance_create_operation_fee_parameters,
vesting_balance_withdraw_operation_fee_parameters,
worker_create_operation_fee_parameters,
custom_operation_fee_parameters,
assert_operation_fee_parameters,
balance_claim_operation_fee_parameters,
override_transfer_operation_fee_parameters,
transfer_to_blind_operation_fee_parameters,
blind_transfer_operation_fee_parameters,
transfer_from_blind_operation_fee_parameters,
asset_settle_cancel_operation_fee_parameters,
asset_claim_fees_operation_fee_parameters,
fba_distribute_operation_fee_parameters,
bid_collateral_operation_fee_parameters,
execute_bid_operation_fee_parameters,
asset_claim_pool_operation_fee_parameters,
asset_update_issuer_operation_fee_parameters
]);
export const fee_schedule = new Serializer("fee_schedule", {
parameters: set(fee_parameters),
scale: uint32
});
export const void_result = new Serializer("void_result");
export const asset = new Serializer("asset", {
amount: int64,
asset_id: protocol_id_type("asset")
});
var operation_result = static_variant([void_result, object_id_type, asset]);
export const Code = new Serializer("Code", {
abi: array(string),
offline_abi: array(string),
events: array(string),
storage_properties: map(string, varint32),
code: codeBytes(),
code_hash: string
});
export const ContractInfoForCalculateAddress = new Serializer(
"ContractInfoForCalculateAddress",
{
0: Code,
1: time_point
}
);
export const processed_transaction = new Serializer("processed_transaction", {
ref_block_num: uint16,
ref_block_prefix: uint32,
expiration: time_point_sec,
operations: array(operation),
extensions: set(future_extensions),
signatures: array(bytes(65)),
operation_results: array(operation_result)
});
export const signed_block = new Serializer("signed_block", {
previous: bytes(20),
timestamp: time_point_sec,
witness: protocol_id_type("witness"),
transaction_merkle_root: bytes(20),
extensions: set(future_extensions),
witness_signature: bytes(65),
transactions: array(processed_transaction)
});
export const block_header = new Serializer("block_header", {
previous: bytes(20),
timestamp: time_point_sec,
witness: protocol_id_type("witness"),
transaction_merkle_root: bytes(20),
extensions: set(future_extensions)
});
export const signed_block_header = new Serializer("signed_block_header", {
previous: bytes(20),
timestamp: time_point_sec,
witness: protocol_id_type("witness"),
transaction_merkle_root: bytes(20),
extensions: set(future_extensions),
witness_signature: bytes(65)
});
export const memo_data = new Serializer("memo_data", {
from: public_key,
to: public_key,
nonce: uint64,
message: bytes()
});
export const transfer = new Serializer("transfer", {
fee: asset,
guarantee_id: optional(protocol_id_type("account")),
from: protocol_id_type("account"),
to: protocol_id_type("account"),
from_addr: address,
to_addr: address,
amount: asset,
memo: optional(memo_data),
extensions: set(future_extensions)
});
export const contract_register = new Serializer("contract_register", {
fee: asset,
init_cost: uint64,
gas_price: uint64,
owner_addr: address,
owner_pubkey: public_key_bytes, // bytes(),
register_time: time_point_sec,
contract_id: address,
contract_code: Code,
inherit_from: address,
guarantee_id: optional(protocol_id_type("account"))
});
export const contract_invoke = new Serializer("contract_invoke", {
fee: asset,
invoke_cost: uint64,
gas_price: uint64,
caller_addr: address,
caller_pubkey: public_key_bytes, // bytes()
contract_id: address,
contract_api: string,
contract_arg: string,
guarantee_id: optional(protocol_id_type("account"))
});
export const transfer_contract = new Serializer("transfer_contract", {
fee: asset,
invoke_cost: uint64,
gas_price: uint64,
caller_addr: address,
caller_pubkey: public_key_bytes,
contract_id: address,
amount: asset,
param: string,
guarantee_id: optional(protocol_id_type("account"))
});
export const pay_back = new Serializer("pay_back", {
pay_back_owner: address,
pay_back_balance: map(string, asset),
guarantee_id: optional(protocol_id_type("account")),
fee: asset
});
export const lockbalance = new Serializer("lockbalance", {
lock_asset_id: protocol_id_type("asset"),
lock_asset_amount: int64,
contract_addr: address,
lock_balance_account: protocol_id_type("account"),
lockto_miner_account: protocol_id_type("miner"),
lock_balance_addr: address,
fee: asset
});
export const foreclose_balance = new Serializer("foreclose_balance", {
fee: asset,
foreclose_asset_id: protocol_id_type("asset"),
foreclose_asset_amount: int64,
foreclose_miner_account: protocol_id_type("miner"),
foreclose_contract_addr: address,
foreclose_account: protocol_id_type("account"),
foreclose_addr: address
});
export const limit_order_create = new Serializer("limit_order_create", {
fee: asset,
seller: protocol_id_type("account"),
amount_to_sell: asset,
min_to_receive: asset,
expiration: time_point_sec,
fill_or_kill: bool,
extensions: set(future_extensions)
});
export const limit_order_cancel = new Serializer("limit_order_cancel", {
fee: asset,
fee_paying_account: protocol_id_type("account"),
order: protocol_id_type("limit_order"),
extensions: set(future_extensions)
});
export const call_order_update = new Serializer("call_order_update", {
fee: asset,
funding_account: protocol_id_type("account"),
delta_collateral: asset,
delta_debt: asset,
extensions: set(future_extensions)
});
export const fill_order = new Serializer("fill_order", {
fee: asset,
order_id: object_id_type,
account_id: protocol_id_type("account"),
pays: asset,
receives: asset
});
export const authority = new Serializer("authority", {
weight_threshold: uint32,
account_auths: map(protocol_id_type("account"), uint16),
key_auths: map(public_key, uint16),
address_auths: map(address, uint16)
});
export const account_options = new Serializer("account_options", {
memo_key: public_key,
voting_account: protocol_id_type("account"),
num_witness: uint16,
num_committee: uint16,
votes: set(vote_id),
miner_pledge_pay_back: uint8,
extensions: set(future_extensions)
});
export const account_create = new Serializer("account_create", {
fee: asset,
registrar: protocol_id_type("account"),
referrer: protocol_id_type("account"),
referrer_percent: uint16,
name: string,
owner: authority,
active: authority,
payer: address,
options: account_options,
extensions: set(future_extensions),
guarantee_id: optional(protocol_id_type("account"))
});
export const account_update = new Serializer("account_update", {
fee: asset,
account: protocol_id_type("account"),
owner: optional(authority),
active: optional(authority),
new_options: optional(account_options),
extensions: set(future_extensions)
});
export const account_whitelist = new Serializer("account_whitelist", {
fee: asset,
authorizing_account: protocol_id_type("account"),
account_to_list: protocol_id_type("account"),
new_listing: uint8,
extensions: set(future_extensions)
});
export const account_upgrade = new Serializer("account_upgrade", {
fee: asset,
account_to_upgrade: protocol_id_type("account"),
upgrade_to_lifetime_member: bool,
extensions: set(future_extensions)
});
export const account_transfer = new Serializer("account_transfer", {
fee: asset,
account_id: protocol_id_type("account"),
new_owner: protocol_id_type("account"),
extensions: set(future_extensions)
});
export const price = new Serializer("price", {
base: asset,
quote: asset
});
export const asset_options = new Serializer("asset_options", {
max_supply: int64,
market_fee_percent: uint16,
max_market_fee: int64,
issuer_permissions: uint16,
flags: uint16,
core_exchange_rate: price,
whitelist_authorities: set(protocol_id_type("account")),
blacklist_authorities: set(protocol_id_type("account")),
whitelist_markets: set(protocol_id_type("asset")),
blacklist_markets: set(protocol_id_type("asset")),
description: string,
extensions: set(future_extensions)
});
export const bitasset_options = new Serializer("bitasset_options", {
feed_lifetime_sec: uint32,
minimum_feeds: uint8,
force_settlement_delay_sec: uint32,
force_settlement_offset_percent: uint16,
maximum_force_settlement_volume: uint16,
short_backing_asset: protocol_id_type("asset"),
extensions: set(future_extensions)
});
export const asset_create = new Serializer("asset_create", {
fee: asset,
issuer: protocol_id_type("account"),
symbol: string,
precision: uint8,
common_options: asset_options,
bitasset_opts: optional(bitasset_options),
is_prediction_market: bool,
extensions: set(future_extensions)
});
export const asset_update = new Serializer("asset_update", {
fee: asset,
issuer: protocol_id_type("account"),
asset_to_update: protocol_id_type("asset"),
new_issuer: optional(protocol_id_type("account")),
new_options: asset_options,
extensions: set(future_extensions)
});
export const asset_update_bitasset = new Serializer("asset_update_bitasset", {
fee: asset,
issuer: protocol_id_type("account"),
asset_to_update: protocol_id_type("asset"),
new_options: bitasset_options,
extensions: set(future_extensions)
});
export const asset_update_feed_producers = new Serializer(
"asset_update_feed_producers",
{
fee: asset,
issuer: protocol_id_type("account"),
asset_to_update: protocol_id_type("asset"),
new_feed_producers: set(protocol_id_type("account")),
extensions: set(future_extensions)
}
);
export const asset_issue = new Serializer("asset_issue", {
fee: asset,
issuer: protocol_id_type("account"),
asset_to_issue: asset,
issue_to_account: protocol_id_type("account"),
memo: optional(memo_data),
extensions: set(future_extensions)
});
export const asset_reserve = new Serializer("asset_reserve", {
fee: asset,
payer: protocol_id_type("account"),
amount_to_reserve: asset,
extensions: set(future_extensions)
});
export const asset_fund_fee_pool = new Serializer("asset_fund_fee_pool", {
fee: asset,
from_account: protocol_id_type("account"),
asset_id: protocol_id_type("asset"),
amount: int64,
extensions: set(future_extensions)
});
export const asset_settle = new Serializer("asset_settle", {
fee: asset,
account: protocol_id_type("account"),
amount: asset,
extensions: set(future_extensions)
});
export const asset_global_settle = new Serializer("asset_global_settle", {
fee: asset,
issuer: protocol_id_type("account"),
asset_to_settle: protocol_id_type("asset"),
settle_price: price,
extensions: set(future_extensions)
});
export const price_feed = new Serializer("price_feed", {
settlement_price: price,
maintenance_collateral_ratio: uint16,
maximum_short_squeeze_ratio: uint16,
core_exchange_rate: price
});
export const asset_publish_feed = new Serializer("asset_publish_feed", {
fee: asset,
publisher: protocol_id_type("account"),
asset_id: protocol_id_type("asset"),
feed: price_feed,
extensions: set(future_extensions)
});
export const witness_create = new Serializer("witness_create", {
fee: asset,
witness_account: protocol_id_type("account"),
url: string,
block_signing_key: public_key
});
export const witness_update = new Serializer("witness_update", {
fee: asset,
witness: protocol_id_type("witness"),
witness_account: protocol_id_type("account"),
new_url: optional(string),
new_signing_key: optional(public_key)
});
export const op_wrapper = new Serializer("op_wrapper", {op: operation});
export const proposal_create = new Serializer("proposal_create", {
fee: asset,
fee_paying_account: protocol_id_type("account"),
expiration_time: time_point_sec,
proposed_ops: array(op_wrapper),
review_period_seconds: optional(uint32),
extensions: set(future_extensions)
});
export const proposal_update = new Serializer("proposal_update", {
fee: asset,
fee_paying_account: protocol_id_type("account"),
proposal: protocol_id_type("proposal"),
active_approvals_to_add: set(protocol_id_type("account")),
active_approvals_to_remove: set(protocol_id_type("account")),
owner_approvals_to_add: set(protocol_id_type("account")),
owner_approvals_to_remove: set(protocol_id_type("account")),
key_approvals_to_add: set(public_key),
key_approvals_to_remove: set(public_key),
extensions: set(future_extensions)
});
export const proposal_delete = new Serializer("proposal_delete", {
fee: asset,
fee_paying_account: protocol_id_type("account"),
using_owner_authority: bool,
proposal: protocol_id_type("proposal"),
extensions: set(future_extensions)
});
export const withdraw_permission_create = new Serializer(
"withdraw_permission_create",
{
fee: asset,
withdraw_from_account: protocol_id_type("account"),
authorized_account: protocol_id_type("account"),
withdrawal_limit: asset,
withdrawal_period_sec: uint32,
periods_until_expiration: uint32,
period_start_time: time_point_sec
}
);
export const withdraw_permission_update = new Serializer(
"withdraw_permission_update",
{
fee: asset,
withdraw_from_account: protocol_id_type("account"),
authorized_account: protocol_id_type("account"),
permission_to_update: protocol_id_type("withdraw_permission"),
withdrawal_limit: asset,
withdrawal_period_sec: uint32,
period_start_time: time_point_sec,
periods_until_expiration: uint32
}
);
export const withdraw_permission_claim = new Serializer(
"withdraw_permission_claim",
{
fee: asset,
withdraw_permission: protocol_id_type("withdraw_permission"),
withdraw_from_account: protocol_id_type("account"),
withdraw_to_account: protocol_id_type("account"),
amount_to_withdraw: asset,
memo: optional(memo_data)
}
);
export const withdraw_permission_delete = new Serializer(
"withdraw_permission_delete",
{
fee: asset,
withdraw_from_account: protocol_id_type("account"),
authorized_account: protocol_id_type("account"),
withdrawal_permission: protocol_id_type("withdraw_permission")
}
);
export const committee_member_create = new Serializer(
"committee_member_create",
{
fee: asset,
committee_member_account: protocol_id_type("account"),
url: string
}
);
export const committee_member_update = new Serializer(
"committee_member_update",
{
fee: asset,
committee_member: protocol_id_type("committee_member"),
committee_member_account: protocol_id_type("account"),
new_url: optional(string)
}
);
export const chain_parameters = new Serializer("chain_parameters", {
current_fees: fee_schedule,
block_interval: uint8,
maintenance_interval: uint32,
maintenance_skip_slots: uint8,
committee_proposal_review_period: uint32,
maximum_transaction_size: uint32,
maximum_block_size: uint32,
maximum_time_until_expiration: uint32,
maximum_proposal_lifetime: uint32,
maximum_asset_whitelist_authorities: uint8,
maximum_asset_feed_publishers: uint8,
maximum_witness_count: uint16,
maximum_committee_count: uint16,
maximum_authority_membership: uint16,
reserve_percent_of_fee: uint16,
network_percent_of_fee: uint16,
lifetime_referrer_percent_of_fee: uint16,
cashback_vesting_period_seconds: uint32,
cashback_vesting_threshold: int64,
count_non_member_votes: bool,
allow_non_member_whitelists: bool,
witness_pay_per_block: int64,
worker_budget_per_day: int64,
max_predicate_opcode: uint16,
fee_liquidation_threshold: int64,
accounts_per_fee_scale: uint16,
account_fee_scale_bitshifts: uint8,
max_authority_depth: uint8,
extensions: set(future_extensions)
});
export const committee_member_update_global_parameters = new Serializer(
"committee_member_update_global_parameters",
{
fee: asset,
new_parameters: chain_parameters
}
);
export const linear_vesting_policy_initializer = new Serializer(
"linear_vesting_policy_initializer",
{
begin_timestamp: time_point_sec,
vesting_cliff_seconds: uint32,
vesting_duration_seconds: uint32
}
);
export const cdd_vesting_policy_initializer = new Serializer(
"cdd_vesting_policy_initializer",
{
start_claim: time_point_sec,
vesting_seconds: uint32
}
);
var vesting_policy_initializer = static_variant([
linear_vesting_policy_initializer,
cdd_vesting_policy_initializer
]);
export const vesting_balance_create = new Serializer("vesting_balance_create", {
fee: asset,
creator: protocol_id_type("account"),
owner: protocol_id_type("account"),
amount: asset,
policy: vesting_policy_initializer
});
export const vesting_balance_withdraw = new Serializer(
"vesting_balance_withdraw",
{
fee: asset,
vesting_balance: protocol_id_type("vesting_balance"),
owner: protocol_id_type("account"),
amount: asset
}
);
export const refund_worker_initializer = new Serializer(
"refund_worker_initializer"
);
export const vesting_balance_worker_initializer = new Serializer(
"vesting_balance_worker_initializer",
{pay_vesting_period_days: uint16}
);
export const burn_worker_initializer = new Serializer(
"burn_worker_initializer"
);
var worker_initializer = static_variant([
refund_worker_initializer,
vesting_balance_worker_initializer,
burn_worker_initializer
]);
export const worker_create = new Serializer("worker_create", {
fee: asset,
owner: protocol_id_type("account"),
work_begin_date: time_point_sec,
work_end_date: time_point_sec,
daily_pay: int64,
name: string,
url: string,
initializer: worker_initializer
});
export const custom = new Serializer("custom", {
fee: asset,
payer: protocol_id_type("account"),
required_auths: set(protocol_id_type("account")),
id: uint16,
data: bytes()
});
export const account_name_eq_lit_predicate = new Serializer(
"account_name_eq_lit_predicate",
{
account_id: protocol_id_type("account"),
name: string
}
);
export const asset_symbol_eq_lit_predicate = new Serializer(
"asset_symbol_eq_lit_predicate",
{
asset_id: protocol_id_type("asset"),
symbol: string
}
);
export const block_id_predicate = new Serializer("block_id_predicate", {
id: bytes(20)
});
var predicate = static_variant([
account_name_eq_lit_predicate,
asset_symbol_eq_lit_predicate,
block_id_predicate
]);
export const assert = new Serializer("assert", {
fee: asset,
fee_paying_account: protocol_id_type("account"),
predicates: array(predicate),
required_auths: set(protocol_id_type("account")),
extensions: set(future_extensions)
});
export const balance_claim = new Serializer("balance_claim", {
fee: asset,
deposit_to_account: protocol_id_type("account"),
balance_to_claim: protocol_id_type("balance"),
balance_owner_key: public_key,
total_claimed: asset
});
export const override_transfer = new Serializer("override_transfer", {
fee: asset,
issuer: protocol_id_type("account"),
from: protocol_id_type("account"),
to: protocol_id_type("account"),
amount: asset,
memo: optional(memo_data),
extensions: set(future_extensions)
});
export const stealth_confirmation = new Serializer("stealth_confirmation", {
one_time_key: public_key,
to: optional(public_key),
encrypted_memo: bytes()
});
export const blind_output = new Serializer("blind_output", {
commitment: bytes(33),
range_proof: bytes(),
owner: authority,
stealth_memo: optional(stealth_confirmation)
});
export const transfer_to_blind = new Serializer("transfer_to_blind", {
fee: asset,
amount: asset,
from: protocol_id_type("account"),
blinding_factor: bytes(32),
outputs: array(blind_output)
});
export const blind_input = new Serializer("blind_input", {
commitment: bytes(33),
owner: authority
});
export const blind_transfer = new Serializer("blind_transfer", {
fee: asset,
inputs: array(blind_input),
outputs: array(blind_output)
});
export const transfer_from_blind = new Serializer("transfer_from_blind", {
fee: asset,
amount: asset,
to: protocol_id_type("account"),
blinding_factor: bytes(32),
inputs: array(blind_input)
});
export const asset_settle_cancel = new Serializer("asset_settle_cancel", {
fee: asset,
settlement: protocol_id_type("force_settlement"),
account: protocol_id_type("account"),
amount: asset,
extensions: set(future_extensions)
});
export const asset_claim_fees = new Serializer("asset_claim_fees", {
fee: asset,
issuer: protocol_id_type("account"),
amount_to_claim: asset,
extensions: set(future_extensions)
});
export const fba_distribute = new Serializer("fba_distribute", {
fee: asset,
account_id: protocol_id_type("account"),
fba_id: protocol_id_type("fba_accumulator"),
amount: int64
});
export const bid_collateral = new Serializer("bid_collateral", {
fee: asset,
bidder: protocol_id_type("account"),
additional_collateral: asset,
debt_covered: asset,
extensions: set(future_extensions)
});
export const execute_bid = new Serializer("execute_bid", {
fee: asset,
bidder: protocol_id_type("account"),
debt: asset,
collateral: asset
});
export const asset_claim_pool = new Serializer("asset_claim_pool", {
fee: asset,
issuer: protocol_id_type("account"),
asset_id: protocol_id_type("asset"),
amount_to_claim: asset,
extensions: set(future_extensions)
});
export const asset_update_issuer = new Serializer("asset_update_issuer", {
fee: asset,
issuer: protocol_id_type("account"),
asset_to_update: protocol_id_type("asset"),
new_issuer: protocol_id_type("account"),
extensions: set(future_extensions)
});
operation.st_operations = [
transfer,
limit_order_create,
limit_order_cancel,
call_order_update,
fill_order,
account_create,
account_update,
account_whitelist,
account_upgrade,
account_transfer,
asset_create,
asset_update,
asset_update_bitasset,
asset_update_feed_producers,
asset_issue,
asset_reserve,
asset_fund_fee_pool,
asset_settle,
asset_global_settle,
asset_publish_feed,
witness_create,
witness_update,
proposal_create,
proposal_update,
proposal_delete,
withdraw_permission_create,
withdraw_permission_update,
withdraw_permission_claim,
withdraw_permission_delete,
committee_member_create,
committee_member_update,
committee_member_update_global_parameters,
vesting_balance_create,
vesting_balance_withdraw,
worker_create,
custom,
assert,
balance_claim,
override_transfer,
transfer_to_blind,
blind_transfer,
transfer_from_blind,
asset_settle_cancel,
asset_claim_fees,
fba_distribute,
bid_collateral,
execute_bid,
asset_claim_pool,
asset_update_issuer, // 48
// other not implemented xwc operations in js
null,
null, // 50
null,
null,
null,
null,
lockbalance, // 55
foreclose_balance, // 56
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
pay_back, // 73
null,
null,
// xwc operations
contract_register, // 76
null,
null,
contract_invoke, // 79
null,
transfer_contract // 81
];
export const transaction = new Serializer("transaction", {
ref_block_num: uint16,
ref_block_prefix: uint32,
expiration: time_point_sec,
operations: array(operation),
extensions: set(future_extensions)
});
export const signed_transaction = new Serializer("signed_transaction", {
ref_block_num: uint16,
ref_block_prefix: uint32,
expiration: time_point_sec,
operations: array(operation),
extensions: set(future_extensions),
signatures: array(bytes(65))
});
//# -------------------------------
//# Generated code end
//# -------------------------------
// Custom Types
export const stealth_memo_data = new Serializer("stealth_memo_data", {
from: optional(public_key),
amount: asset,
blinding_factor: bytes(32),
commitment: bytes(33),
check: uint32
});
// var stealth_confirmation = new Serializer(
// "stealth_confirmation", {
// one_time_key: public_key,
// to: optional( public_key ),
// encrypted_memo: stealth_memo_data
// })
export const rawTypes = types;
| 28.247727 | 97 | 0.736342 |
3d8f26f99d561915c40c50e12f335861d862f26b | 1,000 | js | JavaScript | webapp/Connector/src/model/MabDetail.js | LabKey/cds | 7e5ba9e03211dae21d1a19c4391f9a4dbb9bcf88 | [
"Apache-2.0"
] | 2 | 2015-07-07T20:58:13.000Z | 2018-02-06T21:21:43.000Z | webapp/Connector/src/model/MabDetail.js | LabKey/cds | 7e5ba9e03211dae21d1a19c4391f9a4dbb9bcf88 | [
"Apache-2.0"
] | 62 | 2015-02-20T22:32:23.000Z | 2022-03-17T20:23:09.000Z | webapp/Connector/src/model/MabDetail.js | LabKey/cds | 7e5ba9e03211dae21d1a19c4391f9a4dbb9bcf88 | [
"Apache-2.0"
] | 3 | 2018-05-29T21:45:56.000Z | 2019-12-04T16:26:54.000Z | /*
* Copyright (c) 2018 LabKey Corporation
*
* Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
*/
Ext.define('Connector.model.MabDetail', {
extend: 'Connector.model.Detail',
idProperty: 'label',
fields: [
{name: 'filterConfig', defaultValue: undefined},
{name: 'name'},
{name: 'label'},
{name: 'learnProp'},
{name: 'value'},
{name: 'count', type: 'int'},
{name: 'subcount', type: 'int'}, // a value of -1 determines that the subcount is not provided
{name: 'valueLabel'},
{name: 'highlight', type: 'boolean'},
{name: 'activeCountLink', type: 'boolean'},
{name: 'viewClass', defaultValue: undefined}, // alternate class name for the info pane to display on click (must extend Connector.view.InfoPane)
{name: 'modelClass', defaultValue: undefined} // alternate class name for the info pane model (must extend Connector.model.InfoPane)
]
}); | 38.461538 | 153 | 0.624 |
3d8f5264aecd11be3c2c35440dca411cdfdcaa36 | 5,606 | js | JavaScript | packages/eae-compute/test/testserver.js | dsi-icl/eae | fdc69b8ef0238f2d5275833a8d09cc89f396f2e4 | [
"MIT"
] | 1 | 2020-03-05T11:24:56.000Z | 2020-03-05T11:24:56.000Z | packages/eae-compute/test/testserver.js | dsi-icl/eae | fdc69b8ef0238f2d5275833a8d09cc89f396f2e4 | [
"MIT"
] | 170 | 2019-05-09T07:53:15.000Z | 2021-09-03T08:30:45.000Z | test/testserver.js | dsi-icl/eae-compute | 78ffa23b59ec77fb249f5deb465a6f735b4e5a4b | [
"MIT"
] | 5 | 2017-11-14T14:53:22.000Z | 2019-03-12T16:22:55.000Z | let express = require('express');
let EaeCompute = require('../src/eaeCompute.js');
let config = require('../config/eae.compute.config.js');
let ObjectID = require('mongodb').ObjectID;
const fs = require('fs');
const path = require('path');
const eaeutils = require('eae-utils');
function TestServer() {
// Bind member vars
this._app = express();
this._swift = new eaeutils.SwiftHelper({
url: config.swiftURL,
username: config.swiftUsername,
password: config.swiftPassword
});
// Bind member functions
this.run = TestServer.prototype.run.bind(this);
this.stop = TestServer.prototype.stop.bind(this);
this.mongo = TestServer.prototype.mongo.bind(this);
this.createJob = TestServer.prototype.createJob.bind(this);
this.deleteJob = TestServer.prototype.deleteJob.bind(this);
}
TestServer.prototype.run = function() {
let _this = this;
return new Promise(function(resolve, reject) {
// Setup node env to test during test
process.env.TEST = 1;
// Create eae compute server
_this.eae_compute = new EaeCompute(config);
// Start server
_this.eae_compute.start().then(function (compute_router) {
_this._app.use(compute_router);
_this._server = _this._app.listen(config.port, function (error) {
if (error)
reject(error);
else {
resolve(true);
}
});
}, function (error) {
reject(error);
});
});
};
TestServer.prototype.stop = function() {
let _this = this;
return new Promise(function(resolve, reject) {
// Remove test flag from env
delete process.env.TEST;
_this.eae_compute.stop().then(function() {
_this._server.close(function(error) {
if (error)
reject(error);
else
resolve(true);
});
}, function (error) {
reject(error);
});
});
};
TestServer.prototype.mongo = function() {
return this.eae_compute.db;
};
TestServer.prototype.createJob = function(type, mainScript, params, inputFiles = []) {
let _this = this;
return new Promise(function(resolve, reject) {
let job_id = new ObjectID();
let input_container = job_id.toHexString() + '_input';
let output_container = job_id.toHexString() + '_output';
let job_model = Object.assign({},
eaeutils.DataModels.EAE_JOB_MODEL,
{
_id: job_id,
type: type,
main: mainScript,
params: params,
input: inputFiles.map(function (file) {
return path.basename(file);
})
}
);
// Insert in DB
_this.eae_compute.jobController._jobCollection.insertOne(job_model).then(function() {
// Upload files
let upload_promises = [];
// Create this job input container
_this._swift.createContainer(input_container).then(function() {
// Create each file
inputFiles.forEach(function (file) {
let rs = fs.createReadStream(file);
if (rs === undefined) {
reject(eaeutils.ErrorHelper(file + ' does not exists'));
return;
}
let up = _this._swift.createFile(input_container, path.basename(file), rs);
upload_promises.push(up);
});
//Adds in output container creation
upload_promises.push(_this._swift.createContainer(output_container));
Promise.all(upload_promises).then(function() {
resolve(job_model);
}, function(error) {
reject(error);
});
}, function(error) {
reject(error);
});
}, function(error) {
reject(error);
});
});
};
TestServer.prototype.deleteJob = function(job_model) {
let _this = this;
return new Promise(function(resolve, reject) {
let input_container = job_model._id.toHexString() + '_input';
let output_container = job_model._id.toHexString() + '_output';
let delete_promises = [];
// Delete input files
job_model.input.forEach(function (file) {
let dp = _this._swift.deleteFile(input_container, file);
delete_promises.push(dp);
});
// Delete output files
job_model.output.forEach(function (file) {
let dp = _this._swift.deleteFile(output_container, file);
delete_promises.push(dp);
});
// Wait all files deletes
Promise.all(delete_promises).then(function() {
// Wait for all containers delete
Promise.all([_this._swift.deleteContainer(input_container), _this._swift.deleteContainer(output_container)]).then(function() {
// Remove from DB
_this.eae_compute.jobController._jobCollection.deleteOne({_id : job_model._id}).then(function() {
resolve(true);
}, function(error) {
reject(error);
});
}, function(error) {
reject(error);
});
}, function(error) {
reject(error);
});
});
};
module.exports = TestServer;
| 34.604938 | 138 | 0.545309 |
3d8faee12882e2e513f86d1ef456dde58f7541c0 | 116 | js | JavaScript | test/handlers/syncHelloWorld.js | styfle/everynode | 34a70839d2f85474b78daeaf824c1aaa9460f605 | [
"MIT"
] | 78 | 2022-02-15T18:55:29.000Z | 2022-03-31T16:06:22.000Z | test/handlers/syncHelloWorld.js | styfle/everynode | 34a70839d2f85474b78daeaf824c1aaa9460f605 | [
"MIT"
] | 8 | 2022-02-26T03:11:51.000Z | 2022-03-30T16:30:39.000Z | test/handlers/syncHelloWorld.js | styfle/everynode | 34a70839d2f85474b78daeaf824c1aaa9460f605 | [
"MIT"
] | 1 | 2022-02-25T18:50:15.000Z | 2022-02-25T18:50:15.000Z | exports.handler = (event, context, callback) => {
return callback(null, { env: process.env, event, context });
};
| 29 | 62 | 0.663793 |
3d8fbeb24fa8fdec022b193c9681b0708ecbb9de | 742 | js | JavaScript | public/constants/index.js | stefli/sentinl | 2c6c7b005b4e9923953789590bebcecf17f61b29 | [
"Apache-2.0"
] | null | null | null | public/constants/index.js | stefli/sentinl | 2c6c7b005b4e9923953789590bebcecf17f61b29 | [
"Apache-2.0"
] | null | null | null | public/constants/index.js | stefli/sentinl | 2c6c7b005b4e9923953789590bebcecf17f61b29 | [
"Apache-2.0"
] | null | null | null | import { uiModules } from 'ui/modules';
import common from './common';
import emailWatcherAdvanced from './email_watcher_advanced';
import emailWatcherWizard from './email_watcher_wizard';
import emailWatcherDashboard from './email_watcher_dashboard';
import reportWatcher from './report_watcher';
import watcherScript from './watcher_script';
import api from './api';
const module = uiModules.get('apps/sentinl', []);
module
.constant('COMMON', common)
.constant('EMAILWATCHERADVANCED', emailWatcherAdvanced)
.constant('EMAILWATCHERWIZARD', emailWatcherWizard)
.constant('EMAILWATCHERDASHBOARD', emailWatcherDashboard)
.constant('REPORTWATCHER', reportWatcher)
.constant('API', api)
.constant('WATCHERSCRIPT', watcherScript);
| 39.052632 | 62 | 0.778976 |
3d90a7355815cd2f7216c44c52314eb7b9a32570 | 63,661 | js | JavaScript | lib/client/index.js | SwingbyProtocol/javascript-sdk | e36fe29dad2143b916620c7506f3f2ad753543bc | [
"Apache-2.0"
] | 1 | 2021-04-25T16:54:44.000Z | 2021-04-25T16:54:44.000Z | lib/client/index.js | SwingbyProtocol/javascript-sdk | e36fe29dad2143b916620c7506f3f2ad753543bc | [
"Apache-2.0"
] | null | null | null | lib/client/index.js | SwingbyProtocol/javascript-sdk | e36fe29dad2143b916620c7506f3f2ad753543bc | [
"Apache-2.0"
] | null | null | null | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BncClient = exports.LedgerSigningDelegate = exports.DefaultBroadcastDelegate = exports.DefaultSigningDelegate = exports.NETWORK_PREFIX_MAPPING = exports.api = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var crypto = _interopRequireWildcard(require("../crypto"));
var _tx = _interopRequireDefault(require("../tx"));
var _request = _interopRequireDefault(require("../utils/request"));
var _validateHelper = require("../utils/validateHelper");
var _token = _interopRequireDefault(require("./token"));
var _swap = _interopRequireDefault(require("./swap"));
var _gov = _interopRequireDefault(require("./gov"));
var _big = _interopRequireDefault(require("big.js"));
var _types = require("../types/");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var BASENUMBER = Math.pow(10, 8);
var api = {
broadcast: "/api/v1/broadcast",
nodeInfo: "/api/v1/node-info",
getAccount: "/api/v1/account",
getMarkets: "/api/v1/markets",
getSwaps: "/api/v1/atomic-swaps",
getOpenOrders: "/api/v1/orders/open",
getDepth: "/api/v1/depth",
getTransactions: "/api/v1/transactions",
getTx: "/api/v1/tx"
};
exports.api = api;
var NETWORK_PREFIX_MAPPING = {
testnet: "tbnb",
mainnet: "bnb"
};
exports.NETWORK_PREFIX_MAPPING = NETWORK_PREFIX_MAPPING;
/**
* The default signing delegate which uses the local private key.
* @param {Transaction} tx the transaction
* @param {Object} signMsg the canonical sign bytes for the msg
* @return {Transaction}
*/
var DefaultSigningDelegate = /*#__PURE__*/function () {
var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(tx, signMsg) {
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", tx.sign(this.privateKey, signMsg));
case 1:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
return function DefaultSigningDelegate(_x, _x2, _x3) {
return _ref.apply(this, arguments);
};
}();
/**
* The default broadcast delegate which immediately broadcasts a transaction.
* @param {Transaction} signedTx the signed transaction
*/
exports.DefaultSigningDelegate = DefaultSigningDelegate;
var DefaultBroadcastDelegate = /*#__PURE__*/function () {
var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(signedTx) {
return _regenerator["default"].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
return _context2.abrupt("return", this.sendTransaction(signedTx, true));
case 1:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
return function DefaultBroadcastDelegate(_x4, _x5) {
return _ref2.apply(this, arguments);
};
}();
/**
* The Ledger signing delegate.
* @param {LedgerApp} ledgerApp
* @param {preSignCb} function
* @param {postSignCb} function
* @param {errCb} function
* @return {function}
*/
exports.DefaultBroadcastDelegate = DefaultBroadcastDelegate;
var LedgerSigningDelegate = function LedgerSigningDelegate(ledgerApp, preSignCb, postSignCb, errCb, hdPath) {
return /*#__PURE__*/function () {
var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(tx, signMsg) {
var signBytes, pubKeyResp, sigResp, pubKey;
return _regenerator["default"].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
signBytes = tx.getSignBytes(signMsg);
preSignCb && preSignCb(signBytes);
_context3.prev = 2;
_context3.next = 5;
return ledgerApp.getPublicKey(hdPath);
case 5:
pubKeyResp = _context3.sent;
_context3.next = 8;
return ledgerApp.sign(signBytes, hdPath);
case 8:
sigResp = _context3.sent;
postSignCb && postSignCb(pubKeyResp, sigResp);
_context3.next = 16;
break;
case 12:
_context3.prev = 12;
_context3.t0 = _context3["catch"](2);
console.warn("LedgerSigningDelegate error", _context3.t0);
errCb && errCb(_context3.t0);
case 16:
if (!(sigResp && sigResp.signature)) {
_context3.next = 19;
break;
}
pubKey = crypto.getPublicKey(pubKeyResp.pk.toString("hex"));
return _context3.abrupt("return", tx.addSignature(pubKey, sigResp.signature));
case 19:
return _context3.abrupt("return", tx);
case 20:
case "end":
return _context3.stop();
}
}
}, _callee3, null, [[2, 12]]);
}));
return function (_x6, _x7) {
return _ref3.apply(this, arguments);
};
}();
};
/**
* validate the input number.
* @param {Array} outputs
*/
exports.LedgerSigningDelegate = LedgerSigningDelegate;
var checkOutputs = function checkOutputs(outputs) {
outputs.forEach(function (transfer) {
var coins = transfer.coins || [];
coins.forEach(function (coin) {
(0, _validateHelper.checkNumber)(coin.amount);
if (!coin.denom) {
throw new Error("invalid denmon");
}
});
});
};
/**
* sum corresponding input coin
* @param {Array} inputs
* @param {Array} coins
*/
var calInputCoins = function calInputCoins(inputs, coins) {
coins.forEach(function (coin) {
var existCoin = inputs[0].coins.find(function (c) {
return c.denom === coin.denom;
});
if (existCoin) {
var existAmount = new _big["default"](existCoin.amount);
existCoin.amount = Number(existAmount.plus(coin.amount).toString());
} else {
inputs[0].coins.push(_objectSpread({}, coin));
}
});
};
/**
* The Binance Chain client.
*/
var BncClient = /*#__PURE__*/function () {
/**
* @param {String} server Binance Chain public url
* @param {Boolean} useAsyncBroadcast use async broadcast mode, faster but less guarantees (default off)
* @param {Number} source where does this transaction come from (default 0)
*/
function BncClient(server) {
var useAsyncBroadcast = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var source = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
(0, _classCallCheck2["default"])(this, BncClient);
(0, _defineProperty2["default"])(this, "_httpClient", void 0);
(0, _defineProperty2["default"])(this, "_signingDelegate", void 0);
(0, _defineProperty2["default"])(this, "_broadcastDelegate", void 0);
(0, _defineProperty2["default"])(this, "_useAsyncBroadcast", void 0);
(0, _defineProperty2["default"])(this, "_source", void 0);
(0, _defineProperty2["default"])(this, "tokens", void 0);
(0, _defineProperty2["default"])(this, "swap", void 0);
(0, _defineProperty2["default"])(this, "gov", void 0);
(0, _defineProperty2["default"])(this, "chainId", void 0);
(0, _defineProperty2["default"])(this, "addressPrefix", "tbnb");
(0, _defineProperty2["default"])(this, "network", "testnet");
(0, _defineProperty2["default"])(this, "privateKey", void 0);
(0, _defineProperty2["default"])(this, "address", void 0);
(0, _defineProperty2["default"])(this, "_setPkPromise", void 0);
(0, _defineProperty2["default"])(this, "account_number", void 0);
if (!server) {
throw new Error("Binance chain server should not be null");
}
this._httpClient = new _request["default"](server);
this._signingDelegate = DefaultSigningDelegate;
this._broadcastDelegate = DefaultBroadcastDelegate;
this._useAsyncBroadcast = useAsyncBroadcast;
this._source = source;
this.tokens = new _token["default"](this);
this.swap = new _swap["default"](this);
this.gov = new _gov["default"](this);
this.privateKey = "";
}
/**
* Initialize the client with the chain's ID. Asynchronous.
* @return {Promise}
*/
(0, _createClass2["default"])(BncClient, [{
key: "initChain",
value: function () {
var _initChain = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() {
var data;
return _regenerator["default"].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (this.chainId) {
_context4.next = 5;
break;
}
_context4.next = 3;
return this._httpClient.request("get", api.nodeInfo);
case 3:
data = _context4.sent;
this.chainId = data.result.node_info && data.result.node_info.network;
case 5:
return _context4.abrupt("return", this);
case 6:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function initChain() {
return _initChain.apply(this, arguments);
}
return initChain;
}()
/**
* Sets the client network (testnet or mainnet).
* @param {String} network Indicate testnet or mainnet
*/
}, {
key: "chooseNetwork",
value: function chooseNetwork(network) {
this.addressPrefix = NETWORK_PREFIX_MAPPING[network] || "tbnb";
this.network = NETWORK_PREFIX_MAPPING[network] ? network : "testnet";
}
/**
* Sets the client's private key for calls made by this client. Asynchronous.
* @param {string} privateKey the private key hexstring
* @param {boolean} localOnly set this to true if you will supply an account_number yourself via `setAccountNumber`. Warning: You must do that if you set this to true!
* @return {Promise}
*/
}, {
key: "setPrivateKey",
value: function () {
var _setPrivateKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(privateKey) {
var localOnly,
address,
promise,
data,
_args5 = arguments;
return _regenerator["default"].wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
localOnly = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : false;
if (!(privateKey !== this.privateKey)) {
_context5.next = 21;
break;
}
address = crypto.getAddressFromPrivateKey(privateKey, this.addressPrefix);
if (address) {
_context5.next = 5;
break;
}
throw new Error("address is falsy: ".concat(address, ". invalid private key?"));
case 5:
if (!(address === this.address)) {
_context5.next = 7;
break;
}
return _context5.abrupt("return", this);
case 7:
// safety
this.privateKey = privateKey;
this.address = address;
if (localOnly) {
_context5.next = 21;
break;
}
_context5.prev = 10;
promise = this._setPkPromise = this._httpClient.request("get", "".concat(api.getAccount, "/").concat(address));
_context5.next = 14;
return promise;
case 14:
data = _context5.sent;
this.account_number = data.result.account_number;
_context5.next = 21;
break;
case 18:
_context5.prev = 18;
_context5.t0 = _context5["catch"](10);
throw new Error("unable to query the address on the blockchain. try sending it some funds first: ".concat(address));
case 21:
return _context5.abrupt("return", this);
case 22:
case "end":
return _context5.stop();
}
}
}, _callee5, this, [[10, 18]]);
}));
function setPrivateKey(_x8) {
return _setPrivateKey.apply(this, arguments);
}
return setPrivateKey;
}()
/**
* Sets the client's account number.
* @param {number} accountNumber
*/
}, {
key: "setAccountNumber",
value: function setAccountNumber(accountNumber) {
this.account_number = accountNumber;
}
/**
* Use async broadcast mode. Broadcasts faster with less guarantees (default off)
* @param {Boolean} useAsyncBroadcast
* @return {BncClient} this instance (for chaining)
*/
}, {
key: "useAsyncBroadcast",
value: function useAsyncBroadcast() {
var _useAsyncBroadcast = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
this._useAsyncBroadcast = _useAsyncBroadcast;
return this;
}
/**
* Sets the signing delegate (for wallet integrations).
* @param {function} delegate
* @return {BncClient} this instance (for chaining)
*/
}, {
key: "setSigningDelegate",
value: function setSigningDelegate(delegate) {
if (typeof delegate !== "function") throw new Error("signing delegate must be a function");
this._signingDelegate = delegate;
return this;
}
/**
* Sets the broadcast delegate (for wallet integrations).
* @param {function} delegate
* @return {BncClient} this instance (for chaining)
*/
}, {
key: "setBroadcastDelegate",
value: function setBroadcastDelegate(delegate) {
if (typeof delegate !== "function") throw new Error("broadcast delegate must be a function");
this._broadcastDelegate = delegate;
return this;
}
/**
* Applies the default signing delegate.
* @return {BncClient} this instance (for chaining)
*/
}, {
key: "useDefaultSigningDelegate",
value: function useDefaultSigningDelegate() {
this._signingDelegate = DefaultSigningDelegate;
return this;
}
/**
* Applies the default broadcast delegate.
* @return {BncClient} this instance (for chaining)
*/
}, {
key: "useDefaultBroadcastDelegate",
value: function useDefaultBroadcastDelegate() {
this._broadcastDelegate = DefaultBroadcastDelegate;
return this;
}
/**
* Applies the Ledger signing delegate.
* @param {function} ledgerApp
* @param {function} preSignCb
* @param {function} postSignCb
* @param {function} errCb
* @return {BncClient} this instance (for chaining)
*/
}, {
key: "useLedgerSigningDelegate",
value: function useLedgerSigningDelegate() {
this._signingDelegate = LedgerSigningDelegate.apply(void 0, arguments);
return this;
}
/**
* Transfer tokens from one address to another.
* @param {String} fromAddress
* @param {String} toAddress
* @param {Number} amount
* @param {String} asset
* @param {String} memo optional memo
* @param {Number} sequence optional sequence
* @return {Promise} resolves with response (success or fail)
*/
}, {
key: "transfer",
value: function () {
var _transfer = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(fromAddress, toAddress, amount, asset) {
var memo,
sequence,
accCode,
toAccCode,
coin,
msg,
signMsg,
signedTx,
_args6 = arguments;
return _regenerator["default"].wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
memo = _args6.length > 4 && _args6[4] !== undefined ? _args6[4] : "";
sequence = _args6.length > 5 && _args6[5] !== undefined ? _args6[5] : null;
accCode = crypto.decodeAddress(fromAddress);
toAccCode = crypto.decodeAddress(toAddress);
amount = new _big["default"](amount);
amount = Number(amount.mul(BASENUMBER).toString());
(0, _validateHelper.checkNumber)(amount, "amount");
coin = {
denom: asset,
amount: amount
};
msg = {
inputs: [{
address: accCode,
coins: [coin]
}],
outputs: [{
address: toAccCode,
coins: [coin]
}],
aminoPrefix: _types.AminoPrefix.MsgSend
};
signMsg = {
inputs: [{
address: fromAddress,
coins: [{
amount: amount,
denom: asset
}]
}],
outputs: [{
address: toAddress,
coins: [{
amount: amount,
denom: asset
}]
}]
};
_context6.next = 12;
return this._prepareTransaction(msg, signMsg, fromAddress, sequence, memo);
case 12:
signedTx = _context6.sent;
return _context6.abrupt("return", this._broadcastDelegate(signedTx));
case 14:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function transfer(_x9, _x10, _x11, _x12) {
return _transfer.apply(this, arguments);
}
return transfer;
}()
/**
* Create and sign a multi send tx
* @param {String} fromAddress
* @param {Array} outputs
* @example
* const outputs = [
* {
* "to": "tbnb1p4kpnj5qz5spsaf0d2555h6ctngse0me5q57qe",
* "coins": [{
* "denom": "BNB",
* "amount": 10
* },{
* "denom": "BTC",
* "amount": 10
* }]
* },
* {
* "to": "tbnb1scjj8chhhp7lngdeflltzex22yaf9ep59ls4gk",
* "coins": [{
* "denom": "BTC",
* "amount": 10
* },{
* "denom": "BNB",
* "amount": 10
* }]
* }]
* @param {String} memo optional memo
* @param {Number} sequence optional sequence
* @return {Promise} resolves with response (success or fail)
*/
}, {
key: "multiSend",
value: function () {
var _multiSend = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(fromAddress, outputs) {
var memo,
sequence,
fromAddrCode,
inputs,
transfers,
msg,
signInputs,
signOutputs,
signMsg,
signedTx,
_args7 = arguments;
return _regenerator["default"].wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
memo = _args7.length > 2 && _args7[2] !== undefined ? _args7[2] : "";
sequence = _args7.length > 3 && _args7[3] !== undefined ? _args7[3] : null;
if (fromAddress) {
_context7.next = 4;
break;
}
throw new Error("fromAddress should not be falsy");
case 4:
if (Array.isArray(outputs)) {
_context7.next = 6;
break;
}
throw new Error("outputs should be array");
case 6:
checkOutputs(outputs); //sort denom by alphbet and init amount
outputs.forEach(function (item) {
item.coins = item.coins.sort(function (a, b) {
return a.denom.localeCompare(b.denom);
});
item.coins.forEach(function (coin) {
var amount = new _big["default"](coin.amount);
coin.amount = Number(amount.mul(BASENUMBER).toString());
});
});
fromAddrCode = crypto.decodeAddress(fromAddress);
inputs = [{
address: fromAddrCode,
coins: []
}];
transfers = [];
outputs.forEach(function (item) {
var toAddcCode = crypto.decodeAddress(item.to);
calInputCoins(inputs, item.coins);
transfers.push({
address: toAddcCode,
coins: item.coins
});
});
msg = {
inputs: inputs,
outputs: transfers,
aminoPrefix: _types.AminoPrefix.MsgSend
};
signInputs = [{
address: fromAddress,
coins: []
}];
signOutputs = [];
outputs.forEach(function (item, index) {
signOutputs.push({
address: item.to,
coins: []
});
item.coins.forEach(function (c) {
signOutputs[index].coins.push(c);
});
calInputCoins(signInputs, item.coins);
});
signMsg = {
inputs: signInputs,
outputs: signOutputs
};
_context7.next = 19;
return this._prepareTransaction(msg, signMsg, fromAddress, sequence, memo);
case 19:
signedTx = _context7.sent;
return _context7.abrupt("return", this._broadcastDelegate(signedTx));
case 21:
case "end":
return _context7.stop();
}
}
}, _callee7, this);
}));
function multiSend(_x13, _x14) {
return _multiSend.apply(this, arguments);
}
return multiSend;
}()
/**
* Cancel an order.
* @param {String} fromAddress
* @param {String} symbol the market pair
* @param {String} refid the order ID of the order to cancel
* @param {Number} sequence optional sequence
* @return {Promise} resolves with response (success or fail)
*/
}, {
key: "cancelOrder",
value: function () {
var _cancelOrder = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(fromAddress, symbol, refid) {
var sequence,
accCode,
msg,
signMsg,
signedTx,
_args8 = arguments;
return _regenerator["default"].wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
sequence = _args8.length > 3 && _args8[3] !== undefined ? _args8[3] : null;
accCode = crypto.decodeAddress(fromAddress);
msg = {
sender: accCode,
symbol: symbol,
refid: refid,
aminoPrefix: _types.AminoPrefix.CancelOrderMsg
};
signMsg = {
refid: refid,
sender: fromAddress,
symbol: symbol
};
_context8.next = 6;
return this._prepareTransaction(msg, signMsg, fromAddress, sequence, "");
case 6:
signedTx = _context8.sent;
return _context8.abrupt("return", this._broadcastDelegate(signedTx));
case 8:
case "end":
return _context8.stop();
}
}
}, _callee8, this);
}));
function cancelOrder(_x15, _x16, _x17) {
return _cancelOrder.apply(this, arguments);
}
return cancelOrder;
}()
/**
* Place an order.
* @param {String} address
* @param {String} symbol the market pair
* @param {Number} side (1-Buy, 2-Sell)
* @param {Number} price
* @param {Number} quantity
* @param {Number} sequence optional sequence
* @param {Number} timeinforce (1-GTC(Good Till Expire), 3-IOC(Immediate or Cancel))
* @return {Promise} resolves with response (success or fail)
*/
}, {
key: "placeOrder",
value: function () {
var _placeOrder = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9() {
var address,
symbol,
side,
price,
quantity,
sequence,
timeinforce,
accCode,
data,
bigPrice,
bigQuantity,
placeOrderMsg,
signMsg,
signedTx,
_args9 = arguments;
return _regenerator["default"].wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
address = _args9.length > 0 && _args9[0] !== undefined ? _args9[0] : this.address;
symbol = _args9.length > 1 ? _args9[1] : undefined;
side = _args9.length > 2 ? _args9[2] : undefined;
price = _args9.length > 3 ? _args9[3] : undefined;
quantity = _args9.length > 4 ? _args9[4] : undefined;
sequence = _args9.length > 5 && _args9[5] !== undefined ? _args9[5] : null;
timeinforce = _args9.length > 6 && _args9[6] !== undefined ? _args9[6] : 1;
if (address) {
_context9.next = 9;
break;
}
throw new Error("address should not be falsy");
case 9:
if (symbol) {
_context9.next = 11;
break;
}
throw new Error("symbol should not be falsy");
case 11:
if (!(side !== 1 && side !== 2)) {
_context9.next = 13;
break;
}
throw new Error("side can only be 1 or 2");
case 13:
if (!(timeinforce !== 1 && timeinforce !== 3)) {
_context9.next = 15;
break;
}
throw new Error("timeinforce can only be 1 or 3");
case 15:
accCode = crypto.decodeAddress(address);
if (!(sequence !== 0 && !sequence)) {
_context9.next = 21;
break;
}
_context9.next = 19;
return this._httpClient.request("get", "".concat(api.getAccount, "/").concat(address));
case 19:
data = _context9.sent;
sequence = data.result && data.result.sequence;
case 21:
bigPrice = new _big["default"](price);
bigQuantity = new _big["default"](quantity);
placeOrderMsg = {
sender: accCode,
id: "".concat(accCode.toString("hex"), "-").concat(sequence + 1).toUpperCase(),
symbol: symbol,
ordertype: 2,
side: side,
price: parseFloat(bigPrice.mul(BASENUMBER).toString()),
quantity: parseFloat(bigQuantity.mul(BASENUMBER).toString()),
timeinforce: timeinforce,
aminoPrefix: _types.AminoPrefix.NewOrderMsg
};
signMsg = {
id: placeOrderMsg.id,
ordertype: placeOrderMsg.ordertype,
price: placeOrderMsg.price,
quantity: placeOrderMsg.quantity,
sender: address,
side: placeOrderMsg.side,
symbol: placeOrderMsg.symbol,
timeinforce: timeinforce
};
(0, _validateHelper.checkNumber)(placeOrderMsg.price, "price");
(0, _validateHelper.checkNumber)(placeOrderMsg.quantity, "quantity");
_context9.next = 29;
return this._prepareTransaction(placeOrderMsg, signMsg, address, sequence, "");
case 29:
signedTx = _context9.sent;
return _context9.abrupt("return", this._broadcastDelegate(signedTx));
case 31:
case "end":
return _context9.stop();
}
}
}, _callee9, this);
}));
function placeOrder() {
return _placeOrder.apply(this, arguments);
}
return placeOrder;
}()
/**
* @param {String} address
* @param {Number} proposalId
* @param {String} baseAsset
* @param {String} quoteAsset
* @param {Number} initPrice
* @param {Number} sequence optional sequence
* @return {Promise} resolves with response (success or fail)
*/
}, {
key: "list",
value: function () {
var _list = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(address, proposalId, baseAsset, quoteAsset, initPrice) {
var sequence,
accCode,
init_price,
listMsg,
signMsg,
signedTx,
_args10 = arguments;
return _regenerator["default"].wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
sequence = _args10.length > 5 && _args10[5] !== undefined ? _args10[5] : null;
accCode = crypto.decodeAddress(address);
if (address) {
_context10.next = 4;
break;
}
throw new Error("address should not be falsy");
case 4:
if (!(proposalId <= 0)) {
_context10.next = 6;
break;
}
throw new Error("proposal id should larger than 0");
case 6:
if (!(initPrice <= 0)) {
_context10.next = 8;
break;
}
throw new Error("price should larger than 0");
case 8:
if (baseAsset) {
_context10.next = 10;
break;
}
throw new Error("baseAsset should not be falsy");
case 10:
if (quoteAsset) {
_context10.next = 12;
break;
}
throw new Error("quoteAsset should not be falsy");
case 12:
init_price = Number(new _big["default"](initPrice).mul(BASENUMBER).toString());
listMsg = {
from: accCode,
proposal_id: proposalId,
base_asset_symbol: baseAsset,
quote_asset_symbol: quoteAsset,
init_price: init_price,
aminoPrefix: _types.AminoPrefix.ListMsg
};
signMsg = {
base_asset_symbol: baseAsset,
from: address,
init_price: init_price,
proposal_id: proposalId,
quote_asset_symbol: quoteAsset
};
_context10.next = 17;
return this._prepareTransaction(listMsg, signMsg, address, sequence, "");
case 17:
signedTx = _context10.sent;
return _context10.abrupt("return", this._broadcastDelegate(signedTx));
case 19:
case "end":
return _context10.stop();
}
}
}, _callee10, this);
}));
function list(_x18, _x19, _x20, _x21, _x22) {
return _list.apply(this, arguments);
}
return list;
}()
/**
* Set account flags
* @param {String} address
* @param {Number} flags new value of account flags
* @param {Number} sequence optional sequence
* @return {Promise} resolves with response (success or fail)
*/
}, {
key: "setAccountFlags",
value: function () {
var _setAccountFlags = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(address, flags) {
var sequence,
accCode,
msg,
signMsg,
signedTx,
_args11 = arguments;
return _regenerator["default"].wrap(function _callee11$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
sequence = _args11.length > 2 && _args11[2] !== undefined ? _args11[2] : null;
accCode = crypto.decodeAddress(address);
msg = {
from: accCode,
flags: flags,
aminoPrefix: _types.AminoPrefix.SetAccountFlagsMsg
};
signMsg = {
flags: flags,
from: address
};
_context11.next = 6;
return this._prepareTransaction(msg, signMsg, address, sequence, "");
case 6:
signedTx = _context11.sent;
return _context11.abrupt("return", this._broadcastDelegate(signedTx));
case 8:
case "end":
return _context11.stop();
}
}
}, _callee11, this);
}));
function setAccountFlags(_x23, _x24) {
return _setAccountFlags.apply(this, arguments);
}
return setAccountFlags;
}()
/**
* Prepare a serialized raw transaction for sending to the blockchain.
* @param {Object} msg the msg object
* @param {Object} stdSignMsg the sign doc object used to generate a signature
* @param {String} address
* @param {Number} sequence optional sequence
* @param {String} memo optional memo
* @return {Transaction} signed transaction
*/
}, {
key: "_prepareTransaction",
value: function () {
var _prepareTransaction2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(msg, stdSignMsg, address) {
var sequence,
memo,
data,
tx,
_args12 = arguments;
return _regenerator["default"].wrap(function _callee12$(_context12) {
while (1) {
switch (_context12.prev = _context12.next) {
case 0:
sequence = _args12.length > 3 && _args12[3] !== undefined ? _args12[3] : null;
memo = _args12.length > 4 && _args12[4] !== undefined ? _args12[4] : "";
if (!((!this.account_number || sequence !== 0 && !sequence) && address)) {
_context12.next = 10;
break;
}
_context12.next = 5;
return this._httpClient.request("get", "".concat(api.getAccount, "/").concat(address));
case 5:
data = _context12.sent;
sequence = data.result.sequence;
this.account_number = data.result.account_number; // if user has not used `await` in its call to setPrivateKey (old API), we should wait for the promise here
_context12.next = 13;
break;
case 10:
if (!this._setPkPromise) {
_context12.next = 13;
break;
}
_context12.next = 13;
return this._setPkPromise;
case 13:
tx = new _tx["default"]({
accountNumber: typeof this.account_number !== "number" ? parseInt(this.account_number) : this.account_number,
chainId: this.chainId,
memo: memo,
msg: msg,
sequence: typeof sequence !== "number" ? parseInt(sequence) : sequence,
source: this._source
});
return _context12.abrupt("return", this._signingDelegate.call(this, tx, stdSignMsg));
case 15:
case "end":
return _context12.stop();
}
}
}, _callee12, this);
}));
function _prepareTransaction(_x25, _x26, _x27) {
return _prepareTransaction2.apply(this, arguments);
}
return _prepareTransaction;
}()
/**
* Broadcast a transaction to the blockchain.
* @param {signedTx} tx signed Transaction object
* @param {Boolean} sync use synchronous mode, optional
* @return {Promise} resolves with response (success or fail)
*/
}, {
key: "sendTransaction",
value: function () {
var _sendTransaction2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(signedTx, sync) {
var signedBz;
return _regenerator["default"].wrap(function _callee13$(_context13) {
while (1) {
switch (_context13.prev = _context13.next) {
case 0:
signedBz = signedTx.serialize();
return _context13.abrupt("return", this.sendRawTransaction(signedBz, sync));
case 2:
case "end":
return _context13.stop();
}
}
}, _callee13, this);
}));
function sendTransaction(_x28, _x29) {
return _sendTransaction2.apply(this, arguments);
}
return sendTransaction;
}()
/**
* Broadcast a raw transaction to the blockchain.
* @param {String} signedBz signed and serialized raw transaction
* @param {Boolean} sync use synchronous mode, optional
* @return {Promise} resolves with response (success or fail)
*/
}, {
key: "sendRawTransaction",
value: function () {
var _sendRawTransaction = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee14(signedBz) {
var sync,
opts,
_args14 = arguments;
return _regenerator["default"].wrap(function _callee14$(_context14) {
while (1) {
switch (_context14.prev = _context14.next) {
case 0:
sync = _args14.length > 1 && _args14[1] !== undefined ? _args14[1] : !this._useAsyncBroadcast;
opts = {
data: signedBz,
headers: {
"content-type": "text/plain"
}
};
return _context14.abrupt("return", this._httpClient.request("post", "".concat(api.broadcast, "?sync=").concat(sync), null, opts));
case 3:
case "end":
return _context14.stop();
}
}
}, _callee14, this);
}));
function sendRawTransaction(_x30) {
return _sendRawTransaction.apply(this, arguments);
}
return sendRawTransaction;
}()
/**
* Broadcast a raw transaction to the blockchain.
* @param {Object} msg the msg object
* @param {Object} stdSignMsg the sign doc object used to generate a signature
* @param {String} address
* @param {Number} sequence optional sequence
* @param {String} memo optional memo
* @param {Boolean} sync use synchronous mode, optional
* @return {Promise} resolves with response (success or fail)
*/
}, {
key: "_sendTransaction",
value: function () {
var _sendTransaction3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee15(msg, stdSignMsg, address) {
var sequence,
memo,
sync,
signedTx,
_args15 = arguments;
return _regenerator["default"].wrap(function _callee15$(_context15) {
while (1) {
switch (_context15.prev = _context15.next) {
case 0:
sequence = _args15.length > 3 && _args15[3] !== undefined ? _args15[3] : null;
memo = _args15.length > 4 && _args15[4] !== undefined ? _args15[4] : "";
sync = _args15.length > 5 && _args15[5] !== undefined ? _args15[5] : !this._useAsyncBroadcast;
_context15.next = 5;
return this._prepareTransaction(msg, stdSignMsg, address, sequence, memo);
case 5:
signedTx = _context15.sent;
return _context15.abrupt("return", this.sendTransaction(signedTx, sync));
case 7:
case "end":
return _context15.stop();
}
}
}, _callee15, this);
}));
function _sendTransaction(_x31, _x32, _x33) {
return _sendTransaction3.apply(this, arguments);
}
return _sendTransaction;
}()
/**
* get account
* @param {String} address
* @return {Promise} resolves with http response
*/
}, {
key: "getAccount",
value: function () {
var _getAccount = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee16() {
var address,
data,
_args16 = arguments;
return _regenerator["default"].wrap(function _callee16$(_context16) {
while (1) {
switch (_context16.prev = _context16.next) {
case 0:
address = _args16.length > 0 && _args16[0] !== undefined ? _args16[0] : this.address;
if (address) {
_context16.next = 3;
break;
}
throw new Error("address should not be falsy");
case 3:
_context16.prev = 3;
_context16.next = 6;
return this._httpClient.request("get", "".concat(api.getAccount, "/").concat(address));
case 6:
data = _context16.sent;
return _context16.abrupt("return", data);
case 10:
_context16.prev = 10;
_context16.t0 = _context16["catch"](3);
return _context16.abrupt("return", null);
case 13:
case "end":
return _context16.stop();
}
}
}, _callee16, this, [[3, 10]]);
}));
function getAccount() {
return _getAccount.apply(this, arguments);
}
return getAccount;
}()
/**
* get balances
* @param {String} address optional address
* @return {Promise} resolves with http response
*/
}, {
key: "getBalance",
value: function () {
var _getBalance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee17() {
var address,
data,
_args17 = arguments;
return _regenerator["default"].wrap(function _callee17$(_context17) {
while (1) {
switch (_context17.prev = _context17.next) {
case 0:
address = _args17.length > 0 && _args17[0] !== undefined ? _args17[0] : this.address;
_context17.prev = 1;
_context17.next = 4;
return this.getAccount(address);
case 4:
data = _context17.sent;
return _context17.abrupt("return", data.result.balances);
case 8:
_context17.prev = 8;
_context17.t0 = _context17["catch"](1);
return _context17.abrupt("return", []);
case 11:
case "end":
return _context17.stop();
}
}
}, _callee17, this, [[1, 8]]);
}));
function getBalance() {
return _getBalance.apply(this, arguments);
}
return getBalance;
}()
/**
* get markets
* @param {Number} limit max 1000 is default
* @param {Number} offset from beggining, default 0
* @return {Promise} resolves with http response
*/
}, {
key: "getMarkets",
value: function () {
var _getMarkets = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee18() {
var limit,
offset,
data,
_args18 = arguments;
return _regenerator["default"].wrap(function _callee18$(_context18) {
while (1) {
switch (_context18.prev = _context18.next) {
case 0:
limit = _args18.length > 0 && _args18[0] !== undefined ? _args18[0] : 1000;
offset = _args18.length > 1 && _args18[1] !== undefined ? _args18[1] : 0;
_context18.prev = 2;
_context18.next = 5;
return this._httpClient.request("get", "".concat(api.getMarkets, "?limit=").concat(limit, "&offset=").concat(offset));
case 5:
data = _context18.sent;
return _context18.abrupt("return", data);
case 9:
_context18.prev = 9;
_context18.t0 = _context18["catch"](2);
console.warn("getMarkets error", _context18.t0);
return _context18.abrupt("return", []);
case 13:
case "end":
return _context18.stop();
}
}
}, _callee18, this, [[2, 9]]);
}));
function getMarkets() {
return _getMarkets.apply(this, arguments);
}
return getMarkets;
}()
/**
* get transactions for an account
* @param {String} address optional address
* @param {Number} offset from beggining, default 0
* @return {Promise} resolves with http response
*/
}, {
key: "getTransactions",
value: function () {
var _getTransactions = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee19() {
var address,
offset,
data,
_args19 = arguments;
return _regenerator["default"].wrap(function _callee19$(_context19) {
while (1) {
switch (_context19.prev = _context19.next) {
case 0:
address = _args19.length > 0 && _args19[0] !== undefined ? _args19[0] : this.address;
offset = _args19.length > 1 && _args19[1] !== undefined ? _args19[1] : 0;
_context19.prev = 2;
_context19.next = 5;
return this._httpClient.request("get", "".concat(api.getTransactions, "?address=").concat(address, "&offset=").concat(offset));
case 5:
data = _context19.sent;
return _context19.abrupt("return", data);
case 9:
_context19.prev = 9;
_context19.t0 = _context19["catch"](2);
console.warn("getTransactions error", _context19.t0);
return _context19.abrupt("return", []);
case 13:
case "end":
return _context19.stop();
}
}
}, _callee19, this, [[2, 9]]);
}));
function getTransactions() {
return _getTransactions.apply(this, arguments);
}
return getTransactions;
}()
/**
* get transaction
* @param {String} hash the transaction hash
* @return {Promise} resolves with http response
*/
}, {
key: "getTx",
value: function () {
var _getTx = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee20(hash) {
var data;
return _regenerator["default"].wrap(function _callee20$(_context20) {
while (1) {
switch (_context20.prev = _context20.next) {
case 0:
_context20.prev = 0;
_context20.next = 3;
return this._httpClient.request("get", "".concat(api.getTx, "/").concat(hash));
case 3:
data = _context20.sent;
return _context20.abrupt("return", data);
case 7:
_context20.prev = 7;
_context20.t0 = _context20["catch"](0);
console.warn("getTx error", _context20.t0);
return _context20.abrupt("return", []);
case 11:
case "end":
return _context20.stop();
}
}
}, _callee20, this, [[0, 7]]);
}));
function getTx(_x34) {
return _getTx.apply(this, arguments);
}
return getTx;
}()
/**
* get depth for a given market
* @param {String} symbol the market pair
* @return {Promise} resolves with http response
*/
}, {
key: "getDepth",
value: function () {
var _getDepth = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee21() {
var symbol,
data,
_args21 = arguments;
return _regenerator["default"].wrap(function _callee21$(_context21) {
while (1) {
switch (_context21.prev = _context21.next) {
case 0:
symbol = _args21.length > 0 && _args21[0] !== undefined ? _args21[0] : "BNB_BUSD-BD1";
_context21.prev = 1;
_context21.next = 4;
return this._httpClient.request("get", "".concat(api.getDepth, "?symbol=").concat(symbol));
case 4:
data = _context21.sent;
return _context21.abrupt("return", data);
case 8:
_context21.prev = 8;
_context21.t0 = _context21["catch"](1);
console.warn("getDepth error", _context21.t0);
return _context21.abrupt("return", []);
case 12:
case "end":
return _context21.stop();
}
}
}, _callee21, this, [[1, 8]]);
}));
function getDepth() {
return _getDepth.apply(this, arguments);
}
return getDepth;
}()
/**
* get open orders for an address
* @param {String} address binance address
* @param {String} symbol binance BEP2 symbol
* @return {Promise} resolves with http response
*/
}, {
key: "getOpenOrders",
value: function () {
var _getOpenOrders = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee22() {
var address,
data,
_args22 = arguments;
return _regenerator["default"].wrap(function _callee22$(_context22) {
while (1) {
switch (_context22.prev = _context22.next) {
case 0:
address = _args22.length > 0 && _args22[0] !== undefined ? _args22[0] : this.address;
_context22.prev = 1;
_context22.next = 4;
return this._httpClient.request("get", "".concat(api.getOpenOrders, "?address=").concat(address));
case 4:
data = _context22.sent;
return _context22.abrupt("return", data);
case 8:
_context22.prev = 8;
_context22.t0 = _context22["catch"](1);
console.warn("getOpenOrders error", _context22.t0);
return _context22.abrupt("return", []);
case 12:
case "end":
return _context22.stop();
}
}
}, _callee22, this, [[1, 8]]);
}));
function getOpenOrders() {
return _getOpenOrders.apply(this, arguments);
}
return getOpenOrders;
}()
/**
* get atomic swap
* @param {String} swapID: ID of an existing swap
* @return {Promise} AtomicSwap
*/
}, {
key: "getSwapByID",
value: function () {
var _getSwapByID = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee23(swapID) {
var data;
return _regenerator["default"].wrap(function _callee23$(_context23) {
while (1) {
switch (_context23.prev = _context23.next) {
case 0:
_context23.prev = 0;
_context23.next = 3;
return this._httpClient.request("get", "".concat(api.getSwaps, "/").concat(swapID));
case 3:
data = _context23.sent;
return _context23.abrupt("return", data);
case 7:
_context23.prev = 7;
_context23.t0 = _context23["catch"](0);
console.warn("query swap by swapID error", _context23.t0);
return _context23.abrupt("return", []);
case 11:
case "end":
return _context23.stop();
}
}
}, _callee23, this, [[0, 7]]);
}));
function getSwapByID(_x35) {
return _getSwapByID.apply(this, arguments);
}
return getSwapByID;
}()
/**
* query atomic swap list by creator address
* @param {String} creator: swap creator address
* @param {Number} offset from beginning, default 0
* @param {Number} limit, max 1000 is default
* @return {Promise} Array of AtomicSwap
*/
}, {
key: "getSwapByCreator",
value: function () {
var _getSwapByCreator = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee24(creator) {
var limit,
offset,
data,
_args24 = arguments;
return _regenerator["default"].wrap(function _callee24$(_context24) {
while (1) {
switch (_context24.prev = _context24.next) {
case 0:
limit = _args24.length > 1 && _args24[1] !== undefined ? _args24[1] : 100;
offset = _args24.length > 2 && _args24[2] !== undefined ? _args24[2] : 0;
_context24.prev = 2;
_context24.next = 5;
return this._httpClient.request("get", "".concat(api.getSwaps, "?fromAddress=").concat(creator, "&limit=").concat(limit, "&offset=").concat(offset));
case 5:
data = _context24.sent;
return _context24.abrupt("return", data);
case 9:
_context24.prev = 9;
_context24.t0 = _context24["catch"](2);
console.warn("query swap list by swap creator error", _context24.t0);
return _context24.abrupt("return", []);
case 13:
case "end":
return _context24.stop();
}
}
}, _callee24, this, [[2, 9]]);
}));
function getSwapByCreator(_x36) {
return _getSwapByCreator.apply(this, arguments);
}
return getSwapByCreator;
}()
/**
* query atomic swap list by recipient address
* @param {String} recipient: the recipient address of the swap
* @param {Number} offset from beginning, default 0
* @param {Number} limit, max 1000 is default
* @return {Promise} Array of AtomicSwap
*/
}, {
key: "getSwapByRecipient",
value: function () {
var _getSwapByRecipient = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee25(recipient) {
var limit,
offset,
data,
_args25 = arguments;
return _regenerator["default"].wrap(function _callee25$(_context25) {
while (1) {
switch (_context25.prev = _context25.next) {
case 0:
limit = _args25.length > 1 && _args25[1] !== undefined ? _args25[1] : 100;
offset = _args25.length > 2 && _args25[2] !== undefined ? _args25[2] : 0;
_context25.prev = 2;
_context25.next = 5;
return this._httpClient.request("get", "".concat(api.getSwaps, "?toAddress=").concat(recipient, "&limit=").concat(limit, "&offset=").concat(offset));
case 5:
data = _context25.sent;
return _context25.abrupt("return", data);
case 9:
_context25.prev = 9;
_context25.t0 = _context25["catch"](2);
console.warn("query swap list by swap recipient error", _context25.t0);
return _context25.abrupt("return", []);
case 13:
case "end":
return _context25.stop();
}
}
}, _callee25, this, [[2, 9]]);
}));
function getSwapByRecipient(_x37) {
return _getSwapByRecipient.apply(this, arguments);
}
return getSwapByRecipient;
}()
/**
* Creates a private key and returns it and its address.
* @return {object} the private key and address in an object.
* {
* address,
* privateKey
* }
*/
}, {
key: "createAccount",
value: function createAccount() {
var privateKey = crypto.generatePrivateKey();
return {
privateKey: privateKey,
address: crypto.getAddressFromPrivateKey(privateKey, this.addressPrefix)
};
}
/**
* Creates an account keystore object, and returns the private key and address.
* @param {String} password
* {
* privateKey,
* address,
* keystore
* }
*/
}, {
key: "createAccountWithKeystore",
value: function createAccountWithKeystore(password) {
if (!password) {
throw new Error("password should not be falsy");
}
var privateKey = crypto.generatePrivateKey();
var address = crypto.getAddressFromPrivateKey(privateKey, this.addressPrefix);
var keystore = crypto.generateKeyStore(privateKey, password);
return {
privateKey: privateKey,
address: address,
keystore: keystore
};
}
/**
* Creates an account from mnemonic seed phrase.
* @return {object}
* {
* privateKey,
* address,
* mnemonic
* }
*/
}, {
key: "createAccountWithMneomnic",
value: function createAccountWithMneomnic() {
var mnemonic = crypto.generateMnemonic();
var privateKey = crypto.getPrivateKeyFromMnemonic(mnemonic);
var address = crypto.getAddressFromPrivateKey(privateKey, this.addressPrefix);
return {
privateKey: privateKey,
address: address,
mnemonic: mnemonic
};
}
/**
* Recovers an account from a keystore object.
* @param {object} keystore object.
* @param {string} password password.
* {
* privateKey,
* address
* }
*/
}, {
key: "recoverAccountFromKeystore",
value: function recoverAccountFromKeystore(keystore, password) {
var privateKey = crypto.getPrivateKeyFromKeyStore(keystore, password);
var address = crypto.getAddressFromPrivateKey(privateKey, this.addressPrefix);
return {
privateKey: privateKey,
address: address
};
}
/**
* Recovers an account from a mnemonic seed phrase.
* @param {string} mneomnic
* {
* privateKey,
* address
* }
*/
}, {
key: "recoverAccountFromMnemonic",
value: function recoverAccountFromMnemonic(mnemonic) {
var privateKey = crypto.getPrivateKeyFromMnemonic(mnemonic);
var address = crypto.getAddressFromPrivateKey(privateKey, this.addressPrefix);
return {
privateKey: privateKey,
address: address
};
} // support an old method name containing a typo
}, {
key: "recoverAccountFromMneomnic",
value: function recoverAccountFromMneomnic(mnemonic) {
return this.recoverAccountFromMnemonic(mnemonic);
}
/**
* Recovers an account using private key.
* @param {String} privateKey
* {
* privateKey,
* address
* }
*/
}, {
key: "recoverAccountFromPrivateKey",
value: function recoverAccountFromPrivateKey(privateKey) {
var address = crypto.getAddressFromPrivateKey(privateKey, this.addressPrefix);
return {
privateKey: privateKey,
address: address
};
}
/**
* Validates an address.
* @param {String} address
* @param {String} prefix
* @return {Boolean}
*/
}, {
key: "checkAddress",
value: function checkAddress(address) {
var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.addressPrefix;
return crypto.checkAddress(address, prefix);
}
/**
* Returns the address for the current account if setPrivateKey has been called on this client.
* @return {String}
*/
}, {
key: "getClientKeyAddress",
value: function getClientKeyAddress() {
if (!this.privateKey) throw new Error("no private key is set on this client");
var address = crypto.getAddressFromPrivateKey(this.privateKey, this.addressPrefix);
this.address = address;
return address;
}
}]);
return BncClient;
}();
exports.BncClient = BncClient; | 33.312925 | 551 | 0.537865 |
3d90b25c409d646bb484e27363ef97f4ae8cb85b | 5,390 | js | JavaScript | app/containers/LogPage.js | tomrule007/grinding | a876902875bfc9b6bcc27e33d6be28cd2ffd0e68 | [
"MIT"
] | null | null | null | app/containers/LogPage.js | tomrule007/grinding | a876902875bfc9b6bcc27e33d6be28cd2ffd0e68 | [
"MIT"
] | 19 | 2019-07-30T20:07:28.000Z | 2021-01-28T20:08:30.000Z | app/containers/LogPage.js | tomrule007/grinding | a876902875bfc9b6bcc27e33d6be28cd2ffd0e68 | [
"MIT"
] | null | null | null | import React, { Component, forwardRef } from 'react';
import MaterialTable from 'material-table';
import Typography from '@material-ui/core/Typography';
// ICON SUPPORT
import AddBox from '@material-ui/icons/AddBox';
import ArrowUpward from '@material-ui/icons/ArrowUpward';
import Check from '@material-ui/icons/Check';
import ChevronLeft from '@material-ui/icons/ChevronLeft';
import ChevronRight from '@material-ui/icons/ChevronRight';
import Clear from '@material-ui/icons/Clear';
import DeleteOutline from '@material-ui/icons/DeleteOutline';
import Edit from '@material-ui/icons/Edit';
import FilterList from '@material-ui/icons/FilterList';
import FirstPage from '@material-ui/icons/FirstPage';
import LastPage from '@material-ui/icons/LastPage';
import Remove from '@material-ui/icons/Remove';
import SaveAlt from '@material-ui/icons/SaveAlt';
import Search from '@material-ui/icons/Search';
import ViewColumn from '@material-ui/icons/ViewColumn';
//Mood Icons
import CloseIcon from '@material-ui/icons/Close';
import VeryDissatisfied from '@material-ui/icons/SentimentVeryDissatisfiedOutlined';
import Dissatisfied from '@material-ui/icons/SentimentDissatisfiedOutlined';
import VerySatisfied from '@material-ui/icons/SentimentVerySatisfiedOutlined';
import Satisfied from '@material-ui/icons/SentimentSatisfiedOutlined';
import localStore from '../utils/localStore';
const tableIcons = {
Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
DetailPanel: forwardRef((props, ref) => (
<ChevronRight {...props} ref={ref} />
)),
Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
PreviousPage: forwardRef((props, ref) => (
<ChevronLeft {...props} ref={ref} />
)),
ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
SortArrow: forwardRef((props, ref) => <ArrowUpward {...props} ref={ref} />),
ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />)
};
// END ICON SUPPORT
type Props = {};
const moodToIcon = mood => {
switch (mood) {
case 'VeryDissatisfied':
return <VeryDissatisfied fontSize="large" />;
case 'Dissatisfied':
return <Dissatisfied fontSize="large" />;
case 'Satisfied':
return <Satisfied fontSize="large" />;
case 'VerySatisfied':
return <VerySatisfied fontSize="large" />;
default:
return <div>N/A</div>;
}
};
const formatJustTime = ms =>
new Date(ms).toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit'
});
const formatJustDate = ms => new Date(ms).toLocaleDateString('en-US');
const formatTime = ms => {
const minutes = Math.floor(ms / 1000 / 60);
const hours = Math.floor(minutes / 60);
return minutes < 60 ? `${minutes} Minutes` : `${hours}:${minutes % 60} Hours`;
};
export default class LogPage extends Component<Props> {
constructor(props) {
super(props);
// @TODO log wrapper that tells children to update when log data changes and also allow table to update log data store.
const logData = localStore.get('log');
this.state = {
columns: [
{
title: 'Grinding Time',
field: 'gTime',
editable: 'never',
render: ({ gTime }) => formatTime(gTime)
},
{
title: 'Start Time',
field: 'start',
editable: 'never',
render: ({ start }) => formatJustDate(start)
},
{ title: 'Tag', field: 'tag' },
{
title: 'Mood',
field: 'mood',
render: ({ mood }) => moodToIcon(mood)
}
],
data: logData
};
}
render() {
return (
<div style={{ maxWidth: '100%' }}>
<MaterialTable
icons={tableIcons}
columns={this.state.columns}
data={this.state.data}
onRowClick={(event, rowData, togglePanel) => togglePanel()}
detailPanel={rowData => {
return (
<div>
<Typography component="p">
<b>Goal: </b> {rowData.goal}
</Typography>
<Typography component="p">
<b>Comment: </b> {rowData.comment}
</Typography>
<Typography component="p">
<b>Start:</b> {formatJustTime(rowData.start)}
{' '}
<b>Stop:</b> {formatJustTime(rowData.stop)}
</Typography>
<Typography component="p" />
</div>
);
}}
options={{
exportButton: true
}}
title="Grinding Log"
/>
</div>
);
}
}
| 35 | 123 | 0.600742 |
3d917e781d661fe46d3b3ced56cf82d9d04ae5cc | 106 | js | JavaScript | LightTemperatureSensor/lib/STM32 B_LUX_D_V32/CMSIS/Documentation/Core/html/search/groups_64.js | zhangxinhui02/ArduinoProjects | 776ed431f9e945f2068ceb5395cab6401b3ae670 | [
"Apache-2.0"
] | 1 | 2021-07-07T23:22:26.000Z | 2021-07-07T23:22:26.000Z | LightTemperatureSensor/lib/STM32 B_LUX_D_V32/CMSIS/Documentation/Core/html/search/groups_64.js | zhangxinhui02/ArduinoProjects | 776ed431f9e945f2068ceb5395cab6401b3ae670 | [
"Apache-2.0"
] | null | null | null | LightTemperatureSensor/lib/STM32 B_LUX_D_V32/CMSIS/Documentation/Core/html/search/groups_64.js | zhangxinhui02/ArduinoProjects | 776ed431f9e945f2068ceb5395cab6401b3ae670 | [
"Apache-2.0"
] | null | null | null | var searchData=
[
['debug_20access',['Debug Access',['../group___i_t_m___debug__gr.html',1,'']]]
];
| 21.2 | 81 | 0.641509 |
3d91839228e079f894fca51fd0eeba75be70cf8f | 285 | js | JavaScript | lib/isHMRUpdate.js | henrikhermansen/assets-webpack-plugin | 49cbde56282d3b4769cdad74c6ea3d7352fec00c | [
"MIT"
] | null | null | null | lib/isHMRUpdate.js | henrikhermansen/assets-webpack-plugin | 49cbde56282d3b4769cdad74c6ea3d7352fec00c | [
"MIT"
] | null | null | null | lib/isHMRUpdate.js | henrikhermansen/assets-webpack-plugin | 49cbde56282d3b4769cdad74c6ea3d7352fec00c | [
"MIT"
] | null | null | null | const pathTemplate = require('./pathTemplate')
module.exports = function isHMRUpdate (options, asset) {
const hotUpdateChunkFilename = options.output.hotUpdateChunkFilename
const hotUpdateTemplate = pathTemplate(hotUpdateChunkFilename)
return hotUpdateTemplate.matches(asset)
}
| 35.625 | 70 | 0.817544 |
3d91c125dd23ffce1f092a46c26f76fca078d4e1 | 514 | js | JavaScript | public/admin/master/components/bootstrapui/buttons.controller.js | rolfisub/riskman-dashboard | 64800573e8c52162c101a5c4da7315bbd8036c9c | [
"BSD-3-Clause"
] | 1 | 2019-05-01T14:09:45.000Z | 2019-05-01T14:09:45.000Z | public/admin/master/components/bootstrapui/buttons.controller.js | rolfisub/riskman-dashboard | 64800573e8c52162c101a5c4da7315bbd8036c9c | [
"BSD-3-Clause"
] | null | null | null | public/admin/master/components/bootstrapui/buttons.controller.js | rolfisub/riskman-dashboard | 64800573e8c52162c101a5c4da7315bbd8036c9c | [
"BSD-3-Clause"
] | null | null | null | (function() {
'use strict';
angular
.module('app.bootstrapui')
.controller('ButtonsCtrl', ButtonsCtrl);
function ButtonsCtrl() {
var vm = this;
activate();
////////////////
function activate() {
vm.singleModel = 1;
vm.radioModel = 'Middle';
vm.checkModel = {
left: false,
middle: true,
right: false
};
}
}
})();
| 18.357143 | 49 | 0.391051 |
3d91da255d1f568f3218ebcc142b6cc33f31709b | 14,782 | js | JavaScript | src/other/arcgisonline/js/jsapi/esri/dijit/metadata/nls/it/i18nIso.js | da07ng/dipper | 03834b7ffa1612055cb535f4cd4a8f9cf347124e | [
"MIT"
] | 1 | 2019-11-05T16:47:26.000Z | 2019-11-05T16:47:26.000Z | src/other/arcgisonline/js/jsapi/esri/dijit/metadata/nls/it/i18nIso.js | da07ng/dipper | 03834b7ffa1612055cb535f4cd4a8f9cf347124e | [
"MIT"
] | null | null | null | src/other/arcgisonline/js/jsapi/esri/dijit/metadata/nls/it/i18nIso.js | da07ng/dipper | 03834b7ffa1612055cb535f4cd4a8f9cf347124e | [
"MIT"
] | null | null | null | // All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.15/esri/copyright.txt for details.
//>>built
define("esri/dijit/metadata/nls/it/i18nIso",{documentTypes:{data:{caption:"ISO 19115 (Dati)",description:""},service:{caption:"ISO 19119 (Servizio)",description:""},gmi:{caption:"ISO 19115-2 (Immagini e dati nella griglia)",description:""}},general:{reference:"Riferimento"},sections:{metadata:"Metadati",identification:"Identificazione",distribution:"Distribuzione",quality:"Qualit\u00e0",acquisition:"Acquisizione"},metadataSection:{identifier:"Identificatore",contact:"Contatto",date:"Data",standard:"Standard",
reference:"Riferimento"},identificationSection:{citation:"Citazione",description:"Descrizione",contact:"Contatto",thumbnail:"Miniatura",keywords:"Parole chiave",constraints:"Vincoli",resource:"Risorsa",resourceTab:{representation:"Rappresentazione",language:"Lingua",classification:"Classificazione",extent:"Estensione"},serviceResourceTab:{serviceType:"Tipo di servizio",extent:"Estensione",couplingType:"Tipo di accoppiamento",operation:"Operazione",operatesOn:"Funziona il"}},distributionSection:{},
qualitySection:{scope:"Ambito",conformance:"Conformit\u00e0",lineage:"Lineage"},acquisitionSection:{requirement:"Requisito",objective:"Obiettivo",instrument:"Strumento",plan:"Piano",operation:"Operazione",platform:"Piattaforma",environment:"Ambiente"},AbstractMD_Identification:{sAbstract:"Riassunto",purpose:"Scopo",credit:"Crediti",pointOfContact:"Punto di contatto",resourceMaintenance:"Manutenzione",graphicOverview:"Panoramica degli elementi grafici",descriptiveKeywords:"Raccolta parole chiave",
resourceConstraints:"Vincoli"},CI_Address:{deliveryPoint:"Punto di consegna",city:"Citt\u00e0",administrativeArea:"Area amministrativa",postalCode:"Codice postale",country:"Paese",electronicMailAddress:"Indirizzo e-mail"},CI_Citation:{title:"Titolo",alternateTitle:"Titolo alternativo",identifier:"Unique Resource Identifier",resource:{title:"Titolo della risorsa",date:"Data della risorsa"},specification:{title:"Titolo della specifica",date:"Data della specifica"}},CI_Contact:{phone:"Telefono",address:"Indirizzo",
onlineResource:"Risorsa online",hoursOfService:"Orari di servizio",contactInstructions:"Istruzioni di contatto"},CI_Date:{date:"Data",dateType:"Tipo di data"},CI_DateTypeCode:{caption:"Tipo di data",creation:"Data di creazione",publication:"Data di Pubblicazione",revision:"Data di revisione"},CI_OnLineFunctionCode:{caption:"Funzione",download:"Scarica",information:"Informazioni",offlineAccess:"Accesso offline",order:"Ordina",search:"Ricerca"},CI_OnlineResource:{caption:"Risorsa online",linkage:"URL",
protocol:"Protocollo",applicationProfile:"Profilo d'applicazione",name:"Nome",description:"Descrizione",sFunction:"Funzione"},CI_ResponsibleParty:{caption:"Punto di contatto",individualName:"Nome individuale",organisationName:"Nome organizzazione",positionName:"Nome posizione",contactInfo:"Informazioni di contatto",role:"Ruolo"},CI_RoleCode:{caption:"Ruolo",resourceProvider:"Fornitore di risorse",custodian:"Custode",owner:"Proprietario",user:"Utente",distributor:"Distributore",originator:"Creatore",
pointOfContact:"Punto di contatto",principalInvestigator:"Investigatore principale",processor:"Processore",publisher:"Editore",author:"Autore"},CI_Telephone:{voice:"Voce",facsimile:"Fax"},DCPList:{caption:"DCP",XML:"XML",CORBA:"CORBA",JAVA:"JAVA",COM:"COM",SQL:"SQL",WebServices:"Servizi Web"},DQ_ConformanceResult:{caption:"Risultati conformit\u00e0",explanation:"Spiegazione",degree:{caption:"Gradi",validationPerformed:"Convalida eseguita",conformant:"Conforme",nonConformant:"Non conforme"}},DQ_DataQuality:{report:"Report"},
DQ_Scope:{level:"Ambito (a cui si applicano informazioni sulla qualit\u00e0)",levelDescription:"Descrizione livello"},EX_Extent:{caption:"Estensione",description:"Descrizione",geographicElement:"Estensione spaziale",temporalElement:"Estensione temporale",verticalElement:"Estensione verticale"},EX_GeographicBoundingBox:{westBoundLongitude:"Longitudine confine occidentale",eastBoundLongitude:"Longitudine confine orientale",southBoundLatitude:"Latitudine confine meridionale",northBoundLatitude:"Latitudine confine settentrionale"},
EX_GeographicDescription:{caption:"Descrizione geografica"},EX_TemporalExtent:{TimePeriod:{beginPosition:"Data di inizio",endPosition:"Data di fine"}},EX_VerticalExtent:{minimumValue:"Valore Minimo",maximumValue:"Valore Massimo",verticalCRS:"CRS verticale"},Length:{caption:"Lunghezza",uom:"Unit\u00e0 di misura",km:"Chilometri",m:"Metri",mi:"Miglia",ft:"Piede"},LI_Lineage:{statement:"Dichiarazione lineage"},MD_BrowseGraphic:{fileName:"URL del grafico di esplorazione",fileDescription:"Didascalia del grafico di esplorazione",
fileType:"Tipo di grafico di esplorazione"},MD_ClassificationCode:{unclassified:"Senza classificazione",restricted:"Limitato",confidential:"Riservato",secret:"Segreto",topSecret:"Top Secret"},MD_Constraints:{caption:"Vincoli d'uso",useLimitation:"Limitazione d'uso"},MD_DataIdentification:{spatialRepresentationType:"Tipo di rappresentazione spaziale",spatialResolution:"Risoluzione spaziale",language:"Lingua risorsa",supplementalInformation:"Supplementare"},MD_DigitalTransferOptions:{onLine:"Online"},
MD_Distribution:{distributionFormat:"Formato di distribuzione",transferOptions:"Opzioni di trasferimento"},MD_Format:{name:"Nome Formato",version:"Versione formato"},MD_Identifier:{caption:"URI",identifierCaption:"Identificatore",code:"Codice"},MD_Keywords:{delimitedCaption:"Parole chiave",thesaurusName:"Thesaurus associato"},MD_KeywordTypeCode:{caption:"Tipo di parola chiave",discipline:"Disciplina",place:"Posiziona",stratum:"Strato",temporal:"Temporale",theme:"Tema"},MD_LegalConstraints:{caption:"Vincoli legali",
accessConstraints:"Vincoli di accesso",useConstraints:"Vincoli d'uso",otherConstraints:"Altri vincoli"},MD_MaintenanceFrequencyCode:{caption:"Frequenza",continual:"Continuo",daily:"Ogni giorno",weekly:"Ogni settimana",fortnightly:"Quindicinale",monthly:"Ogni mese",quarterly:"Trimestrale",biannually:"Biennale",annually:"Annuale",asNeeded:"In base alle necessit\u00e0",irregular:"Irregolare",notPlanned:"Non pianificato",unknown:"Sconosciuto"},MD_Metadata:{caption:"Metadati",fileIdentifier:"Identificatore file",
language:"Lingua dei metadata",hierarchyLevel:"Livello gerarchia",hierarchyLevelName:"Nome livello della gerarchia",contact:"Contatto metadati",dateStamp:"Data del Matadati",metadataStandardName:"Nome standard dei metadati",metadataStandardVersion:"Versione standard dei metadata",referenceSystemInfo:"Sistema di Riferimento",identificationInfo:"Identificazione",distributionInfo:"Distribuzione",dataQualityInfo:"Qualit\u00e0"},MD_ProgressCode:{caption:"Codice di avanzamento",completed:"Completato",historicalArchive:"Archivio storico",
obsolete:"Obsoleto",onGoing:"In corso",planned:"Pianificato",required:"Richiesto",underDevelopment:"In fase di sviluppo"},MD_RepresentativeFraction:{denominator:"Denominatore"},MD_Resolution:{equivalentScale:"Scala equivalente",distance:"Distanza"},MD_RestrictionCode:{copyright:"Copyright",patent:"Brevetto",patentPending:"Brevetto in corso di registrazione",trademark:"Marchio",license:"Licenza",intellectualPropertyRights:"Diritti di propriet\u00e0 intellettuale",restricted:"Limitato",otherRestrictions:"Altre restrizioni"},
MD_ScopeCode:{attribute:"Attributo",attributeType:"Tipo di attributo",collectionHardware:"Hardware di raccolta",collectionSession:"Sessione di raccolta",dataset:"Dataset",series:"Serie",nonGeographicDataset:"Dataset non geografici",dimensionGroup:"Gruppo di dimensioni",feature:"Funzionalit\u00e0",featureType:"Tipo di feature",propertyType:"Tipo Propriet\u00e0",fieldSession:"Sessione di campo",software:"Software",service:"Servizio",model:"Modello",tile:"Affianca"},MD_ScopeDescription:{attributes:"Attributi",
features:"Feature",featureInstances:"Istanze feature",attributeInstances:"Istanze attributo",dataset:"Dataset",other:"Altro"},MD_SecurityConstraints:{caption:"Vincoli di sicurezza",classification:"Classificazione",userNote:"Nota utente",classificationSystem:"Sistema di classificazione",handlingDescription:"Descrizione gestione"},MD_SpatialRepresentationTypeCode:{caption:"Tipo di rappresentazione spaziale",vector:"Vettoriali",grid:"Griglia",textTable:"Tabella di testo",tin:"TIN",stereoModel:"Modello stereo",
video:"Video"},MD_TopicCategoryCode:{caption:"Categoria argomento",boundaries:"Limiti amministrativi e politici",farming:"Agricoltura ed allevamento",climatologyMeteorologyAtmosphere:"Atmosfera e clima",biota:"Biologia ed ecologia",economy:"Affari ed economia",planningCadastre:"Catastale",society:"Cultura, societ\u00e0 e demografia",elevation:"Elevazione e prodotti derivati",environment:"Ambiente e conservazione",structure:"Servizi e strutture",geoscientificInformation:"Geologico e geofisico",health:"Salute e malattie",
imageryBaseMapsEarthCover:"Immagini e mappe base",inlandWaters:"Risorse idriche",location:"Reti geodetiche e posizioni",intelligenceMilitary:"Military",oceans:"Oceani ed estuari",transportation:"Reti di trasporto",utilitiesCommunication:"Servizi pubblici e comunicazioni"},MI_ContextCode:{caption:"Contesto",acquisition:"Acquisizione",pass:"Superato",wayPoint:"Punto di riferimento"},MI_EnvironmentalRecord:{caption:"Condizioni ambientali",averageAirTemperature:"Temperatura media dell'aria",maxRelativeHumidity:"Umidit\u00e0 relativa massima",
maxAltitude:"Altitudine massima",meterologicalConditions:"Condizioni meteorologiche"},MI_Event:{identifier:"Identificatore di evento",time:"Ora",expectedObjectiveReference:"Obiettivo previsto (Identificatore obiettivo)",relatedSensorReference:"Sensore collegato (Identificatore strumento)",relatedPassReference:"Ammissione collegata (Identificatore ammissione alla piattaforma)"},MI_GeometryTypeCode:{point:"Punto",linear:"Lineare",areal:"Areale",strip:"Striscia"},MI_Instrument:{citation:"Citazione strumento",
identifier:"Identificatore strumento",sType:"Tipo di strumento",description:"Descrizione strumento",mountedOn:"Montato su",mountedOnPlatformReference:"Montato su (Identificatore piattaforma)"},MI_Metadata:{acquisitionInformation:"Acquisizione"},MI_Objective:{caption:"Obiettivo",identifier:"Identificatore obiettivo",priority:"Priorit\u00e0 di obiettivo",sFunction:"Funzione di obiettivo",extent:"Estensione",pass:"Ammissione di piattaforma",sensingInstrumentReference:"Strumento di rilevazione (Identificatore strumento)",
objectiveOccurrence:"Eventi",sections:{identification:"Identificazione",extent:"Estensione",pass:"Superato",sensingInstrument:"Strumento di rilevazione",objectiveOccurrence:"Eventi"}},MI_ObjectiveTypeCode:{caption:"Tipo (Tecnica di raccolta per obiettivo)",instantaneousCollection:"Raccolta istantanea",persistentView:"Vista persistente",survey:"Indagini"},MI_Operation:{caption:"Operazione",description:"Descrizione Operazione",citation:"Citazione operazione",identifier:"Identificatore operazione",status:"Stato operazione",
objectiveReference:"Obiettivo collegato (Identificatore obiettivo)",planReference:"Piano collegato (Identificatore piano)",significantEventReference:"Evento collegato (Identificatore evento)",platformReference:"Piattaforma collegata (Identificatore piattaforma)",sections:{identification:"Identificazione",related:"Collegato"}},MI_OperationTypeCode:{caption:"Tipo di Operazione",real:"Reale",simulated:"Simulato",synthesized:"Sintetizzato"},MI_Plan:{sType:"Geometria campione per raccolta di dati",status:"Stato del piano",
citation:"Citazione di autorit\u00e0 che richiede la raccolta",satisfiedRequirementReference:"Requisito soddisfatto (Identificatore requisito)",operationReference:"Operazione collegata (Identificatore operazione)"},MI_Platform:{citation:"Citazione piattaforma",identifier:"Identificatore piattaforma",description:"Descrizione di piattaforma che supporta lo strumento",sponsor:"Organizzazione sponsor per piattaforma",instrument:"Strumenti montati sulla piattaforma",instrumentReference:"Identificatore strumento",
sections:{identification:"Identificazione",sponsor:"Sponsor",instruments:"Strumenti"}},MI_PlatformPass:{identifier:"Identificatore ammissione piattaforma",extent:"Estensione ammissione piattaforma",relatedEventReference:"Evento collegato (Identificatore evento)"},MI_PriorityCode:{critical:"Critica",highImportance:"Importanza elevata",mediumImportance:"Importanza media",lowImportance:"Importanza scarsa"},MI_RequestedDate:{requestedDateOfCollection:"Data richiesta della raccolta",latestAcceptableDate:"Ultima data accettabile"},
MI_Requirement:{caption:"Requisito",citation:"Citazione per documento di guida ai requisiti",identifier:"Identificatore requisito",requestor:"Richiedente del requisito",recipient:"Destinatario dei risultati del requisito",priority:"Priorit\u00e0 del requisito",requestedDate:"Data richiesta",expiryDate:"Data di scadenza",satisifiedPlanReference:"Piano soddisfatto (Identificatore piano)",sections:{identification:"Identificazione",requestor:"Richiedente",recipient:"Destinatario",priorityAndDates:"Propriet\u00e0 e date",
satisifiedPlan:"Piano soddisfatto"}},MI_SequenceCode:{caption:"Sequenza",start:"Inizia",end:"Fine",instantaneous:"Istantaneo"},MI_TriggerCode:{caption:"Trigger",automatic:"Automatico",manual:"Manuale",preProgrammed:"Preprogrammato"},ObjectReference:{uuidref:"Riferimento UUID",xlinkref:"Riferimento URL"},RS_Identifier:{caption:"Spazio ID e codice",code:"Codice",codeSpace:"Spazio di codici"},SV_CouplingType:{loose:"Libero",mixed:"Misto",tight:"Stretto"},SV_OperationMetadata:{operationName:"Nome operazione",
DCP:"DCP",connectPoint:"Punto di connessione"},SV_ServiceIdentification:{serviceType:"Tipo di servizio",couplingType:"Tipo di accoppiamento",containsOperations:"Metadati operativi",operatesOn:"Funziona il"},TM_Primitive:{indeterminatePosition:"Posizione indeterminata",indeterminates:{before:"Prima",after:"Dopo",now:"Adesso",unknown:"Sconosciuto"}},gemet:{concept:{gemetConceptKeyword:"Parola chiave concetto GEMET",tool:"Ricerca...",dialogTitle:"GEMET - Parola chiave concetto",searchLabel:"Trova:",
searchTip:"Cerca in GEMET"},theme:{tool:"Ricerca...",dialogTitle:"GEMET - Temi di dati di Inspire"},ioerror:"Si \u00e8 verificato un errore di comunicazione con il servizio GEMET: {url}",searching:"Ricerca in GEMET in corso...",noMatch:"Nessun risultato corrispondente trovato.",languages:{bg:"Bulgaro",cs:"Ceco",da:"Danese",nl:"Olandese",en:"Inglese",et:"Estone",fi:"Finlandese",fr:"Francese",de:"Tedesco",el:"Greco",hu:"Ungherese",ga:"Gaelico (irlandese)",it:"Italiano",lv:"Lettone",lt:"Lituano",mt:"Maltese",
pl:"Polacco",pt:"Portoghese",ro:"Rumeno",sk:"Slovacco",sl:"Sloveno",es:"Spagnolo",sv:"Svedese"}}}); | 461.9375 | 544 | 0.82269 |
3d91e9abbcfce0a419cde24698584578550590a0 | 27,854 | js | JavaScript | ui/src/app/widget/lib/alarms-table-widget.js | sejpalhemangi/thingsboard- | 0f0d521d740f70401f04130c28f55bef85aff2b9 | [
"ECL-2.0",
"Apache-2.0"
] | 7 | 2018-12-31T13:00:17.000Z | 2022-03-30T06:33:24.000Z | ui/src/app/widget/lib/alarms-table-widget.js | sejpalhemangi/thingsboard- | 0f0d521d740f70401f04130c28f55bef85aff2b9 | [
"ECL-2.0",
"Apache-2.0"
] | 38 | 2020-02-19T05:15:37.000Z | 2021-07-19T04:36:24.000Z | ui/src/app/widget/lib/alarms-table-widget.js | sejpalhemangi/thingsboard- | 0f0d521d740f70401f04130c28f55bef85aff2b9 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2019-05-11T00:40:34.000Z | 2019-05-15T15:47:35.000Z | /*
* Copyright © 2016-2018 The Thingsboard 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.
*/
import './alarms-table-widget.scss';
import './display-columns-panel.scss';
import './alarm-status-filter-panel.scss';
/* eslint-disable import/no-unresolved, import/default */
import alarmsTableWidgetTemplate from './alarms-table-widget.tpl.html';
import alarmDetailsDialogTemplate from '../../alarm/alarm-details-dialog.tpl.html';
import displayColumnsPanelTemplate from './display-columns-panel.tpl.html';
import alarmStatusFilterPanelTemplate from './alarm-status-filter-panel.tpl.html';
/* eslint-enable import/no-unresolved, import/default */
import tinycolor from 'tinycolor2';
import cssjs from '../../../vendor/css.js/css';
export default angular.module('thingsboard.widgets.alarmsTableWidget', [])
.directive('tbAlarmsTableWidget', AlarmsTableWidget)
.name;
/*@ngInject*/
function AlarmsTableWidget() {
return {
restrict: "E",
scope: true,
bindToController: {
tableId: '=',
ctx: '='
},
controller: AlarmsTableWidgetController,
controllerAs: 'vm',
templateUrl: alarmsTableWidgetTemplate
};
}
/*@ngInject*/
function AlarmsTableWidgetController($element, $scope, $filter, $mdMedia, $mdDialog, $mdPanel, $document, $translate, $q, $timeout, alarmService, utils, types) {
var vm = this;
vm.stylesInfo = {};
vm.contentsInfo = {};
vm.columnWidth = {};
vm.showData = true;
vm.hasData = false;
vm.alarms = [];
vm.alarmsCount = 0;
vm.selectedAlarms = []
vm.alarmSource = null;
vm.alarmSearchStatus = null;
vm.allAlarms = [];
vm.currentAlarm = null;
vm.enableSelection = true;
vm.displayDetails = true;
vm.allowAcknowledgment = true;
vm.allowClear = true;
vm.actionCellDescriptors = [];
vm.displayPagination = true;
vm.defaultPageSize = 10;
vm.defaultSortOrder = '-'+types.alarmFields.createdTime.value;
vm.query = {
order: vm.defaultSortOrder,
limit: vm.defaultPageSize,
page: 1,
search: null
};
vm.searchAction = {
name: 'action.search',
show: true,
onAction: function() {
vm.enterFilterMode();
},
icon: 'search'
};
vm.enterFilterMode = enterFilterMode;
vm.exitFilterMode = exitFilterMode;
vm.onReorder = onReorder;
vm.onPaginate = onPaginate;
vm.onRowClick = onRowClick;
vm.onActionButtonClick = onActionButtonClick;
vm.actionEnabled = actionEnabled;
vm.isCurrent = isCurrent;
vm.openAlarmDetails = openAlarmDetails;
vm.ackAlarms = ackAlarms;
vm.ackAlarm = ackAlarm;
vm.clearAlarms = clearAlarms;
vm.clearAlarm = clearAlarm;
vm.cellStyle = cellStyle;
vm.cellContent = cellContent;
vm.editAlarmStatusFilter = editAlarmStatusFilter;
vm.editColumnsToDisplay = editColumnsToDisplay;
$scope.$watch('vm.ctx', function() {
if (vm.ctx) {
vm.settings = vm.ctx.settings;
vm.widgetConfig = vm.ctx.widgetConfig;
vm.subscription = vm.ctx.defaultSubscription;
vm.alarmSource = vm.subscription.alarmSource;
initializeConfig();
updateAlarmSource();
}
});
$scope.$watch("vm.query.search", function(newVal, prevVal) {
if (!angular.equals(newVal, prevVal) && vm.query.search != null) {
updateAlarms();
}
});
$scope.$on('alarms-table-data-updated', function(event, tableId) {
if (vm.tableId == tableId) {
if (vm.subscription) {
vm.allAlarms = vm.subscription.alarms || [];
updateAlarms(true);
$scope.$digest();
}
}
});
$scope.$watch(function() { return $mdMedia('gt-xs'); }, function(isGtXs) {
vm.isGtXs = isGtXs;
});
$scope.$watch(function() { return $mdMedia('gt-md'); }, function(isGtMd) {
vm.isGtMd = isGtMd;
if (vm.isGtMd) {
vm.limitOptions = [vm.defaultPageSize, vm.defaultPageSize*2, vm.defaultPageSize*3];
} else {
vm.limitOptions = null;
}
});
$scope.$watch('vm.selectedAlarms.length', function (newLength) {
var selectionMode = newLength ? true : false;
if (vm.ctx) {
if (selectionMode) {
vm.ctx.hideTitlePanel = true;
} else if (vm.query.search == null) {
vm.ctx.hideTitlePanel = false;
}
}
});
function initializeConfig() {
vm.ctx.widgetActions = [ vm.searchAction ];
vm.displayDetails = angular.isDefined(vm.settings.displayDetails) ? vm.settings.displayDetails : true;
vm.allowAcknowledgment = angular.isDefined(vm.settings.allowAcknowledgment) ? vm.settings.allowAcknowledgment : true;
vm.allowClear = angular.isDefined(vm.settings.allowClear) ? vm.settings.allowClear : true;
if (vm.displayDetails) {
vm.actionCellDescriptors.push(
{
displayName: $translate.instant('alarm.details'),
icon: 'more_horiz',
details: true
}
);
}
if (vm.allowAcknowledgment) {
vm.actionCellDescriptors.push(
{
displayName: $translate.instant('alarm.acknowledge'),
icon: 'done',
acknowledge: true
}
);
}
if (vm.allowClear) {
vm.actionCellDescriptors.push(
{
displayName: $translate.instant('alarm.clear'),
icon: 'clear',
clear: true
}
);
}
vm.actionCellDescriptors = vm.actionCellDescriptors.concat(vm.ctx.actionsApi.getActionDescriptors('actionCellButton'));
if (vm.settings.alarmsTitle && vm.settings.alarmsTitle.length) {
vm.alarmsTitle = utils.customTranslation(vm.settings.alarmsTitle, vm.settings.alarmsTitle);
} else {
vm.alarmsTitle = $translate.instant('alarm.alarms');
}
vm.ctx.widgetTitle = vm.alarmsTitle;
vm.enableSelection = angular.isDefined(vm.settings.enableSelection) ? vm.settings.enableSelection : true;
vm.searchAction.show = angular.isDefined(vm.settings.enableSearch) ? vm.settings.enableSearch : true;
if (!vm.allowAcknowledgment && !vm.allowClear) {
vm.enableSelection = false;
}
vm.displayPagination = angular.isDefined(vm.settings.displayPagination) ? vm.settings.displayPagination : true;
var pageSize = vm.settings.defaultPageSize;
if (angular.isDefined(pageSize) && angular.isNumber(pageSize) && pageSize > 0) {
vm.defaultPageSize = pageSize;
}
if (vm.settings.defaultSortOrder && vm.settings.defaultSortOrder.length) {
vm.defaultSortOrder = vm.settings.defaultSortOrder;
}
vm.query.order = vm.defaultSortOrder;
vm.query.limit = vm.defaultPageSize;
if (vm.isGtMd) {
vm.limitOptions = [vm.defaultPageSize, vm.defaultPageSize*2, vm.defaultPageSize*3];
} else {
vm.limitOptions = null;
}
var origColor = vm.widgetConfig.color || 'rgba(0, 0, 0, 0.87)';
var defaultColor = tinycolor(origColor);
var mdDark = defaultColor.setAlpha(0.87).toRgbString();
var mdDarkSecondary = defaultColor.setAlpha(0.54).toRgbString();
var mdDarkDisabled = defaultColor.setAlpha(0.26).toRgbString();
//var mdDarkIcon = mdDarkSecondary;
var mdDarkDivider = defaultColor.setAlpha(0.12).toRgbString();
var cssString = 'table.md-table th.md-column {\n'+
'color: ' + mdDarkSecondary + ';\n'+
'}\n'+
'table.md-table th.md-column.md-checkbox-column md-checkbox:not(.md-checked) .md-icon {\n'+
'border-color: ' + mdDarkSecondary + ';\n'+
'}\n'+
'table.md-table th.md-column md-icon.md-sort-icon {\n'+
'color: ' + mdDarkDisabled + ';\n'+
'}\n'+
'table.md-table th.md-column.md-active, table.md-table th.md-column.md-active md-icon {\n'+
'color: ' + mdDark + ';\n'+
'}\n'+
'table.md-table td.md-cell {\n'+
'color: ' + mdDark + ';\n'+
'border-top: 1px '+mdDarkDivider+' solid;\n'+
'}\n'+
'table.md-table td.md-cell.md-checkbox-cell md-checkbox:not(.md-checked) .md-icon {\n'+
'border-color: ' + mdDarkSecondary + ';\n'+
'}\n'+
'table.md-table td.md-cell.tb-action-cell button.md-icon-button md-icon {\n'+
'color: ' + mdDarkSecondary + ';\n'+
'}\n'+
'table.md-table td.md-cell.md-placeholder {\n'+
'color: ' + mdDarkDisabled + ';\n'+
'}\n'+
'table.md-table td.md-cell md-select > .md-select-value > span.md-select-icon {\n'+
'color: ' + mdDarkSecondary + ';\n'+
'}\n'+
'.md-table-pagination {\n'+
'color: ' + mdDarkSecondary + ';\n'+
'border-top: 1px '+mdDarkDivider+' solid;\n'+
'}\n'+
'.md-table-pagination .buttons md-icon {\n'+
'color: ' + mdDarkSecondary + ';\n'+
'}\n'+
'.md-table-pagination md-select:not([disabled]):focus .md-select-value {\n'+
'color: ' + mdDarkSecondary + ';\n'+
'}';
var cssParser = new cssjs();
cssParser.testMode = false;
var namespace = 'ts-table-' + hashCode(cssString);
cssParser.cssPreviewNamespace = namespace;
cssParser.createStyleElement(namespace, cssString);
$element.addClass(namespace);
function hashCode(str) {
var hash = 0;
var i, char;
if (str.length === 0) return hash;
for (i = 0; i < str.length; i++) {
char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return hash;
}
}
function enterFilterMode () {
vm.query.search = '';
vm.ctx.hideTitlePanel = true;
$timeout(()=>{
angular.element(vm.ctx.$container).find('.searchInput').focus();
})
}
function exitFilterMode () {
vm.query.search = null;
updateAlarms();
vm.ctx.hideTitlePanel = false;
}
function onReorder () {
updateAlarms();
}
function onPaginate () {
updateAlarms();
}
function onRowClick($event, alarm) {
if ($event) {
$event.stopPropagation();
}
if (vm.currentAlarm != alarm) {
vm.currentAlarm = alarm;
}
var descriptors = vm.ctx.actionsApi.getActionDescriptors('rowClick');
if (descriptors.length) {
var entityId;
var entityName;
if (vm.currentAlarm && vm.currentAlarm.originator) {
entityId = vm.currentAlarm.originator;
entityName = vm.currentAlarm.originatorName;
}
vm.ctx.actionsApi.handleWidgetAction($event, descriptors[0], entityId, entityName, { alarm: alarm });
}
}
function onActionButtonClick($event, alarm, actionDescriptor) {
if (actionDescriptor.details) {
vm.openAlarmDetails($event, alarm);
} else if (actionDescriptor.acknowledge) {
vm.ackAlarm($event, alarm);
} else if (actionDescriptor.clear) {
vm.clearAlarm($event, alarm);
} else {
if ($event) {
$event.stopPropagation();
}
var entityId;
var entityName;
if (alarm && alarm.originator) {
entityId = alarm.originator;
entityName = alarm.originatorName;
}
vm.ctx.actionsApi.handleWidgetAction($event, actionDescriptor, entityId, entityName, {alarm: alarm});
}
}
function actionEnabled(alarm, actionDescriptor) {
if (actionDescriptor.acknowledge) {
return (alarm.status == types.alarmStatus.activeUnack ||
alarm.status == types.alarmStatus.clearedUnack);
} else if (actionDescriptor.clear) {
return (alarm.status == types.alarmStatus.activeAck ||
alarm.status == types.alarmStatus.activeUnack);
}
return true;
}
function isCurrent(alarm) {
return (vm.currentAlarm && alarm && vm.currentAlarm.id && alarm.id) &&
(vm.currentAlarm.id.id === alarm.id.id);
}
function openAlarmDetails($event, alarm) {
if (alarm && alarm.id) {
var onShowingCallback = {
onShowing: function(){}
}
$mdDialog.show({
controller: 'AlarmDetailsDialogController',
controllerAs: 'vm',
templateUrl: alarmDetailsDialogTemplate,
locals: {
alarmId: alarm.id.id,
allowAcknowledgment: vm.allowAcknowledgment,
allowClear: vm.allowClear,
displayDetails: true,
showingCallback: onShowingCallback
},
parent: angular.element($document[0].body),
targetEvent: $event,
fullscreen: true,
multiple: true,
onShowing: function(scope, element) {
onShowingCallback.onShowing(scope, element);
}
}).then(function (alarm) {
if (alarm) {
vm.subscription.update();
}
});
}
}
function ackAlarms($event) {
if ($event) {
$event.stopPropagation();
}
if (vm.selectedAlarms && vm.selectedAlarms.length > 0) {
var title = $translate.instant('alarm.aknowledge-alarms-title', {count: vm.selectedAlarms.length}, 'messageformat');
var content = $translate.instant('alarm.aknowledge-alarms-text', {count: vm.selectedAlarms.length}, 'messageformat');
var confirm = $mdDialog.confirm()
.targetEvent($event)
.title(title)
.htmlContent(content)
.ariaLabel(title)
.cancel($translate.instant('action.no'))
.ok($translate.instant('action.yes'));
$mdDialog.show(confirm).then(function () {
var tasks = [];
for (var i=0;i<vm.selectedAlarms.length;i++) {
var alarm = vm.selectedAlarms[i];
if (alarm.id) {
tasks.push(alarmService.ackAlarm(alarm.id.id));
}
}
if (tasks.length) {
$q.all(tasks).then(function () {
vm.selectedAlarms = [];
vm.subscription.update();
});
}
});
}
}
function ackAlarm($event, alarm) {
if ($event) {
$event.stopPropagation();
}
var confirm = $mdDialog.confirm()
.targetEvent($event)
.title($translate.instant('alarm.aknowledge-alarm-title'))
.htmlContent($translate.instant('alarm.aknowledge-alarm-text'))
.ariaLabel($translate.instant('alarm.acknowledge'))
.cancel($translate.instant('action.no'))
.ok($translate.instant('action.yes'));
$mdDialog.show(confirm).then(function () {
alarmService.ackAlarm(alarm.id.id).then(function () {
vm.selectedAlarms = [];
vm.subscription.update();
});
});
}
function clearAlarms($event) {
if ($event) {
$event.stopPropagation();
}
if (vm.selectedAlarms && vm.selectedAlarms.length > 0) {
var title = $translate.instant('alarm.clear-alarms-title', {count: vm.selectedAlarms.length}, 'messageformat');
var content = $translate.instant('alarm.clear-alarms-text', {count: vm.selectedAlarms.length}, 'messageformat');
var confirm = $mdDialog.confirm()
.targetEvent($event)
.title(title)
.htmlContent(content)
.ariaLabel(title)
.cancel($translate.instant('action.no'))
.ok($translate.instant('action.yes'));
$mdDialog.show(confirm).then(function () {
var tasks = [];
for (var i=0;i<vm.selectedAlarms.length;i++) {
var alarm = vm.selectedAlarms[i];
if (alarm.id) {
tasks.push(alarmService.clearAlarm(alarm.id.id));
}
}
if (tasks.length) {
$q.all(tasks).then(function () {
vm.selectedAlarms = [];
vm.subscription.update();
});
}
});
}
}
function clearAlarm($event, alarm) {
if ($event) {
$event.stopPropagation();
}
var confirm = $mdDialog.confirm()
.targetEvent($event)
.title($translate.instant('alarm.clear-alarm-title'))
.htmlContent($translate.instant('alarm.clear-alarm-text'))
.ariaLabel($translate.instant('alarm.clear'))
.cancel($translate.instant('action.no'))
.ok($translate.instant('action.yes'));
$mdDialog.show(confirm).then(function () {
alarmService.clearAlarm(alarm.id.id).then(function () {
vm.selectedAlarms = [];
vm.subscription.update();
});
});
}
function updateAlarms(preserveSelections) {
if (!preserveSelections) {
vm.selectedAlarms = [];
}
var result = $filter('orderBy')(vm.allAlarms, vm.query.order);
if (vm.query.search != null) {
result = $filter('filter')(result, {$: vm.query.search});
}
vm.alarmsCount = result.length;
if (vm.displayPagination) {
var startIndex = vm.query.limit * (vm.query.page - 1);
vm.alarms = result.slice(startIndex, startIndex + vm.query.limit);
} else {
vm.alarms = result;
}
if (preserveSelections) {
var newSelectedAlarms = [];
if (vm.selectedAlarms && vm.selectedAlarms.length) {
var i = vm.selectedAlarms.length;
while (i--) {
var selectedAlarm = vm.selectedAlarms[i];
if (selectedAlarm.id) {
result = $filter('filter')(vm.alarms, {id: {id: selectedAlarm.id.id} });
if (result && result.length) {
newSelectedAlarms.push(result[0]);
}
}
}
}
vm.selectedAlarms = newSelectedAlarms;
}
}
function cellStyle(alarm, key) {
var style = {};
if (alarm && key) {
var styleInfo = vm.stylesInfo[key.label];
var value = getAlarmValue(alarm, key);
if (styleInfo.useCellStyleFunction && styleInfo.cellStyleFunction) {
try {
style = styleInfo.cellStyleFunction(value);
} catch (e) {
style = {};
}
} else {
style = defaultStyle(key, value);
}
}
if (!style.width) {
var columnWidth = vm.columnWidth[key.label];
style.width = columnWidth;
}
return style;
}
function cellContent(alarm, key) {
var strContent = '';
if (alarm && key) {
var contentInfo = vm.contentsInfo[key.label];
var value = getAlarmValue(alarm, key);
if (contentInfo.useCellContentFunction && contentInfo.cellContentFunction) {
if (angular.isDefined(value)) {
strContent = '' + value;
}
var content = strContent;
try {
content = contentInfo.cellContentFunction(value, alarm, $filter);
} catch (e) {
content = strContent;
}
} else {
content = defaultContent(key, value);
}
return content;
} else {
return strContent;
}
}
function defaultContent(key, value) {
if (angular.isDefined(value)) {
var alarmField = types.alarmFields[key.name];
if (alarmField) {
if (alarmField.time) {
return $filter('date')(value, 'yyyy-MM-dd HH:mm:ss');
} else if (alarmField.value == types.alarmFields.severity.value) {
return $translate.instant(types.alarmSeverity[value].name);
} else if (alarmField.value == types.alarmFields.status.value) {
return $translate.instant('alarm.display-status.'+value);
} else if (alarmField.value == types.alarmFields.originatorType.value) {
return $translate.instant(types.entityTypeTranslations[value].type);
}
else {
return value;
}
} else {
return value;
}
} else {
return '';
}
}
function defaultStyle(key, value) {
if (angular.isDefined(value)) {
var alarmField = types.alarmFields[key.name];
if (alarmField) {
if (alarmField.value == types.alarmFields.severity.value) {
return {
fontWeight: 'bold',
color: types.alarmSeverity[value].color
};
} else {
return {};
}
} else {
return {};
}
} else {
return {};
}
}
const getDescendantProp = (obj, path) => (
path.split('.').reduce((acc, part) => acc && acc[part], obj)
);
function getAlarmValue(alarm, key) {
var alarmField = types.alarmFields[key.name];
if (alarmField) {
return getDescendantProp(alarm, alarmField.value);
} else {
return getDescendantProp(alarm, key.name);
}
}
function editAlarmStatusFilter($event) {
var element = angular.element($event.target);
var position = $mdPanel.newPanelPosition()
.relativeTo(element)
.addPanelPosition($mdPanel.xPosition.ALIGN_END, $mdPanel.yPosition.BELOW);
var config = {
attachTo: angular.element($document[0].body),
controller: AlarmStatusFilterPanelController,
controllerAs: 'vm',
templateUrl: alarmStatusFilterPanelTemplate,
panelClass: 'tb-alarm-status-filter-panel',
position: position,
fullscreen: false,
locals: {
'subscription': vm.subscription
},
openFrom: $event,
clickOutsideToClose: true,
escapeToClose: true,
focusOnOpen: false
};
$mdPanel.open(config);
}
function editColumnsToDisplay($event) {
var element = angular.element($event.target);
var position = $mdPanel.newPanelPosition()
.relativeTo(element)
.addPanelPosition($mdPanel.xPosition.ALIGN_END, $mdPanel.yPosition.BELOW);
var config = {
attachTo: angular.element($document[0].body),
controller: DisplayColumnsPanelController,
controllerAs: 'vm',
templateUrl: displayColumnsPanelTemplate,
panelClass: 'tb-display-columns-panel',
position: position,
fullscreen: false,
locals: {
'columns': vm.alarmSource.dataKeys
},
openFrom: $event,
clickOutsideToClose: true,
escapeToClose: true,
focusOnOpen: false
};
$mdPanel.open(config);
}
function updateAlarmSource() {
vm.ctx.widgetTitle = utils.createLabelFromDatasource(vm.alarmSource, vm.alarmsTitle);
vm.stylesInfo = {};
vm.contentsInfo = {};
vm.columnWidth = {};
for (var d = 0; d < vm.alarmSource.dataKeys.length; d++ ) {
var dataKey = vm.alarmSource.dataKeys[d];
dataKey.title = utils.customTranslation(dataKey.label, dataKey.label);
dataKey.display = true;
var keySettings = dataKey.settings;
var cellStyleFunction = null;
var useCellStyleFunction = false;
if (keySettings.useCellStyleFunction === true) {
if (angular.isDefined(keySettings.cellStyleFunction) && keySettings.cellStyleFunction.length > 0) {
try {
cellStyleFunction = new Function('value', keySettings.cellStyleFunction);
useCellStyleFunction = true;
} catch (e) {
cellStyleFunction = null;
useCellStyleFunction = false;
}
}
}
vm.stylesInfo[dataKey.label] = {
useCellStyleFunction: useCellStyleFunction,
cellStyleFunction: cellStyleFunction
};
var cellContentFunction = null;
var useCellContentFunction = false;
if (keySettings.useCellContentFunction === true) {
if (angular.isDefined(keySettings.cellContentFunction) && keySettings.cellContentFunction.length > 0) {
try {
cellContentFunction = new Function('value, alarm, filter', keySettings.cellContentFunction);
useCellContentFunction = true;
} catch (e) {
cellContentFunction = null;
useCellContentFunction = false;
}
}
}
vm.contentsInfo[dataKey.label] = {
useCellContentFunction: useCellContentFunction,
cellContentFunction: cellContentFunction
};
var columnWidth = angular.isDefined(keySettings.columnWidth) ? keySettings.columnWidth : '0px';
vm.columnWidth[dataKey.label] = columnWidth;
}
}
}
/*@ngInject*/
function DisplayColumnsPanelController(columns) { //eslint-disable-line
var vm = this;
vm.columns = columns;
}
/*@ngInject*/
function AlarmStatusFilterPanelController(subscription, types) { //eslint-disable-line
var vm = this;
vm.types = types;
vm.subscription = subscription;
}
| 35.528061 | 161 | 0.538917 |
3d92f4dd0c39e3145b471a1150d583763bb03faa | 15,562 | js | JavaScript | java/com/google/protobuf/contrib/immutablejs/runtime/descriptor/internal_descriptor.js | google/j2cl-proto | da35f76b28953775303622634d95a0ce82d71192 | [
"Apache-2.0"
] | 3 | 2020-01-11T09:31:46.000Z | 2020-01-29T14:06:24.000Z | java/com/google/protobuf/contrib/immutablejs/runtime/descriptor/internal_descriptor.js | google/j2cl-proto | da35f76b28953775303622634d95a0ce82d71192 | [
"Apache-2.0"
] | null | null | null | java/com/google/protobuf/contrib/immutablejs/runtime/descriptor/internal_descriptor.js | google/j2cl-proto | da35f76b28953775303622634d95a0ce82d71192 | [
"Apache-2.0"
] | null | null | null | // 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.
goog.module('proto.im.descriptor.internal_descriptor');
const {Descriptor, Field, FieldType} = goog.require('proto.im.descriptor');
const {MAX_FIELD_NUMBER, fieldSkipConstants, fieldTypeConstants} = goog.require('proto.im.descriptor.internal_constants');
const {cacheReturnValue} = goog.require('goog.functions');
const {fieldTypeConstants: encodedFieldTypeConstants} = goog.require('proto.im.descriptor.internal_encodedConstants');
/** @implements {Descriptor} */
class DescriptorImpl {
/**
* @param {string} fullEncodedDescriptor
* @param {!Array<function():!Descriptor>=} submessageDescriptorProviders
* @param {function():!Array<!ExtensionFieldInfo>=} extensionsProvider
* @param {string=} messageId
* @param {boolean=} isMessageSet
* @private
*/
constructor(
fullEncodedDescriptor, submessageDescriptorProviders = undefined,
extensionsProvider = undefined, messageId = undefined,
isMessageSet = false) {
/** @private @const {string} */
this.fullEncodedDescriptor_ = fullEncodedDescriptor;
/** @private @const {number} */
this.fieldDescriptorEnd_ = this.fullEncodedDescriptor_.indexOf(
encodedFieldTypeConstants.END_OF_FIELD_DESCRIPTOR);
/** @private @const {!Array<function():!Descriptor>|undefined} */
this.submessageDescriptorProviders_ = submessageDescriptorProviders;
/** @private @const {function():!Array<!ExtensionFieldInfo>|undefined} */
this.extensionsProvider_ = extensionsProvider;
/** @private @const {?string} */
this.messageId_ = messageId != null ? messageId : null;
/** @private @const {boolean} */
this.isMessageSet_ = isMessageSet;
}
/**
* @param {!Args} args
* @return {!DescriptorImpl}
*/
static fromArgs(args) {
checkState(
args.extensionRegistry == null || args.extensionsProvider == null,
'Descriptor cannot be constructed with both an extensionRegistry and ' +
'extensionsProvider');
if (args.extensionRegistry) {
const extensionRegistry = args.extensionRegistry;
args.extensionsProvider = () =>
unpackExtensionRegistry(extensionRegistry);
}
return new DescriptorImpl(
args.encodedDescriptor, args.submessageDescriptorProviders,
args.extensionsProvider, args.messageId, args.isMessageSet);
}
/**
* @param {string} encodedDescriptor
* @return {!DescriptorImpl}
*/
static fromEncodedString(encodedDescriptor) {
return new DescriptorImpl(encodedDescriptor);
}
/**
* @return {!Object<number, !Field>}
* @override
*/
fields() {
const fields = Object.create(null);
this.forEachField((field) => {
fields[field.fieldNumber] = field;
});
return fields;
}
/**
* @param {function(!Field):void} callback
* @override
*/
forEachField(callback) {
const fieldDescriptorReader = new Base92Reader(
this.fullEncodedDescriptor_, /* offset= */ 0,
/* limit= */ this.fieldDescriptorEnd_);
let lastFieldNumber = 0;
let submessageDescriptorIndex = 0;
const submessageDescriptorSupplier = () => {
if (this.submessageDescriptorProviders_) {
return this.submessageDescriptorProviders_[submessageDescriptorIndex++];
} else {
return undefined;
}
};
while (!isNaN(fieldDescriptorReader.peekValue())) {
lastFieldNumber =
getNextFieldNumber(fieldDescriptorReader, lastFieldNumber);
callback(parseField(
fieldDescriptorReader, lastFieldNumber, /* extension= */ false,
submessageDescriptorSupplier));
}
if (!this.extensionsProvider_) {
return;
}
const extensions = this.extensionsProvider_();
for (let i = 0; i < extensions.length; i++) {
const extension = extensions[i];
const hasSubmessage = extension.submessageDescriptorProvider != null;
const field = parseField(
Base92Reader.readEntireString(extension.encodedDescriptor),
extension.fieldNumber, /* extension= */ true,
hasSubmessage ? () => extension.submessageDescriptorProvider :
undefined);
callback(field);
}
}
/**
* @return {boolean}
* @override
*/
isExtendable() {
return this.extensionsProvider_ != null;
}
/**
* @return {?string}
* @override
*/
messageId() {
return this.messageId_;
}
/**
* @return {boolean}
* @override
*/
isMessageSet() {
return this.isMessageSet_;
}
}
/** @record */
class Args {
constructor() {
/** @const {string} */
this.encodedDescriptor;
/**
* An array of functions that provide `Descriptor`s for message/group
* fields. The array should be in field number ascending order with no
* holes. They will be consumed in the same order that the relevant field
* types are parsed.
*
* Can be undefined if the message has no message/group fields.
* @type {!Array<function():!Descriptor>|undefined}
*/
this.submessageDescriptorProviders;
/** @type {!ExtensionRegistry|undefined} */
this.extensionRegistry;
/** @type {function():!Array<!ExtensionFieldInfo>|undefined} */
this.extensionsProvider;
/**
* The value of` option (jspb.message_id)`, or undefined if not set.
* @type {string|undefined}
*/
this.messageId;
/**
* The value of the message option `message_set_wire_format` or false if not
* set.
* @type {boolean|undefined}
*/
this.isMessageSet;
}
}
/**
* @param {function():!Args} argsSupplier
* @return {function():!Descriptor}
*/
function createGetDescriptorFnFromArgs(argsSupplier) {
return cacheReturnValue(() => DescriptorImpl.fromArgs(argsSupplier()));
}
/**
* @param {string} encodedDescriptor
* @return {function():!Descriptor}
*/
function createGetDescriptorFn(encodedDescriptor) {
return cacheReturnValue(
() => DescriptorImpl.fromEncodedString(encodedDescriptor));
}
/**
* Descriptor information for an extension field.
* @record
*/
class ExtensionFieldInfo {
constructor() {
/** @const {number} */
this.fieldNumber;
/** @const {string} */
this.encodedDescriptor;
/** @const {(function():!Descriptor)|undefined} */
this.submessageDescriptorProvider;
}
}
/**
* A registry of `ExtensionFieldInfo` keyed on the field number.
*
* @typedef {!Object<number, !ExtensionFieldInfo|string>}
*/
let ExtensionRegistry;
function /** !Array<!ExtensionFieldInfo> */ unpackExtensionRegistry(
/** !ExtensionRegistry */ extensionRegistry) {
const /** !Array<!ExtensionFieldInfo> */ extensions = [];
// We want to read the keys as strings since that's what they actually are
// when we iterate with for..in.
const strKeyedRegistry =
/** @type {!Object<string, !ExtensionFieldInfo|string>} */ (
extensionRegistry);
for (const key in strKeyedRegistry) {
const fieldNumber = Number(key);
checkState(
fieldNumber >= 1 && fieldNumber <= MAX_FIELD_NUMBER,
`Field numbers should be <= ${MAX_FIELD_NUMBER} and >= 1, but was ${
fieldNumber}`);
const value = strKeyedRegistry[key];
if (value == null) {
continue;
} else if (typeof value === 'string') {
extensions.push(createExtension(fieldNumber, value));
} else {
extensions.push(value);
}
}
return extensions;
}
/**
* @param {number} fieldNumber
* @param {string} encodedDescriptor The encoded descriptor for the extension
* field. The descriptor should _only_ contain the `FieldType` and any
* `Modifier`s, if applicable.
* @param {(function():!Descriptor)=} submessageDescriptorProvider A provider
* for the submessage descriptor, if applicable for the extension field
* type.
* @return {!ExtensionFieldInfo}
*/
function createExtension(
fieldNumber, encodedDescriptor, submessageDescriptorProvider = undefined) {
return {
fieldNumber,
encodedDescriptor,
submessageDescriptorProvider,
};
}
function /** number */ decodeBase92FromCharCode(/** number */ charCode) {
// Base92 starts at charCode 32. We skip charCodes 34 ("), 39 ('), and
// 92 (\) as they require escaping. When decoding we need to properly
// shift down by 32 and by how many values we've skipped.
if (isNaN(charCode)) {
return NaN;
} else if (charCode > 92) {
return charCode - 35;
} else if (charCode > 39) {
return charCode - 34;
} else if (charCode > 34) {
return charCode - 33;
} else {
return charCode - 32;
}
}
class Base92Reader {
/**
* @param {string} str A base92 encoded string.
* @param {number} offset The index into the backing str that the reader
* should start reading from.
* @param {number} limit The number of characters in the backing str that the
* reader can read up to. If negative then `str.length - offset` will be
* used.
* @private
*/
constructor(str, offset, limit) {
/** @private @const {string} */
this.str_ = str;
/** @private @const {number} */
this.offset_ = offset;
/** @private @const {number} */
this.limit_ = limit >= 0 ? limit : this.str_.length - this.offset_;
/** @private {number} */
this.cursor_ = this.offset_;
/** @private {number} */
this.peekedValue_ = NaN;
this.populatePeekValue_();
}
/**
* @param {string} str The Base92 encoded string
* @return {!Base92Reader}
*/
static readEntireString(str) {
return new Base92Reader(str, /* offset= */ 0, /* limit= */ str.length);
}
/**
* Gets the Base92 at the current location and advances the position.
* @return {number} The Base92 value at the current position, or NaN if out of
* range.
*/
consumeValue() {
const value = this.peekedValue_;
// Only advance if we're not the end.
if (!isNaN(value)) {
this.cursor_++;
this.populatePeekValue_();
}
return value;
}
/**
* @return {number} The Base92 value at the current position, or NaN if out of
* range.
*/
peekValue() {
return this.peekedValue_;
}
/**
* Pre-populates the peeked value before explicitly being requested.
* @private
*/
populatePeekValue_() {
this.peekedValue_ = this.cursor_ < (this.offset_ + this.limit_) ?
decodeBase92FromCharCode(this.str_.charCodeAt(this.cursor_)) :
NaN;
}
}
function /** number */ getNextFieldNumber(
/** !Base92Reader */ reader, /** number */ lastFieldNumber) {
let skipAmount = 0;
let shift = 0;
while (isFieldSkip(reader.peekValue())) {
skipAmount |=
((reader.consumeValue() - fieldTypeConstants.FIELD_SKIPS_START) &
fieldSkipConstants.BITMASK)
<< shift;
shift += fieldSkipConstants.SHIFT_AMOUNT;
}
checkState(
skipAmount >= 0, `Field skips should be >= 0 but was ${skipAmount}`);
const nextFieldNumber = lastFieldNumber + (skipAmount || 1);
checkState(
nextFieldNumber <= MAX_FIELD_NUMBER,
`Field numbers should be <= ${MAX_FIELD_NUMBER} and >= 1, but was ${
nextFieldNumber}`);
return nextFieldNumber;
}
function /** boolean */ isFieldSkip(/** number */ base92Value) {
return base92Value >= fieldTypeConstants.FIELD_SKIPS_START &&
base92Value <= fieldTypeConstants.FIELD_SKIPS_END;
}
/**
* @param {!Base92Reader} reader
* @param {number} fieldNumber The field number of the field being read.
* @param {boolean} extension Whether the field is an extension.
* @param {(function():(function():!Descriptor))=} submessageDescriptorSupplier
* A supplier of the next `getSubmessageDescriptor` function. The supplier
* will be invoked in field number ascending order but only for group and
* message field types. If omitted then the caller is responsible for
* ensuring that the field type will not be a message/group.
* @return {!Field}
*/
function parseField(
reader, fieldNumber, extension, submessageDescriptorSupplier = undefined) {
const fieldTypeValue = reader.consumeValue();
checkState(
isFieldType(fieldTypeValue),
`expected field type but got value: ${fieldTypeValue}`);
const repeated = isRepeatedFieldType(fieldTypeValue);
const fieldType = /** @type {!FieldType} */ (
fieldTypeValue % fieldTypeConstants.REPEATED_FIELDS_START);
const modifiers = isModifier(reader.peekValue()) ? parseModifiers(reader) : 0;
let submessageDescriptorProvider = undefined;
if (fieldType === FieldType.MESSAGE || fieldType === FieldType.GROUP) {
if (submessageDescriptorSupplier) {
submessageDescriptorProvider = submessageDescriptorSupplier();
}
checkState(
submessageDescriptorProvider != null,
`missing submessage descriptor for field ${fieldNumber}`);
}
return {
fieldNumber,
fieldType,
repeated,
extension,
submessageDescriptorProvider,
unpacked: hasModifier(modifiers, Modifier.UNPACKED),
jspbInt64String: hasModifier(modifiers, Modifier.JSPB_STRING),
};
}
function /** boolean */ isFieldType(/** number */ base92Value) {
return (base92Value >= fieldTypeConstants.SINGULAR_FIELDS_START &&
base92Value <= fieldTypeConstants.REPEATED_FIELDS_END) ||
base92Value === fieldTypeConstants.MAP_FIELD;
}
function /** boolean */ isRepeatedFieldType(/** number */ base92Value) {
return (base92Value >= fieldTypeConstants.REPEATED_FIELDS_START &&
base92Value <= fieldTypeConstants.REPEATED_FIELDS_END) ||
base92Value === fieldTypeConstants.MAP_FIELD;
}
function /** number */ parseModifiers(/** !Base92Reader */ reader) {
const value = reader.consumeValue();
checkState(isModifier(value), `expected modifier but got ${value}`);
// Currently only two bits are allocated for modifiers, so all values should
// be <= 3. Ensure that the next value is not also a modifier.
// TODO(kevinoconnor): Maybe remove this check? Or make it debug-only.
if (value <= fieldTypeConstants.MODIFIERS_START + 3 &&
!isModifier(reader.peekValue())) {
return value - fieldTypeConstants.MODIFIERS_START;
}
throw new Error(`Malformed descriptor; modifiers value out of known range.`);
}
function /** boolean */ isModifier(/** number */ base92Value) {
return base92Value >= fieldTypeConstants.MODIFIERS_START &&
base92Value <= fieldTypeConstants.MODIFIERS_END;
}
function checkState(/** boolean */ condition, /** string */ message) {
if (goog.DEBUG && !condition) {
throw new Error(`Malformed descriptor; ${message}`);
}
}
/**
* A bit-mask of extra options attributed to a `Field`.
* @enum {number}
*/
const Modifier = {
UNPACKED: 1 << 0,
JSPB_STRING: 1 << 1,
};
function /** boolean */ hasModifier(
/** number */ modifiers, /** !Modifier */ modifier) {
return !!(modifiers & modifier);
}
exports = {
DescriptorImpl,
ExtensionRegistry,
ExtensionFieldInfo,
Modifier,
createGetDescriptorFn,
createGetDescriptorFnFromArgs,
createExtension,
};
| 30.876984 | 122 | 0.672793 |
3d936da6d0eabcb170ffa1b86053725e9ca2e002 | 1,478 | js | JavaScript | src/monads/either.js | jeanbaptisteassouad/the-monadic-parser | 09d5f9d6fae2ea29b3c4f3d9c998aa82b6054451 | [
"MIT"
] | null | null | null | src/monads/either.js | jeanbaptisteassouad/the-monadic-parser | 09d5f9d6fae2ea29b3c4f3d9c998aa82b6054451 | [
"MIT"
] | null | null | null | src/monads/either.js | jeanbaptisteassouad/the-monadic-parser | 09d5f9d6fae2ea29b3c4f3d9c998aa82b6054451 | [
"MIT"
] | null | null | null | // This is the Either monad
const root_path = '..'
const Accessors = require(root_path + '/accessors')
const none_key = Symbol()
const [getRight, setRight] = Accessors.create()
const [getLeft, setLeft] = Accessors.create()
// (e) -> Either<e, a>
const left = (val) => {
const a = {}
setLeft(val, a)
setRight(none_key, a)
return a
}
// (a) -> Either<e, a>
const right = (val) => {
const a = {}
setLeft(none_key, a)
setRight(val, a)
return a
}
// (Either<e, a>) -> Bool
const isLeft = a => getRight(a) === none_key
// (Either<e, a>) -> Bool
const isRight = a => getLeft(a) === none_key
// (Either<e, a>, (e) -> b, (a) -> b) -> b
const caseOf = (a, leftCallback, rightCallback) => {
if (isRight(a)) {
return rightCallback(getRight(a))
} else {
return leftCallback(getLeft(a))
}
}
// (a) -> Either<e, a>
const pure = right
// (Either<e, a>, (a -> Either<e, b>)) -> Either<e, b>
const then = (a_either, a_to_b_either) => {
if (isLeft(a_either)) {
return a_either
} else {
return a_to_b_either(getRight(a_either))
}
}
// (e, Either<e, a>) -> e
const fromLeft = (c, a_either) => {
if (isLeft(a_either)) {
return getLeft(a_either)
} else {
return c
}
}
// (a, Either<e, a>) -> a
const fromRight = (a, a_either) => {
if (isRight(a_either)) {
return getRight(a_either)
} else {
return a
}
}
module.exports = {
right,
left,
pure,
caseOf,
then,
isRight,
isLeft,
fromRight,
fromLeft,
}
| 17.388235 | 54 | 0.583897 |
3d94557670c68262da567bf476b1f2b0a7cb4a06 | 31,219 | js | JavaScript | index.js | wasilewski-piotr/HalkoTransBot | ae7f6d1868ed91cd5452a3c802868247210b3ab6 | [
"MIT"
] | null | null | null | index.js | wasilewski-piotr/HalkoTransBot | ae7f6d1868ed91cd5452a3c802868247210b3ab6 | [
"MIT"
] | null | null | null | index.js | wasilewski-piotr/HalkoTransBot | ae7f6d1868ed91cd5452a3c802868247210b3ab6 | [
"MIT"
] | null | null | null | const Discord = require('discord.js')
const client = new Discord.Client({ partials: ['MESSAGE', 'REACTION'] })
const config = require('./config.json')
const command = require('./source/command')
const roleClaim = require('./source/role_claim')
const roleClaimAdditional = require('./source/role_claim_additional')
const welcome = require('./embeds/welcome_embed_message')
const discord_entry_log = require('./embeds/discord_log_embed_message')
const discord_rules = require('./embeds/discord_rules_embed_message')
const company_rules = require('./embeds/company_rules_embed_message')
const paintjob = require('./embeds/paintjob_embed_message')
const convoy_commands = require('./embeds/commands_instructions_embed_message')
const company_ids = require('./embeds/company_ids_embed_message')
const recruitment_info = require('./embeds/recruitment_instructions_embed_message')
const cowork_info = require('./embeds/cowork_instructions_embed_messages')
const ping = require('./commands/ping_command')
const clear_channel = require('./commands/clear_channel_command')
const convoy = require('./commands/convoy_command')
const newsy = require('./commands/news_command')
const servers = require('./commands/servers_command')
const show_drivers = require('./commands/drivers_command')
client.on('ready', () =>{
console.log('Client is ready !')
roleClaim(client)
roleClaimAdditional(client)
welcome(client)
discord_entry_log(client)
discord_rules(client)
company_rules(client)
paintjob(client)
convoy_commands(client)
company_ids(client)
recruitment_info(client)
cowork_info(client)
var convoy_title = '\u200B'
var convoy_date = '\u200B'
var convoy_regroup_time = '\u200B'
var convoy_start_time = '\u200B'
var convoy_distance = '\u200B'
var convoy_begin_city = '\u200B'
var convoy_end_city = '\u200B'
var convoy_server_name = '\u200B'
var dlcs = []
var convoy_organizator = '\u200B'
var convoy_map = '\u200B'
var first_pilot = null
var second_pilot = null
let drivers = []
let pilots = []
let users_drivers = []
let users_pilots = []
let scania_list = []
let scania_final = []
let volvo_list = []
let volvo_final = []
let daf_list = []
let daf_final = []
let iveco_list = []
let iveco_final = []
let man_list = []
let man_final = []
let mercedes_list = []
let mercedes_final = []
let renault_list = []
let renault_final = []
const emoji_pilot = client.emojis.cache.find(emoji => emoji.name === 'Pilot')
const emoji_truck = client.emojis.cache.find(emoji => emoji.name === 'Truck')
const emoji_mercedes = client.emojis.cache.find(emoji => emoji.name === 'Mercedes')
const emoji_renault = client.emojis.cache.find(emoji => emoji.name === 'Renault')
const emoji_scania = client.emojis.cache.find(emoji => emoji.name === 'Scania')
const emoji_volvo = client.emojis.cache.find(emoji => emoji.name === 'Volvo')
const emoji_man = client.emojis.cache.find(emoji => emoji.name === 'Man')
const emoji_iveco = client.emojis.cache.find(emoji => emoji.name === 'Iveco')
const emoji_daf = client.emojis.cache.find(emoji => emoji.name === 'Daf')
const emoji_error = client.emojis.cache.find(emoji => emoji.name === "Error")
command(client, 'ping', message_ =>{
ping(client, message_)
})
command(client, 'kierowcy', message =>{
show_drivers(client, message)
})
command(client, 'serwery', message =>{
servers(client, message)
})
command(client, 'cc', message => {
if(message.member.hasPermission('ADMINISTRATOR')){
clear_channel(message)
}
})
command(client, 'ogłoszenie', message => {
if(message.member.hasPermission('ADMINISTRATOR')){
newsy(client, message)
}
})
command(client, 'setTitle', message => {
message.delete({timeout: 100})
if(message.member.hasPermission('ADMINISTRATOR')){
var name = message.content.replace('!setTitle ', '')
convoy_title = name
const channel = client.channels.cache.get(message.channel.id)
channel.send(`Dodano nazwę konwoju - ${convoy_title}`)
}else{
message.channel.send('You cannot do that !').then(msg => {
msg.delete({timeout: 4000})
})
}
})
command(client, 'setDate', message =>{
message.delete({timeout: 100})
if(message.member.hasPermission('ADMINISTRATOR')){
var name = message.content.replace('!setDate ', '')
convoy_date = name
const channel = client.channels.cache.get(message.channel.id)
channel.send(`Dodano datę konwoju - ${convoy_date}`)
}else{
message.channel.send('You cannot do that !').then(msg => {
msg.delete({timeout: 4000})
})
}
})
command(client, 'setRegroupTime', message =>{
message.delete({timeout: 100})
if(message.member.hasPermission('ADMINISTRATOR')){
var name = message.content.replace('!setRegroupTime ', '')
convoy_regroup_time = name
const channel = client.channels.cache.get(message.channel.id)
channel.send(`Dodano godzinę zbiórki na konwój - ${convoy_regroup_time}`)
}else{
message.channel.send('You cannot do that !').then(msg => {
msg.delete({timeout: 4000})
})
}
})
command(client, 'setStartTime', message =>{
message.delete({timeout: 100})
if(message.member.hasPermission('ADMINISTRATOR')){
var name = message.content.replace('!setStartTime ', '')
convoy_start_time = name
const channel = client.channels.cache.get(message.channel.id)
channel.send(`Dodano godzinę rozpoczęcia konwoju - ${convoy_start_time}`)
}else{
message.channel.send('You cannot do that !').then(msg => {
msg.delete({timeout: 4000})
})
}
})
command(client, 'setDistance', message =>{
message.delete({timeout: 100})
if(message.member.hasPermission('ADMINISTRATOR')){
var name = message.content.replace('!setDistance ', '')
convoy_distance = name + ' km'
const channel = client.channels.cache.get(message.channel.id)
channel.send(`Dodano dystans konwoju - ${convoy_distance}`)
}else{
message.channel.send('You cannot do that !').then(msg => {
msg.delete({timeout: 4000})
})
}
})
command(client, 'setBeginCity', message =>{
message.delete({timeout: 100})
if(message.member.hasPermission('ADMINISTRATOR')){
var name = message.content.replace('!setBeginCity ', '')
convoy_begin_city = name
const channel = client.channels.cache.get(message.channel.id)
channel.send(`Dodano miasto startowe - ${convoy_begin_city}`)
}else{
message.channel.send('You cannot do that !').then(msg => {
msg.delete({timeout: 4000})
})
}
})
command(client, 'setEndCity', message =>{
message.delete({timeout: 100})
if(message.member.hasPermission('ADMINISTRATOR')){
var name = message.content.replace('!setEndCity ', '')
convoy_end_city = name
const channel = client.channels.cache.get(message.channel.id)
channel.send(`Dodano miasto końcowe - ${convoy_end_city}`)
}else{
message.channel.send('You cannot do that !').then(msg => {
msg.delete({timeout: 4000})
})
}
})
command(client, 'setServer', message =>{
message.delete({timeout: 100})
if(message.member.hasPermission('ADMINISTRATOR')){
var name = message.content.replace('!setServer ', '')
convoy_server_name = name
const channel = client.channels.cache.get(message.channel.id)
channel.send(`Dodano nazwę serwera - ${convoy_server_name}`)
}else{
message.channel.send('You cannot do that !').then(msg => {
msg.delete({timeout: 4000})
})
}
})
command(client, 'addDLC', message =>{
message.delete({timeout: 100})
if(message.member.hasPermission('ADMINISTRATOR')){
if(message === ''){
console.log('Empty message')
}else{
var name = message.content.replace('!addDLC ', '')
dlc_id = `<@&${name}>`
dlcs.push(dlc_id)
const channel = client.channels.cache.get(message.channel.id)
channel.send(`DLC wymagane do wzięcia udziału - ${dlcs}`)
}
}else{
message.channel.send('You cannot do that !').then(msg => {
msg.delete({timeout: 4000})
})
}
})
command(client, 'setOrganizator', message =>{
message.delete({timeout: 100})
if(message.member.hasPermission('ADMINISTRATOR')){
if(message === ''){
console.log('Empty message')
}else{
var name = message.content.replace('!setOrganizator ', '')
convoy_organizator = `<@&${name}>`
const channel = client.channels.cache.get(message.channel.id)
channel.send(`Dodano organizatora konwoju - ${convoy_organizator}`)
}
}else{
message.channel.send('You cannot do that !').then(msg => {
msg.delete({timeout: 4000})
})
}
})
command(client, 'setMap', message =>{
message.delete({timeout: 100})
if(message.member.hasPermission('ADMINISTRATOR')){
var name = message.content.replace('!setMap ', '')
convoy_map = name
const channel = client.channels.cache.get(message.channel.id)
console.log(convoy_map)
channel.send(`Dodano mapę konwoju`)
}else{
message.channel.send('You cannot do that !').then(msg => {
msg.delete({timeout: 4000})
})
}
})
command(client, 'clearConvoyData', message =>{
message.delete({timeout: 100})
if(message.member.hasPermission('ADMINISTRATOR')){
convoy_title = '\u200B'
convoy_date = '\u200B'
convoy_regroup_time = '\u200B'
convoy_start_time = '\u200B'
convoy_distance = '\u200B'
convoy_begin_city = '\u200B'
convoy_end_city = '\u200B'
convoy_server_name = '\u200B'
convoy_organizator = '\u200B'
dlcs = []
const channel = client.channels.cache.get(message.channel.id)
channel.send(`Dane konwoju zostały wyczyszczone`).then(msg => {
msg.delete({timeout: 4000})
})
}else{
message.channel.send('You cannot do that !').then(msg => {
msg.delete({timeout: 4000})
})
}
})
command(client, 'konwój', message => {
message.delete({timeout: 100})
if(message.member.hasPermission('ADMINISTRATOR')){
const channel = client.channels.cache.get(message.channel.id)
convoy(client, message, convoy_title, convoy_date, convoy_regroup_time, convoy_start_time, convoy_distance, convoy_begin_city, convoy_end_city, convoy_server_name, dlcs, convoy_organizator, convoy_map)
channel.send(`Opublikowano konwój`).then(msg => {
msg.delete({timeout: 4000})
})
message.channel.messages.fetch().then(results => {
message.channel.bulkDelete(results)
})
}else{
message.channel.send('You cannot do that !').then(msg => {
msg.delete({timeout: 4000})
})
}
})
const editMessageConvoyUsers = (pilots, drivers, channel) => {
var desription = ''
channel.messages.fetch({limit:2}).then((messages) => {
if(drivers.length === 0 && pilots.length === 0) {
desription = `Kierowcy zapisani na konwój:\n\n${emoji_error} Brak zgłoszeń\n\n`
} else {
if(drivers.length != 0 && pilots.length === 0) {
desription = `Kierowcy zapisani na konwój:\n\n${drivers}\n\n\n`
}
if(pilots.length != 0 && drivers.length === 0) {
desription = `Kierowcy zapisani na konwój:\n\n${pilots}\n\n\n`
}
if(pilots.length != 0 && drivers.length != 0) {
desription = `Kierowcy zapisani na konwój\n\n**Piloci:**\n\n${pilots}\n\n**Kierowcy:**\n\n${drivers}\n\n\n`
}
}
let message = messages.first()
let embed = new Discord.MessageEmbed()
.setColor('#00c3ff')
.setTitle('Zapisy na konwój')
.setDescription(desription)
.setTimestamp()
.setFooter(client.user.username, client.user.displayAvatarURL())
message.edit(embed)
})
}
const editMessageProducent = (channel, scania, volvo, daf, man, mercedes) => {
let producent = ``
var masterArry = [scania, volvo, daf, man, mercedes]
var maxArrSingle = function(arr) {
return arr.reduce(
function(acc,val){
return Math.max(acc,val);
},
-Infinity);
}
var maxArrIndexes = function(arr) {
var max = maxArrSingle(arr);
return arr.reduce(function(acc,val,idx) {
if (val >= max) acc.push(idx);
return acc;
},[]);
}
const lengths = masterArry.map(a => a.length)
if(lengths.every(a => a === 0)){
producent = `${emoji_error} Brak głosów\n\n`
}else{
let index = maxArrIndexes(Array.from(lengths))
if(index.length === 1 ){
if(index[0] === 0) { producent = `${emoji_scania} Scania\n\n` }
if(index[0] === 1) { producent = `${emoji_volvo} Volvo\n\n` }
if(index[0] === 2) { producent = `${emoji_daf} Daf\n\n` }
if(index[0] === 3) { producent = `${emoji_man} Man\n\n` }
if(index[0] === 4) { producent = `${emoji_mercedes} Mercedes\n\n` }
} else {
producent = `${emoji_error} Nie udało się wybrać ciężarówki\n\n`
}
}
channel.messages.fetch({limit:2}).then((messages) => {
let message = messages.last()
let embed = new Discord.MessageEmbed()
.setColor('#00c3ff')
.setTitle('Wybór ciężarówki do konwoju')
.setDescription(`Producent ciężarówki wybrany na konwój:\n\n${producent}\n\n`)
.setTimestamp()
.setFooter(client.user.username, client.user.displayAvatarURL())
message.edit(embed)
})
}
const checkTruckEmoji = async (reaction) => {
const { guild } = reaction.message
const channel = await client.channels.fetch(reaction.message.channel.id)
const messageID = reaction.message.id
const fetchMessage = await reaction.message.channel.messages.fetch(messageID);
let reactions = fetchMessage.reactions.cache.find(emoji => emoji.emoji.name === "Truck")
fetchMessage.reactions.cache.map(async (reaction) => {
if(reaction.emoji.name !== "Truck") return;
let reactedUsers = await reaction.users.fetch()
reactedUsers.map((user) =>{
if(user.id === '781188809962422323'){
}else{
const member = guild.members.cache.find(member => member.id === user.id)
if(pilots.indexOf(`${emoji_pilot} <@${user.id}>`) > -1){
reaction.users.remove(user.id)
}else{
users_drivers.push(`${emoji_truck} <@${user.id}>`)
}
}
})
drivers = users_drivers.join('\n').trim()
editMessageConvoyUsers(pilots, drivers, channel)
users_drivers = []
})
}
const checkPilotEmoji = async (reaction) => {
const { guild } = reaction.message
const channel = await client.channels.fetch(reaction.message.channel.id)
const messageID = reaction.message.id
const fetchMessage = await reaction.message.channel.messages.fetch(messageID);
let reactions = fetchMessage.reactions.cache.find(emoji => emoji.emoji.name === "Pilot")
fetchMessage.reactions.cache.map(async (reaction) => {
if(reaction.emoji.name !== "Pilot") return;
let reactedUsers = await reaction.users.fetch()
reactedUsers.map((user) =>{
if(first_pilot != null && first_pilot.includes(user.id)){
first_pilot = null
}
if(second_pilot != null && second_pilot.includes(user.id)){
second_pilot = null
}
if(first_pilot != null && second_pilot != null) {
if(user.id != '781188809962422323'){
reaction.users.remove(user.id)
}
}
if(user.id === '781188809962422323'){
}else{
const member = guild.members.cache.find(member => member.id === user.id)
if(drivers.indexOf(`${emoji_truck} <@${user.id}>`) > -1){
reaction.users.remove(user.id)
}else{
if(member.roles.cache.some(role => role.name === 'PILOT') === true){
value = `${emoji_pilot} <@${user.id}>`
if(first_pilot === null) {
first_pilot = value
} else if(first_pilot != null && second_pilot === null) {
if(first_pilot != value){
second_pilot = value
}
}
} else {
reaction.users.remove(user.id)
}
}
}
})
pilots = [first_pilot, second_pilot].join('\n').trim()
editMessageConvoyUsers(pilots, drivers, channel)
users_pilots = []
})
}
const checkScaniaEmoji = async (reaction) => {
const { guild } = reaction.message
const channel = await client.channels.fetch(reaction.message.channel.id)
const messageID = reaction.message.id
const fetchMessage = await reaction.message.channel.messages.fetch(messageID);
fetchMessage.reactions.cache.map(async (reaction) => {
if(reaction.emoji.name === "Scania"){
let reactedUsers = await reaction.users.fetch()
reactedUsers.map((user) => {
if(user.id === '781188809962422323'){
}else{
if(scania_list.indexOf(user.id) > -1){
console.log("User already voted")
}else{
scania_list.push(user.id)
}
}
})
scania_final = scania_list
editMessageProducent(channel, scania_final, volvo_final, daf_final, man_final, mercedes_final)
scania_list = []
}
})
}
const checkVolvoEmoji = async (reaction) => {
const { guild } = reaction.message
const channel = await client.channels.fetch(reaction.message.channel.id)
const messageID = reaction.message.id
const fetchMessage = await reaction.message.channel.messages.fetch(messageID);
fetchMessage.reactions.cache.map(async (reaction) => {
if(reaction.emoji.name === "Volvo"){
let reactedUsers = await reaction.users.fetch()
reactedUsers.map((user) => {
if(user.id === '781188809962422323'){
}else{
if(volvo_list.indexOf(user.id) > -1){
console.log("User already voted")
}else{
volvo_list.push(user.id)
}
}
})
volvo_final = volvo_list
editMessageProducent(channel, scania_final, volvo_final, daf_final, man_final, mercedes_final)
volvo_list = []
}
})
}
const checkDafEmoji = async (reaction) => {
const { guild } = reaction.message
const channel = await client.channels.fetch(reaction.message.channel.id)
const messageID = reaction.message.id
const fetchMessage = await reaction.message.channel.messages.fetch(messageID);
fetchMessage.reactions.cache.map(async (reaction) => {
if(reaction.emoji.name === "Daf"){
let reactedUsers = await reaction.users.fetch()
reactedUsers.map((user) => {
if(user.id === '781188809962422323'){
}else{
if(daf_list.indexOf(user.id) > -1){
console.log("User already voted")
}else{
daf_list.push(user.id)
}
}
})
daf_final = daf_list
editMessageProducent(channel, scania_final, volvo_final, daf_final, man_final, mercedes_final)
daf_list = []
}
})
}
const checkIvecoEmoji = async (reaction) => {
const { guild } = reaction.message
const channel = await client.channels.fetch(reaction.message.channel.id)
const messageID = reaction.message.id
const fetchMessage = await reaction.message.channel.messages.fetch(messageID);
fetchMessage.reactions.cache.map(async (reaction) => {
if(reaction.emoji.name === "Iveco"){
let reactedUsers = await reaction.users.fetch()
reactedUsers.map((user) => {
if(user.id === '781188809962422323'){
}else{
if(iveco_list.indexOf(user.id) > -1){
console.log("User already voted")
}else{
iveco_list.push(user.id)
}
}
})
iveco_final = iveco_list
editMessageProducent(channel, scania_final, volvo_final, daf_final, man_final, mercedes_final)
daf_list = []
}
})
}
const checkManEmoji = async (reaction) => {
const { guild } = reaction.message
const channel = await client.channels.fetch(reaction.message.channel.id)
const messageID = reaction.message.id
const fetchMessage = await reaction.message.channel.messages.fetch(messageID);
fetchMessage.reactions.cache.map(async (reaction) => {
if(reaction.emoji.name === "Man"){
let reactedUsers = await reaction.users.fetch()
reactedUsers.map((user) => {
if(user.id === '781188809962422323'){
}else{
if(man_list.indexOf(user.id) > -1){
console.log("User already voted")
}else{
man_list.push(user.id)
}
}
})
man_final = man_list
editMessageProducent(channel, scania_final, volvo_final, daf_final, man_final, mercedes_final)
man_list = []
}
})
}
const checkMercedesEmoji = async (reaction) => {
const { guild } = reaction.message
const channel = await client.channels.fetch(reaction.message.channel.id)
const messageID = reaction.message.id
const fetchMessage = await reaction.message.channel.messages.fetch(messageID);
fetchMessage.reactions.cache.map(async (reaction) => {
if(reaction.emoji.name === "Mercedes"){
let reactedUsers = await reaction.users.fetch()
reactedUsers.map((user) => {
if(user.id === '781188809962422323'){
}else{
if(mercedes_list.indexOf(user.id) > -1){
console.log("User already voted")
}else{
mercedes_list.push(user.id)
}
}
})
mercedes_final = mercedes_list
editMessageProducent(channel, scania_final, volvo_final, daf_final, man_final, mercedes_final)
mercedes_list = []
}
})
}
const checkRenaultEmoji = async (reaction) => {
const { guild } = reaction.message
const channel = await client.channels.fetch(reaction.message.channel.id)
const messageID = reaction.message.id
const fetchMessage = await reaction.message.channel.messages.fetch(messageID);
fetchMessage.reactions.cache.map(async (reaction) => {
if(reaction.emoji.name === "Renault"){
let reactedUsers = await reaction.users.fetch()
reactedUsers.map((user) => {
if(user.id === '781188809962422323'){
}else{
if(renault_list.indexOf(user.id) > -1){
console.log("User already voted")
}else{
renault_list.push(user.id)
}
}
})
renault_final = renault_list
editMessageProducent(channel, scania_final, volvo_final, daf_final, man_final, mercedes_final)
renault_list = []
}
})
}
client.on('messageReactionAdd', async (reaction, user) =>{
if(reaction.message.partial){
let msg = await reaction.message.fetch()
checkTruckEmoji(reaction)
checkPilotEmoji(reaction)
checkScaniaEmoji(reaction)
checkVolvoEmoji(reaction)
checkDafEmoji(reaction)
// checkIvecoEmoji(reaction)
checkManEmoji(reaction)
checkMercedesEmoji(reaction)
// checkRenaultEmoji(reaction)
//checkPilotEmoji(reaction)
}else{
checkTruckEmoji(reaction)
checkPilotEmoji(reaction)
checkScaniaEmoji(reaction)
checkVolvoEmoji(reaction)
checkDafEmoji(reaction)
// checkIvecoEmoji(reaction)
checkManEmoji(reaction)
checkMercedesEmoji(reaction)
// checkRenaultEmoji(reaction)
//checkPilotEmoji(reaction)
}
})
client.on('messageReactionRemove', async (reaction, user) =>{
if(reaction.message.partial){
let msg = await reaction.message.fetch()
checkTruckEmoji(reaction)
checkPilotEmoji(reaction)
checkScaniaEmoji(reaction)
checkVolvoEmoji(reaction)
checkDafEmoji(reaction)
// checkIvecoEmoji(reaction)
checkManEmoji(reaction)
checkMercedesEmoji(reaction)
// checkRenaultEmoji(reaction)
// checkPilotEmoji(reaction)
}else{
checkTruckEmoji(reaction)
checkPilotEmoji(reaction)
if(first_pilot != null && first_pilot.includes(user.id)){
first_pilot = null
}
if(second_pilot != null && second_pilot.includes(user.id)){
second_pilot = null
}
checkScaniaEmoji(reaction)
checkVolvoEmoji(reaction)
checkDafEmoji(reaction)
// checkIvecoEmoji(reaction)
checkManEmoji(reaction)
checkMercedesEmoji(reaction)
// checkRenaultEmoji(reaction)
//checkPilotEmoji(reaction)
}
})
const addReactions = (message, reactions) => {
message.react(reactions[0])
reactions.shift()
if(reactions.length > 0){
setTimeout(() => addReactions(message, reactions), 750)
}
}
command(client, 'zapisy', message => {
message.delete({timeout: 100})
let react = [emoji_truck, emoji_pilot]
let react_prod = [emoji_scania, emoji_volvo, emoji_daf, emoji_man, emoji_mercedes]
let embed_prod = new Discord.MessageEmbed()
.setColor('#00c3ff')
.setTitle('Wybór ciężarówki do konwoju')
.setDescription(`Producent ciężarówki wybrany na konwój:`)
.setTimestamp()
.setFooter(client.user.username, client.user.displayAvatarURL())
let embed = new Discord.MessageEmbed()
.setColor('#00c3ff')
.setTitle('Zapisy na konwój')
.setDescription(`Kierowcy zapisani na konwój`)
.setTimestamp()
.setFooter(client.user.username, client.user.displayAvatarURL())
message.channel.messages.fetch().then((messages) => {
message.channel.send(embed_prod).then((message) =>{
addReactions(message, react_prod)
message_producent = message
})
})
message.channel.messages.fetch().then((messages) => {
message.channel.send(embed).then((message) =>{
addReactions(message, react)
})
})
id = message.channel.id
})
command(client, 'ciezarowka', message => {
message.delete({timeout: 100})
let react = [emoji_scania, emoji_volvo, emoji_daf, emoji_man, emoji_mercedes]
let embed = new Discord.MessageEmbed()
.setColor('#00c3ff')
.setTitle('Wybór ciężarówki do konwoju')
.setDescription(`Producent ciężarówki wybrany na konwój:`)
.setTimestamp()
.setFooter(client.user.username, client.user.displayAvatarURL())
message.channel.messages.fetch().then((messages) => {
message.channel.send(embed).then((message) =>{
addReactions(message, react)
})
})
id = message.channel.id
})
})
client.login(config.token) | 38.829602 | 213 | 0.542554 |
3d94efa79186ad4ab99f5e0c8dcfc9ca36078b2f | 638 | js | JavaScript | src/index.js | kfalicov/phaser-3-template | 668c587f27db6ca500b7c3af977a34e07f9ab77c | [
"MIT"
] | null | null | null | src/index.js | kfalicov/phaser-3-template | 668c587f27db6ca500b7c3af977a34e07f9ab77c | [
"MIT"
] | null | null | null | src/index.js | kfalicov/phaser-3-template | 668c587f27db6ca500b7c3af977a34e07f9ab77c | [
"MIT"
] | null | null | null | import { Game, WEBGL, Scale } from "phaser";
import { Loader, Menu, Game as GameScene } from "./scenes";
const config = {
type: WEBGL,
parent: "gamewrapper",
width: 320,
height: 240,
scale: {
zoom: Scale.MAX_ZOOM,
},
render: {
pixelArt: true,
},
title: "template",
physics: {
default: "arcade",
arcade: {
fps: 60,
// debug:true
},
},
seed: ["test"],
scene: [Loader, Menu, GameScene],
};
// lets the game resize when the window resizes
window.addEventListener(
"resize",
function (event) {
game.scale.setMaxZoom();
},
false
);
export const game = new Game(config);
| 16.789474 | 59 | 0.595611 |
3d94fae626df5e5baaec6e543c32d553228cff87 | 2,132 | js | JavaScript | src/shared/configure-store.js | graymur/rcn.io | 6c5bc8e809c5e0a615d5b607a42a3c9e1940f9bf | [
"MIT"
] | 47 | 2015-10-05T00:43:00.000Z | 2022-03-28T14:19:37.000Z | src/shared/configure-store.js | graymur/rcn.io | 6c5bc8e809c5e0a615d5b607a42a3c9e1940f9bf | [
"MIT"
] | 162 | 2015-10-04T19:08:19.000Z | 2022-02-10T09:19:29.000Z | src/shared/configure-store.js | graymur/rcn.io | 6c5bc8e809c5e0a615d5b607a42a3c9e1940f9bf | [
"MIT"
] | 23 | 2015-11-18T16:53:23.000Z | 2021-04-15T11:01:49.000Z | import { createStore, applyMiddleware, compose } from 'redux'
import rootReducer from 'shared/reducers/reducer.js'
import createSagaMiddleware from 'redux-saga'
import rootSaga from 'shared/sagas/root'
import { browserHistory } from 'react-router'
import { routerMiddleware as createRouterMiddleware } from 'react-router-redux'
const routingMiddlewhare = createRouterMiddleware(browserHistory)
const sagaMiddleware = createSagaMiddleware()
const middlewares = [
sagaMiddleware,
// used to process routing actions like push() and replace() (navigaiton with redux actions)
// it's not required for routing to work with redux if actions are not used
routingMiddlewhare
]
// use logging middleware only in dev mode
if (process.env.NODE_ENV === 'development') {
const createLogger = require('redux-logger')
const logger = createLogger({
diff: false, //diff it adds like 1s overhead for 300-400 events
timestamp: false,
duration: true,
collapsed: true,
colors: {
title: (action) => '#EEE',
prevState: (state) => '#9e9e9e',
action: (action) => 'yellowgreen',
nextState: (state) => '#98AFC7'
}
})
middlewares.push(logger)
// const reactPerfMiddleware = require('shared/middlewares/react-perf-middleware').default
// middlewares.push(reactPerfMiddleware)
}
const configureStore = (initialState) => {
const store = createStore(
rootReducer,
initialState,
compose(
applyMiddleware(...middlewares), //logger must be last middleware,
// server-side safe enabling of Redux Dev tools
typeof window === 'object' && typeof window.devToolsExtension !== 'undefined' ? window.devToolsExtension() : f => f
)
)
sagaMiddleware.run(rootSaga)
//according to https://github.com/reactjs/react-redux/releases/tag/v2.0.0
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('shared/reducers/reducer.js', () => {
const nextRootReducer = require('shared/reducers/reducer.js').default
store.replaceReducer(nextRootReducer)
})
}
return store
}
export default configureStore
| 30.898551 | 121 | 0.711538 |
3d95d736e7f64542e40081cd0b4f8374c5c40ec5 | 7,393 | js | JavaScript | packages/utils/block-utils/src/blockSchema.js | bhargavaman/lowdefy | e5146378746fa532fc4da2e74c05133e2d8dcfcd | [
"Apache-2.0"
] | null | null | null | packages/utils/block-utils/src/blockSchema.js | bhargavaman/lowdefy | e5146378746fa532fc4da2e74c05133e2d8dcfcd | [
"Apache-2.0"
] | null | null | null | packages/utils/block-utils/src/blockSchema.js | bhargavaman/lowdefy | e5146378746fa532fc4da2e74c05133e2d8dcfcd | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020-2022 Lowdefy, 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.
*/
export default {
type: 'object',
additionalProperties: false,
required: ['id', 'type'],
properties: {
id: {
type: 'string',
},
required: {
type: ['boolean', 'object'],
},
type: {
type: 'string',
},
properties: {
type: 'object',
},
style: {
type: 'object',
},
layout: {
type: 'object',
},
blocks: {
type: 'array',
items: {
type: 'object',
},
},
events: {
type: 'object',
},
menus: {
type: 'array',
items: {
type: 'object',
required: ['id'],
properties: {
id: {
type: 'string',
description: 'Menu id.',
},
links: {
type: 'array',
items: {
type: 'object',
required: ['id', 'type'],
properties: {
id: {
type: 'string',
description: 'Menu item id.',
},
type: {
type: 'string',
enum: ['MenuDivider', 'MenuLink', 'MenuGroup'],
description: 'Menu item type.',
},
pageId: {
type: 'string',
description: 'Page to link to.',
},
style: {
type: 'object',
description: 'Css style to applied to link.',
},
properties: {
type: 'object',
description: 'properties from menu item.',
properties: {
title: {
type: 'string',
description: 'Menu item title.',
},
icon: {
type: ['string', 'object'],
description:
'Name of an React-Icon (See <a href="https://react-icons.github.io/react-icons/">all icons</a>) or properties of an Icon block to customize icon on menu item.',
},
danger: {
type: 'boolean',
description: 'Apply danger style to menu item.',
},
dashed: {
type: 'boolean',
default: false,
description: 'Whether the divider line is dashed.',
},
},
},
links: {
type: 'array',
items: {
type: 'object',
required: ['id', 'type'],
properties: {
id: {
type: 'string',
description: 'Menu item id.',
},
type: {
type: 'string',
enum: ['MenuDivider', 'MenuLink', 'MenuGroup'],
description: 'Menu item type.',
},
style: {
type: 'object',
description: 'Css style to applied to sub-link.',
},
pageId: {
type: 'string',
description: 'Page to link to.',
},
properties: {
type: 'object',
description: 'properties from menu item.',
properties: {
title: {
type: 'string',
description: 'Menu item title.',
},
danger: {
type: 'boolean',
description: 'Apply danger style to menu item.',
},
dashed: {
type: 'boolean',
default: false,
description: 'Whether the divider line is dashed.',
},
},
links: {
type: 'array',
items: {
type: 'object',
required: ['id', 'type'],
properties: {
id: {
type: 'string',
description: 'Menu item id.',
},
type: {
type: 'string',
enum: ['MenuDivider', 'MenuLink'],
description: 'Menu item type.',
},
style: {
type: 'object',
description: 'Css style to applied to sub-link.',
},
pageId: {
type: 'string',
description: 'Page to link to.',
},
properties: {
type: 'object',
description: 'properties from menu item.',
properties: {
title: {
type: 'string',
description: 'Menu item title.',
},
danger: {
type: 'boolean',
description: 'Apply danger style to menu item.',
},
dashed: {
type: 'boolean',
default: false,
description: 'Whether the divider line is dashed.',
},
},
},
},
},
},
},
},
},
},
},
},
},
},
},
},
areas: {
type: 'object',
patternProperties: {
'^.*$': {
type: 'object',
properties: {
blocks: {
type: 'array',
items: {
type: 'object',
},
},
},
},
},
},
},
};
| 33.604545 | 184 | 0.320844 |
3d9659a61120e11c82b7543a4f3ee52fd0ecbe5e | 601 | js | JavaScript | src/components/search_bar.js | dunton/ryantube | db094e8181e4751494518e18e60bca88a54305b4 | [
"MIT"
] | null | null | null | src/components/search_bar.js | dunton/ryantube | db094e8181e4751494518e18e60bca88a54305b4 | [
"MIT"
] | 2 | 2020-07-19T10:52:23.000Z | 2021-05-11T01:55:47.000Z | src/components/search_bar.js | dunton/ryantube | db094e8181e4751494518e18e60bca88a54305b4 | [
"MIT"
] | null | null | null | // search_bar.js
import React, { Component } from 'react';
class SearchBar extends Component {
constructor(props) {
super(props);
// ONLY USE THIS.STATE = IN THE CONSTRUCTOR
// OTHERWISE WE USE this.setState
this.state = { term: '' };
}
render () {
return (
<div className="search-bar">
<input
value = {this.state.term}
onChange={event => this.onInputChange(event.target.value)}
placeholder="Search Youtube..."
/>
</div>
);
}
onInputChange(term) {
this.setState({term});
this.props.onSearchTermChange(term);
}
}
export default SearchBar; | 17.676471 | 63 | 0.637271 |
3d96dc524d082e347ff02d48310e45dd4dfc3355 | 836 | js | JavaScript | src/pages/index.js | ericmlyons/ericmlyons.github.io | 2059d0de9cbad8de14907bafbc856353b4fb7e0a | [
"0BSD"
] | null | null | null | src/pages/index.js | ericmlyons/ericmlyons.github.io | 2059d0de9cbad8de14907bafbc856353b4fb7e0a | [
"0BSD"
] | 1 | 2021-11-05T02:10:31.000Z | 2021-11-05T02:10:31.000Z | src/pages/index.js | ericmlyons/ericmlyons.github.io | 2059d0de9cbad8de14907bafbc856353b4fb7e0a | [
"0BSD"
] | null | null | null | import React from "react";
import Layout from "../components/layout";
import SEO from "../components/seo";
import Banner from "../components/homedefault/banner";
import About from "../components/homedefault/about";
import Project from "../components/homedefault/project";
import Testimonial from "../components/homedefault/testimonial";
import Service from "../components/homedefault/service";
import Brand from "../components/homedefault/brand";
import BlogPost from "../components/blogPost";
import Contact from "../elements/contact/contact";
const Index = () => (
<Layout>
<SEO title="Waxon" />
<Banner />
<About />
<Service />
<div className="portfolio-id" id="portfolio">
<Project />
<Brand />
<Testimonial />
</div>
<BlogPost />
<Contact />
</Layout>
)
export default Index; | 28.827586 | 64 | 0.67823 |
3d9784f5556aa5ebb294466dbe625248c1b7bdbb | 30,101 | js | JavaScript | public/6.js | edwardlorilla/books | 7cc4053ba50b2e3d6dd5bb668be51278396d64a5 | [
"MIT"
] | null | null | null | public/6.js | edwardlorilla/books | 7cc4053ba50b2e3d6dd5bb668be51278396d64a5 | [
"MIT"
] | null | null | null | public/6.js | edwardlorilla/books | 7cc4053ba50b2e3d6dd5bb668be51278396d64a5 | [
"MIT"
] | null | null | null | (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[6],{
/***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/Table/Grid.vue?vue&type=script&lang=js&":
/*!*********************************************************************************************************************************************************************!*\
!*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/components/Table/Grid.vue?vue&type=script&lang=js& ***!
\*********************************************************************************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ __webpack_exports__["default"] = ({
props: {
createName: String,
onCreateName: String,
onEditName: String,
onDelete: String,
data: {},
columns: Array
},
data: function data() {
var vm = this;
return {
search: vm.$route.query.search ? vm.$route.query.search : '',
loading: false
};
},
methods: {
handleSortChange: function handleSortChange(val) {
var vm = this;
var option = _.clone(vm.$route.query);
option.column = val.prop;
option.direction = val.order == 'ascending' ? 'asc' : 'desc';
vm.onRouteChange(option);
},
handleCurrentChange: function handleCurrentChange(val) {
var vm = this;
var option = _.clone(vm.$route.query);
option.page = val;
vm.onRouteChange(option);
},
onRouteChange: function onRouteChange(option) {
var vm = this;
vm.loading = true;
vm.$router.push({
path: "".concat(vm.$route.path),
query: option
}, function () {
vm.loading = false;
}, function () {
vm.loading = false;
});
},
search_: function search_() {
var vm = this;
vm.onSearch(vm.search, vm);
},
onSearch: _.debounce(function (query, vm) {
var vm = this;
vm.loading = true;
vm.$router.push({
path: "".concat(vm.$route.path),
query: {
search: query
}
}, function () {
vm.loading = false;
}, function () {
vm.loading = false;
});
}, 500),
handleEdit: function handleEdit(index, row) {
var vm = this;
vm.$router.push({
name: vm.onEditName,
params: {
id: row.id
}
});
},
handleDelete: function handleDelete(index, row) {
var _this = this;
var vm = this;
vm.loading = true;
vm.$confirm('This will permanently delete the file. Continue?', 'Warning', {
confirmButtonText: 'OK',
cancelButtonText: 'Cancel',
type: 'warning'
}).then(function () {
axios.delete("".concat(vm.onDelete ? vm.onDelete : '/api/agencies', "/").concat(row.id));
vm.$emit('delete', index);
_this.$message({
type: 'success',
message: 'Delete completed'
});
vm.loading = false;
}).catch(function () {
_this.$message({
type: 'info',
message: 'Delete canceled'
});
vm.loading = false;
});
}
}
});
/***/ }),
/***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/book/view.vue?vue&type=script&lang=js&":
/*!********************************************************************************************************************************************************************!*\
!*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/components/book/view.vue?vue&type=script&lang=js& ***!
\********************************************************************************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Table_Grid_vue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./../Table/Grid.vue */ "./resources/js/components/Table/Grid.vue");
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ __webpack_exports__["default"] = ({
data: function data() {
return {
columns: [{
label: 'Author name',
prop: 'author.name',
sort: true
}, {
label: 'Category name',
prop: 'category.name',
sort: true
}, {
label: 'ISBN',
prop: 'isbn',
sort: true
}, {
label: 'Title',
prop: 'title',
sort: true
}, {
label: 'Date of Publication',
prop: 'date_of_publication',
sort: true
}],
data: []
};
},
components: {
GridView: _Table_Grid_vue__WEBPACK_IMPORTED_MODULE_0__["default"]
},
beforeRouteEnter: function beforeRouteEnter(to, from, next) {
axios.get("/api/books", {
params: to.query
}).then(function (response) {
next(function (vm) {
return vm.setData(response.data);
});
});
},
beforeRouteUpdate: function beforeRouteUpdate(to, from, next) {
var vm = this;
axios.get("/api/books", {
params: to.query
}).then(function (response) {
vm.setData(response.data);
next();
});
},
methods: {
setData: function setData(response) {
this.data = response;
}
}
});
/***/ }),
/***/ "./node_modules/css-loader/index.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/book/view.vue?vue&type=style&index=0&lang=css&":
/*!***************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/css-loader??ref--6-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--6-2!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/components/book/view.vue?vue&type=style&index=0&lang=css& ***!
\***************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(/*! ../../../../node_modules/css-loader/lib/css-base.js */ "./node_modules/css-loader/lib/css-base.js")(false);
// imports
// module
exports.push([module.i, "\n\n\n\n\n\n\n\n\n\n\n\n\n", ""]);
// exports
/***/ }),
/***/ "./node_modules/style-loader/index.js!./node_modules/css-loader/index.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/book/view.vue?vue&type=style&index=0&lang=css&":
/*!*******************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/style-loader!./node_modules/css-loader??ref--6-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--6-2!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/components/book/view.vue?vue&type=style&index=0&lang=css& ***!
\*******************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var content = __webpack_require__(/*! !../../../../node_modules/css-loader??ref--6-1!../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../node_modules/postcss-loader/src??ref--6-2!../../../../node_modules/vue-loader/lib??vue-loader-options!./view.vue?vue&type=style&index=0&lang=css& */ "./node_modules/css-loader/index.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/book/view.vue?vue&type=style&index=0&lang=css&");
if(typeof content === 'string') content = [[module.i, content, '']];
var transform;
var insertInto;
var options = {"hmr":true}
options.transform = transform
options.insertInto = undefined;
var update = __webpack_require__(/*! ../../../../node_modules/style-loader/lib/addStyles.js */ "./node_modules/style-loader/lib/addStyles.js")(content, options);
if(content.locals) module.exports = content.locals;
if(false) {}
/***/ }),
/***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/Table/Grid.vue?vue&type=template&id=92c5d39c&":
/*!*************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/components/Table/Grid.vue?vue&type=template&id=92c5d39c& ***!
\*************************************************************************************************************************************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; });
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c(
"div",
[
_c(
"el-row",
[
_vm.onCreateName
? _c(
"el-col",
{ attrs: { span: 6 } },
[
_c(
"el-button",
{
attrs: { type: "primary" },
on: {
click: function($event) {
_vm.$router.push({ name: _vm.onCreateName })
}
}
},
[_vm._v(_vm._s(_vm.createName))]
)
],
1
)
: _vm._e()
],
1
),
_vm._v(" "),
_c(
"el-table",
{
directives: [
{
name: "loading",
rawName: "v-loading",
value: _vm.loading,
expression: "loading"
}
],
staticStyle: { width: "100%" },
attrs: { data: _vm.data.data },
on: { "sort-change": _vm.handleSortChange }
},
[
_vm._t("default"),
_vm._v(" "),
_vm._l(_vm.columns, function(column, index, key) {
return _c("el-table-column", {
key: index + "-" + key + "-" + column.prop + "-" + column.label,
attrs: {
sortable: column.sort ? true : false,
label: column.label,
prop: column.prop
}
})
}),
_vm._v(" "),
_c("el-table-column", {
attrs: { align: "right" },
scopedSlots: _vm._u([
{
key: "header",
fn: function(scope) {
return [
_c("el-input", {
attrs: { size: "mini", placeholder: "Type to search" },
on: { input: _vm.search_ },
model: {
value: _vm.search,
callback: function($$v) {
_vm.search = $$v
},
expression: "search"
}
})
]
}
},
{
key: "default",
fn: function(scope) {
return [
_c(
"el-button",
{
attrs: { size: "mini" },
on: {
click: function($event) {
_vm.handleEdit(scope.$index, scope.row)
}
}
},
[_vm._v("Edit\n ")]
),
_vm._v(" "),
_c(
"el-button",
{
attrs: { size: "mini", type: "danger" },
on: {
click: function($event) {
_vm.handleDelete(scope.$index, scope.row)
}
}
},
[_vm._v("Delete\n ")]
)
]
}
}
])
})
],
2
),
_vm._v(" "),
_c("el-pagination", {
attrs: {
"current-page": _vm.data.current_page,
"page-size": _vm.data.per_page,
layout: "total, prev, pager, next, jumper",
total: _vm.data.total
},
on: { "current-change": _vm.handleCurrentChange }
})
],
1
)
}
var staticRenderFns = []
render._withStripped = true
/***/ }),
/***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/book/view.vue?vue&type=template&id=68039260&":
/*!************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/components/book/view.vue?vue&type=template&id=68039260& ***!
\************************************************************************************************************************************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; });
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c(
"div",
[
_c("grid-view", {
attrs: {
columns: _vm.columns,
data: _vm.data,
"create-name": "Add Book",
"on-delete": "/api/books",
"on-edit-name": "edit-book",
"on-create-name": "create-book"
},
on: {
delete: function($event) {
_vm.data.data.splice($event, 1)
}
}
})
],
1
)
}
var staticRenderFns = []
render._withStripped = true
/***/ }),
/***/ "./resources/js/components/Table/Grid.vue":
/*!************************************************!*\
!*** ./resources/js/components/Table/Grid.vue ***!
\************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Grid_vue_vue_type_template_id_92c5d39c___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Grid.vue?vue&type=template&id=92c5d39c& */ "./resources/js/components/Table/Grid.vue?vue&type=template&id=92c5d39c&");
/* harmony import */ var _Grid_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Grid.vue?vue&type=script&lang=js& */ "./resources/js/components/Table/Grid.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport *//* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js");
/* normalize component */
var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__["default"])(
_Grid_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"],
_Grid_vue_vue_type_template_id_92c5d39c___WEBPACK_IMPORTED_MODULE_0__["render"],
_Grid_vue_vue_type_template_id_92c5d39c___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"],
false,
null,
null,
null
)
/* hot reload */
if (false) { var api; }
component.options.__file = "resources/js/components/Table/Grid.vue"
/* harmony default export */ __webpack_exports__["default"] = (component.exports);
/***/ }),
/***/ "./resources/js/components/Table/Grid.vue?vue&type=script&lang=js&":
/*!*************************************************************************!*\
!*** ./resources/js/components/Table/Grid.vue?vue&type=script&lang=js& ***!
\*************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Grid_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/babel-loader/lib??ref--4-0!../../../../node_modules/vue-loader/lib??vue-loader-options!./Grid.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/Table/Grid.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__["default"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Grid_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]);
/***/ }),
/***/ "./resources/js/components/Table/Grid.vue?vue&type=template&id=92c5d39c&":
/*!*******************************************************************************!*\
!*** ./resources/js/components/Table/Grid.vue?vue&type=template&id=92c5d39c& ***!
\*******************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Grid_vue_vue_type_template_id_92c5d39c___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../node_modules/vue-loader/lib??vue-loader-options!./Grid.vue?vue&type=template&id=92c5d39c& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/Table/Grid.vue?vue&type=template&id=92c5d39c&");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Grid_vue_vue_type_template_id_92c5d39c___WEBPACK_IMPORTED_MODULE_0__["render"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Grid_vue_vue_type_template_id_92c5d39c___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; });
/***/ }),
/***/ "./resources/js/components/book/view.vue":
/*!***********************************************!*\
!*** ./resources/js/components/book/view.vue ***!
\***********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _view_vue_vue_type_template_id_68039260___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./view.vue?vue&type=template&id=68039260& */ "./resources/js/components/book/view.vue?vue&type=template&id=68039260&");
/* harmony import */ var _view_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./view.vue?vue&type=script&lang=js& */ "./resources/js/components/book/view.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport *//* harmony import */ var _view_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./view.vue?vue&type=style&index=0&lang=css& */ "./resources/js/components/book/view.vue?vue&type=style&index=0&lang=css&");
/* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js");
/* normalize component */
var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__["default"])(
_view_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"],
_view_vue_vue_type_template_id_68039260___WEBPACK_IMPORTED_MODULE_0__["render"],
_view_vue_vue_type_template_id_68039260___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"],
false,
null,
null,
null
)
/* hot reload */
if (false) { var api; }
component.options.__file = "resources/js/components/book/view.vue"
/* harmony default export */ __webpack_exports__["default"] = (component.exports);
/***/ }),
/***/ "./resources/js/components/book/view.vue?vue&type=script&lang=js&":
/*!************************************************************************!*\
!*** ./resources/js/components/book/view.vue?vue&type=script&lang=js& ***!
\************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_view_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/babel-loader/lib??ref--4-0!../../../../node_modules/vue-loader/lib??vue-loader-options!./view.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/book/view.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__["default"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_view_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]);
/***/ }),
/***/ "./resources/js/components/book/view.vue?vue&type=style&index=0&lang=css&":
/*!********************************************************************************!*\
!*** ./resources/js/components/book/view.vue?vue&type=style&index=0&lang=css& ***!
\********************************************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_index_js_ref_6_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_vue_loader_lib_index_js_vue_loader_options_view_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/style-loader!../../../../node_modules/css-loader??ref--6-1!../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../node_modules/postcss-loader/src??ref--6-2!../../../../node_modules/vue-loader/lib??vue-loader-options!./view.vue?vue&type=style&index=0&lang=css& */ "./node_modules/style-loader/index.js!./node_modules/css-loader/index.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/book/view.vue?vue&type=style&index=0&lang=css&");
/* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_index_js_ref_6_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_vue_loader_lib_index_js_vue_loader_options_view_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_index_js_node_modules_css_loader_index_js_ref_6_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_vue_loader_lib_index_js_vue_loader_options_view_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _node_modules_style_loader_index_js_node_modules_css_loader_index_js_ref_6_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_vue_loader_lib_index_js_vue_loader_options_view_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _node_modules_style_loader_index_js_node_modules_css_loader_index_js_ref_6_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_vue_loader_lib_index_js_vue_loader_options_view_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony default export */ __webpack_exports__["default"] = (_node_modules_style_loader_index_js_node_modules_css_loader_index_js_ref_6_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_vue_loader_lib_index_js_vue_loader_options_view_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0___default.a);
/***/ }),
/***/ "./resources/js/components/book/view.vue?vue&type=template&id=68039260&":
/*!******************************************************************************!*\
!*** ./resources/js/components/book/view.vue?vue&type=template&id=68039260& ***!
\******************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_view_vue_vue_type_template_id_68039260___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../node_modules/vue-loader/lib??vue-loader-options!./view.vue?vue&type=template&id=68039260& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/book/view.vue?vue&type=template&id=68039260&");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_view_vue_vue_type_template_id_68039260___WEBPACK_IMPORTED_MODULE_0__["render"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_view_vue_vue_type_template_id_68039260___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; });
/***/ })
}]); | 45.885671 | 963 | 0.582605 |
3d985bed8cff233449d9a4ec0367a7c0df8596ce | 726 | js | JavaScript | node_modules/@fluentui/react-icons/lib/cjs/components/ArrowUpLeft20Filled.js | paige-ingram/nwhacks2022 | ea35bfaa8fb6eb8109db8ed357a097474f3bfd1d | [
"Apache-2.0"
] | null | null | null | node_modules/@fluentui/react-icons/lib/cjs/components/ArrowUpLeft20Filled.js | paige-ingram/nwhacks2022 | ea35bfaa8fb6eb8109db8ed357a097474f3bfd1d | [
"Apache-2.0"
] | null | null | null | node_modules/@fluentui/react-icons/lib/cjs/components/ArrowUpLeft20Filled.js | paige-ingram/nwhacks2022 | ea35bfaa8fb6eb8109db8ed357a097474f3bfd1d | [
"Apache-2.0"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const React = require("react");
const wrapIcon_1 = require("../utils/wrapIcon");
const rawSvg = (iconProps) => {
const { className, primaryFill } = iconProps;
return React.createElement("svg", { width: 20, height: 20, viewBox: "0 0 20 20", xmlns: "http://www.w3.org/2000/svg", className: className },
React.createElement("path", { d: "M12 3.75a.75.75 0 00-.75-.75h-7.5a.75.75 0 00-.75.75v7.5a.75.75 0 001.5 0V5.56l11.22 11.22a.75.75 0 001.06-1.06L5.56 4.5h5.69c.41 0 .75-.34.75-.75z", fill: primaryFill }));
};
const ArrowUpLeft20Filled = wrapIcon_1.default(rawSvg({}), 'ArrowUpLeft20Filled');
exports.default = ArrowUpLeft20Filled;
| 60.5 | 214 | 0.684573 |
3d986ea29c1e41de9c7afba285039ba4f2fef91a | 1,846 | js | JavaScript | github-profiles-app/main.js | KaicPierre/JavaScript-Exercises | ae1704b4dad348e95804555b78ab6f23285fb1eb | [
"MIT"
] | 1 | 2020-10-23T16:40:05.000Z | 2020-10-23T16:40:05.000Z | github-profiles-app/main.js | KaicPierre/Ex-JavaScript | ae1704b4dad348e95804555b78ab6f23285fb1eb | [
"MIT"
] | null | null | null | github-profiles-app/main.js | KaicPierre/Ex-JavaScript | ae1704b4dad348e95804555b78ab6f23285fb1eb | [
"MIT"
] | null | null | null |
const APIURL = "https://api.github.com/users/"
const main = document.getElementById("main")
const form = document.getElementById("form")
const search = document.getElementById("search")
async function getUser(username){
const resp = await fetch(APIURL + username)
const respData = await resp.json()
createUserCard(respData)
getRepos(username)
}
async function getRepos(username){
const resp = await fetch(APIURL + username + "/repos")
const respData = await resp.json()
addReposToCard(respData)
}
function createUserCard(user){
const card = document.createElement('div')
card.classList.add('card')
const cardHTML = `
<div class="card">
<div>
<img class="avatar" src="${user.avatar_url}" alt="${user.name}"/>
</div>
<div class="user-info">
<h2>${user.name}</h2>
<p>${user.bio}</p>
<ul class="info">
<li>${user.followers}<strong>Followers</strong></li>
<li>${user.following}<strong>Following</following></li>
<li>${user.public_repos}<strong>Repos</strong></li>
</ul>
<div id="repos"></div>
</div>
</div>
`;
main.innerHTML = cardHTML
}
function addReposToCard (repos){
const reposEl = document.getElementById('repos')
repos.sort((a, b) => b.stargazers_count - a.stargazers_count).slice(0,10).forEach(repo => {
const repoEl = document.createElement('a')
repoEl.classList.add('repo')
repoEl.href = repo.html_url
repoEl.target= "_blank"
repoEl.innerText = repo.name
reposEl.appendChild(repoEl)
})
}
form.addEventListener('submit', e => {
e.preventDefault()
const user = search.value
if(user){
getUser(user)
search.value = ""
}
}) | 23.666667 | 95 | 0.596966 |
3d991187e616ada1b26a6ddf930fac0be8a8b960 | 8,977 | js | JavaScript | node_modules/oae-core/preferences/js/preferences.js | simong/3akai-ux | 8dc63bcc9f693f6695d6575381ab73d8cd147c8f | [
"ECL-2.0"
] | 25 | 2015-01-01T17:49:18.000Z | 2022-02-05T23:25:50.000Z | node_modules/oae-core/preferences/js/preferences.js | simong/3akai-ux | 8dc63bcc9f693f6695d6575381ab73d8cd147c8f | [
"ECL-2.0"
] | 257 | 2015-01-02T14:22:02.000Z | 2021-12-15T16:18:27.000Z | node_modules/oae-core/preferences/js/preferences.js | simong/3akai-ux | 8dc63bcc9f693f6695d6575381ab73d8cd147c8f | [
"ECL-2.0"
] | 35 | 2015-01-01T17:49:48.000Z | 2022-02-02T11:59:10.000Z | /*!
* Copyright 2014 Apereo Foundation (AF) Licensed under the
* Educational Community 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://opensource.org/licenses/ECL-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.
*/
define(['jquery', 'oae.core'], function($, oae) {
return function(uid, showSettings) {
// The widget container
$rootel = $('#' + uid);
/**
* Reset the widget to its original state when the modal is closed
*/
var reset = function() {
// Reset all the forms
$('form', $rootel).each(function(i, form) {
// Reset the form
form.reset();
// Clear the validation messages from the form
oae.api.util.validation().clear(form);
});
// Deactivate all the tabs and tab panels
$('#preferences-tab-container ul li', $rootel).removeClass('active');
$('form', $rootel).removeClass('active');
// Activate the first tab and its corresponding panel
$('#preferences-tab-account', $rootel).addClass('active');
$('#preferences-account', $rootel).addClass('active');
};
/**
* Change the password of the currently authenticated user
*/
var changePassword = function() {
var oldPassword = $('#preferences-current-password', $rootel).val();
var newPassword = $('#preferences-new-password', $rootel).val();
oae.api.authentication.changePassword(oldPassword, newPassword, function(err) {
if (err) {
if (err.code === 400) {
// The user has a non-local account
oae.api.util.notification(
oae.api.i18n.translate('__MSG__PASSWORD_NOT_UPDATED__'),
oae.api.i18n.translate('__MSG__YOUR_PASSWORD_CANNOT_BE_CHANGED_HERE__', 'preferences'),
'error'
);
} else if (err.code === 401) {
// The provided current password is incorrect
oae.api.util.notification(
oae.api.i18n.translate('__MSG__PASSWORD_NOT_UPDATED__'),
oae.api.i18n.translate('__MSG__THE_PROVIDED_PASSWORD_IS_INCORRECT__', 'preferences'),
'error'
);
} else {
// Show a generic failure notification
oae.api.util.notification(
oae.api.i18n.translate('__MSG__PASSWORD_NOT_UPDATED__'),
oae.api.i18n.translate('__MSG__YOUR_PASSWORD_UPDATE_FAILED__', 'preferences'),
'error'
);
}
} else {
// Hide the modal after saving
$('#preferences-modal', $rootel).modal('hide');
// Show a success notification
oae.api.util.notification(
oae.api.i18n.translate('__MSG__PASSWORD_UPDATED__', 'preferences'),
oae.api.i18n.translate('__MSG__YOUR_PASSWORD_SUCCESSFULLY_UPDATED__', 'preferences')
);
}
});
// Avoid default form submit behavior
return false;
};
/**
* Update the email and locale preferences
*/
var updatePreferences = function() {
var profile = {
'locale': $('#preferences-language', $rootel).val(),
'emailPreference': $('.oae-large-options-container input[type="radio"]:checked', $rootel).val()
};
oae.api.user.updateUser(profile, function(err) {
if (err) {
// Show a failure notification
oae.api.util.notification(
oae.api.i18n.translate('__MSG__PREFERENCES_NOT_UPDATED__', 'preferences'),
oae.api.i18n.translate('__MSG__YOUR_PREFERENCES_UPDATE_FAILED__', 'preferences'),
'error'
);
} else {
// Hide the modal after saving
$('#preferences-modal', $rootel).modal('hide');
// Show a success notification
oae.api.util.notification(
oae.api.i18n.translate('__MSG__PREFERENCES_UPDATED__', 'preferences'),
oae.api.i18n.translate('__MSG__YOUR_PREFERENCES_SUCCESSFULLY_UPDATED__', 'preferences')
);
// Cache the email preference
oae.data.me.emailPreference = profile.emailPreference;
// Reload the page if the language has been changed
if (profile.locale !== oae.data.me.locale) {
setTimeout(function() {
document.location.reload();
}, 2000);
}
}
});
// Return false to avoid default form submit behavior
return false;
};
/**
* Set up validation for the `change password` form. This will validate and submit the form or
* show an error message when appropriate.
*/
setUpPasswordValidation = function() {
oae.api.util.validation().validate($('#preferences-password', $rootel), {
'rules': {
'preferences-new-password': {
'minlength': 6
},
'preferences-retype-password': {
'equalTo': '#preferences-new-password'
}
},
'messages': {
'preferences-new-password': {
'required': oae.api.i18n.translate('__MSG__PLEASE_ENTER_YOUR_PASSWORD__'),
'minlength': oae.api.i18n.translate('__MSG__YOUR_PASSWORD_SHOULD_BE_AT_LEAST_SIX_CHARACTERS_LONG__')
},
'preferences-retype-password': {
'required': oae.api.i18n.translate('__MSG__PLEASE_REPEAT_YOUR_PASSWORD__'),
'passwordmatch': oae.api.i18n.translate('__MSG__THIS_PASSWORD_DOES_NOT_MATCH_THE_FIRST_ONE__')
}
},
'submitHandler': changePassword
});
};
/**
* Render the email preferences and the list of available languages.
* The i18n debug language will only be shown to administrators.
*/
var setUpPreferences = function() {
// Render the available languages
oae.api.util.template().render($('#preferences-language-template', $rootel), null, $('#preferences-language', $rootel));
// Render the email preferences
oae.api.util.template().render($('#preferences-email-template', $rootel), null, $('#preferences-email-container', $rootel));
};
/**
* Set up the preferences modal
*/
var setUpPreferencesModal = function() {
// Only show the password tab if the user logged in with the local authentication strategy
if (oae.data.me.authenticationStrategy === 'local') {
$('#preferences-tab-container', $rootel).show();
}
$(document).on('oae.trigger.preferences', function() {
$('#preferences-modal', $rootel).modal({
'backdrop': 'static'
});
setUpPreferences();
});
$(document).on('click', '.oae-trigger-preferences', function() {
$('#preferences-modal', $rootel).modal({
'backdrop': 'static'
});
setUpPreferences();
});
$('#preferences-modal', $rootel).on('hidden.bs.modal', reset);
$rootel.on('change', '.oae-large-options-container input[type="radio"]', function() {
$('.oae-large-options-container label', $rootel).removeClass('checked');
$(this).parents('label').addClass('checked');
});
$rootel.on('submit', '#preferences-account', updatePreferences);
};
setUpPasswordValidation();
setUpPreferencesModal();
};
});
| 42.34434 | 136 | 0.51476 |
3d99359c9b9a724a153eea0669bf774747a4d698 | 9,128 | js | JavaScript | src/index.js | sergiirocks/babel-plugin-transform-ui5 | 9d8da06f477b1a3deb317b4963b3fa949cc95881 | [
"MIT"
] | 2 | 2017-08-29T14:59:15.000Z | 2019-01-25T13:08:43.000Z | src/index.js | enyancc/babel-plugin-transform-ui5 | 9d8da06f477b1a3deb317b4963b3fa949cc95881 | [
"MIT"
] | null | null | null | src/index.js | enyancc/babel-plugin-transform-ui5 | 9d8da06f477b1a3deb317b4963b3fa949cc95881 | [
"MIT"
] | 1 | 2017-10-03T14:22:45.000Z | 2017-10-03T14:22:45.000Z | import template from 'babel-template';
import Path from 'path';
const buildDefine = template(`
VARS;
sap.ui.define(MODULE_NAME, [SOURCES], FACTORY);
`);
const buildFactory = template(`
(function (PARAMS) {
BODY;
})
`);
exports.default = function({ types: t }) {
const ui5ModuleVisitor = {
Program: {
enter: (path, state) => {
const filePath = Path.resolve(path.hub.file.opts.filename);
const sourceRootPath = getSourceRoot(path);
let relativeFilePath = null;
let relativeFilePathWithoutExtension = null;
let namespace = null;
if (filePath.startsWith(sourceRootPath)) {
relativeFilePath = Path.relative(sourceRootPath, filePath);
relativeFilePathWithoutExtension =
Path.dirname(relativeFilePath) + Path.sep + Path.basename(relativeFilePath, Path.extname(relativeFilePath));
relativeFilePathWithoutExtension = relativeFilePathWithoutExtension.replace(/\\/g, '/');
const parts = relativeFilePath.split(Path.sep);
if (parts.length <= 1) {
namespace = relativeFilePath;
} else {
parts.pop();
namespace = parts.join('.');
}
}
if (!path.state) {
path.state = {};
}
path.state.ui5 = {
filePath,
relativeFilePath,
relativeFilePathWithoutExtension,
namespace,
className: null,
fullClassName: null,
superClassName: null,
imports: [],
staticMembers: [],
returnValue: false
};
},
exit(path) {
const state = path.state.ui5;
const hasUi5 = state.returnValue || state.imports.length;
if (hasUi5) {
const { node } = path;
const factoryBody = state.imports.map(i => {
if (i.isLib) {
i.path.remove();
}
return t.assignmentExpression('=', t.identifier(i.name), i.tmpName);
});
if (state.returnValue) {
factoryBody.push(t.returnStatement(state.returnValue));
}
const factory = buildFactory({
PARAMS: state.imports.map(i => i.tmpName),
BODY: factoryBody
});
let factoryInsertIndex = 0;
for (let i = 0, target = node.body; i < target.length; i++) {
if (target[i].type !== 'ImportDeclaration') {
factoryInsertIndex = i + 1;
break;
}
}
const define = buildDefine({
VARS: state.imports
.map(i => t.identifier(i.name))
.map(i => t.variableDeclaration('var', [t.variableDeclarator(i)])),
MODULE_NAME: t.stringLiteral(state.relativeFilePathWithoutExtension),
SOURCES: state.imports.map(i => t.stringLiteral(i.src)),
FACTORY: factory
});
node.body.splice(factoryInsertIndex, 0, ...define);
}
}
},
ImportDeclaration: (path, { opts }) => {
const state = path.state.ui5;
const node = path.node;
const sourceRootPath = getSourceRoot(path);
let name = null;
let srcRaw = node.source.value;
let srcPath = null;
if (srcRaw.startsWith('./') || srcRaw.startsWith('../')) {
srcPath = Path.normalize(Path.resolve(Path.dirname(state.filePath), srcRaw));
srcRaw = Path.relative(sourceRootPath, srcPath);
}
const srcNormalized = Path.normalize(srcRaw);
const src = srcNormalized.replace(/\\/g, '/');
if (node.specifiers && node.specifiers.length === 1) {
name = node.specifiers[0].local.name;
} else {
const parts = srcNormalized.split(Path.sep);
name = parts[parts.length - 1];
}
if (node.leadingComments) {
state.leadingComments = node.leadingComments;
}
const testLibs = opts.libs || ['^sap/'];
const isLibRE = testLibs.length && new RegExp(`(${testLibs.join('|')})`);
const isLib = isLibRE.test(src);
const testSrc = (opts.libs || ['^sap/']).concat(opts.files || []);
const isUi5SrcRE = testSrc.length && new RegExp(`(${testSrc.join('|')})`);
const isUi5Src = isUi5SrcRE.test(src);
if (isLib || isUi5Src) {
const tmpName = path.scope.generateUidIdentifierBasedOnNode(t.identifier(name));
const imp = {
path,
name,
tmpName,
isLib,
isUi5Src,
src
};
state.imports.push(imp);
}
},
ExportDeclaration: path => {
const state = path.state.ui5;
if (!path.node.declaration) {
return;
}
const id = path.node.declaration.id;
const leadingComments = path.node.leadingComments;
if (path.node.declaration.type === 'ClassDeclaration') {
state.returnValue = transformClass(path.node.declaration, state);
path.remove();
}
return;
const defineCallArgs = [
t.stringLiteral(state.relativeFilePathWithoutExtension),
t.arrayExpression(state.imports.map(i => t.stringLiteral(i.src))),
t.functionExpression(
null,
state.imports.map(i => t.identifier(i.name)),
t.blockStatement([
t.expressionStatement(t.stringLiteral('use strict')),
t.returnStatement(transformClass(path.node.declaration, program, state))
])
)
];
const defineCall = t.callExpression(t.identifier('sap.ui.define'), defineCallArgs);
if (state.leadingComments) {
defineCall.leadingComments = state.leadingComments;
}
path.replaceWith(defineCall);
// Add static members
for (let key in state.staticMembers) {
const id = t.identifier(state.fullClassName + '.' + key);
const statement = t.expressionStatement(t.assignmentExpression('=', id, state.staticMembers[key]));
path.insertAfter(statement);
}
},
CallExpression(path) {
const state = path.state.ui5;
const node = path.node;
if (node.callee.type === 'Super') {
if (!state.superClassName) {
this.errorWithNode("The keyword 'super' can only used in a derrived class.");
}
const identifier = t.identifier(state.superClassName + '.apply');
let args = t.arrayExpression(node.arguments);
if (
node.arguments.length === 1 &&
node.arguments[0].type === 'Identifier' &&
node.arguments[0].name === 'arguments'
) {
args = t.identifier('arguments');
}
path.replaceWith(t.callExpression(identifier, [t.identifier('this'), args]));
} else if (node.callee.object && node.callee.object.type === 'Super') {
if (!state.superClassName) {
this.errorWithNode("The keyword 'super' can only used in a derrived class.");
}
const identifier = t.identifier(
state.superClassName + '.prototype' + '.' + node.callee.property.name + '.apply'
);
path.replaceWith(t.callExpression(identifier, [t.identifier('this'), t.arrayExpression(node.arguments)]));
}
}
};
function transformClass(node, state) {
if (node.type !== 'ClassDeclaration') {
return node;
} else {
resolveClass(node, state);
const props = [];
node.body.body.forEach(member => {
if (member.type === 'ClassMethod') {
const func = t.functionExpression(null, member.params, member.body);
if (!member.static) {
func.generator = member.generator;
func.async = member.async;
props.push(t.objectProperty(member.key, func));
} else {
func.body.body.unshift(t.expressionStatement(t.stringLiteral('use strict')));
state.staticMembers[member.key.name] = func;
}
} else if (member.type == 'ClassProperty') {
if (!member.static) {
props.push(t.objectProperty(member.key, member.value));
} else {
state.staticMembers[member.key.name] = member.value;
}
}
});
const bodyJSON = t.objectExpression(props);
const extendCallArgs = [t.stringLiteral(state.fullClassName), bodyJSON];
const extendCall = t.callExpression(t.identifier(state.superClassName + '.extend'), extendCallArgs);
return extendCall;
}
}
function resolveClass(node, state) {
state.className = node.id.name;
state.superClassName = node.superClass.name;
if (state.namespace) {
state.fullClassName = state.namespace + '.' + state.className;
} else {
state.fullClassName = state.className;
}
}
function getSourceRoot(path) {
let sourceRootPath = null;
if (path.hub.file.opts.sourceRoot) {
sourceRootPath = Path.resolve(path.hub.file.opts.sourceRoot);
} else {
sourceRootPath = Path.resolve('.' + Path.sep);
}
return sourceRootPath;
}
return {
name: 'transform-ui5',
visitor: ui5ModuleVisitor
};
};
module.exports = exports.default;
| 32.02807 | 120 | 0.580193 |
3d99b85ac2a601514b35c85a0801e100f620fbfd | 338 | js | JavaScript | components/Fruta.js | thiagohenriqueguimaraes/app-conectt-demo | 849ef9c8636d14a20d051db9febe966df0ffe7a7 | [
"CC-BY-3.0",
"Apache-2.0"
] | null | null | null | components/Fruta.js | thiagohenriqueguimaraes/app-conectt-demo | 849ef9c8636d14a20d051db9febe966df0ffe7a7 | [
"CC-BY-3.0",
"Apache-2.0"
] | 3 | 2020-07-18T11:46:32.000Z | 2021-05-08T08:13:58.000Z | components/Fruta.js | thiagohenriqueguimaraes/app-conectt-demo | 849ef9c8636d14a20d051db9febe966df0ffe7a7 | [
"CC-BY-3.0",
"Apache-2.0"
] | null | null | null | import React, { Component } from 'react';
import { Image } from 'react-native';
export default class Fruta extends Component {
render() {
let pic = {
uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'
};
return (
<Image source={pic} style={{width: 193, height: 110}}/>
);
}
}
| 22.533333 | 84 | 0.62426 |
3d99f9899c32c854c73879399d85adcc1ce5261e | 1,292 | js | JavaScript | screens/AddChatScreen.js | pirasanthan-jesugeevegan/dev-mingle | b8c75658e2ecec555d0a427315d4ce981d3363c6 | [
"MIT"
] | null | null | null | screens/AddChatScreen.js | pirasanthan-jesugeevegan/dev-mingle | b8c75658e2ecec555d0a427315d4ce981d3363c6 | [
"MIT"
] | null | null | null | screens/AddChatScreen.js | pirasanthan-jesugeevegan/dev-mingle | b8c75658e2ecec555d0a427315d4ce981d3363c6 | [
"MIT"
] | null | null | null | import React, { useLayoutEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Button, Input } from 'react-native-elements';
import Icon from 'react-native-vector-icons/FontAwesome';
import { db } from '../firebase';
const AddChatScreen = ({ navigation }) => {
const [input, setInput] = useState('');
useLayoutEffect(() => {
navigation.setOptions({
title: 'Add a new chat',
headerBackTitle: 'Chats',
});
}, [navigation]);
const createChat = async () => {
await db
.collection('chats')
.add({
chatName: input,
})
.then(() => {
navigation.goBack();
})
.catch((error) => alert(error));
};
return (
<View style={styles.container}>
<Input
placeholder="Enter a chat name"
value={input}
onChangeText={(text) => setInput(text)}
onSubmitEditing={createChat}
leftIcon={
<Icon name="wechat" type="antdesign" size={24} color="black" />
}
/>
<Button disabled={!input} onPress={createChat} title="Create new chat" />
</View>
);
};
export default AddChatScreen;
const styles = StyleSheet.create({
container: {
backgroundColor: 'white',
padding: 30,
height: '100%',
},
});
| 25.84 | 79 | 0.583591 |
3d9a11860c82eb20e0af39c58df2505e9a9369f9 | 754 | js | JavaScript | ex7.js | guiferrini/test_JS | fc7f39dee67297db733a2625822bed4c7430260e | [
"Apache-2.0"
] | null | null | null | ex7.js | guiferrini/test_JS | fc7f39dee67297db733a2625822bed4c7430260e | [
"Apache-2.0"
] | null | null | null | ex7.js | guiferrini/test_JS | fc7f39dee67297db733a2625822bed4c7430260e | [
"Apache-2.0"
] | null | null | null | /*Crea una función que transforme un String en mayúscula sin usar las funciones de JavaScript, solo con la Tabla ASCII.
LVL 1: Testear con: JavaScript
LVL 2: Testear con: Champiñones
LVL 3: Testear con: Hola Mundo!
LVL 4: Testear con: Murciélagos en València
LVL 5: Sin Ninguna Función
*/
function gerar() {
let palavra = document.getElementById("txt").value;
// teste -> document.getElementById("resp").innerText = palavra;
//for (let c=0; c <= length.palavra; c++) {
var x = palavra.charCodeAt(0); //gera 1° letra em ordem
document.getElementById("resp").innerHTML = "The Unicode value is: " + x;
/*gerar uma palavra em codigo e depois o codigo em maiuscula
String.fromCharCode(65, 66, 67)
toString...*/
} | 31.416667 | 119 | 0.688329 |
3d9a18a38261894085be5f87067393572fd358fa | 2,077 | js | JavaScript | DWZ/js/dwz.contextmenu.js | kewkew1026/dwz | ccf68014eb121a9d2a07b312b1bbddc990913c1c | [
"Apache-2.0"
] | null | null | null | DWZ/js/dwz.contextmenu.js | kewkew1026/dwz | ccf68014eb121a9d2a07b312b1bbddc990913c1c | [
"Apache-2.0"
] | null | null | null | DWZ/js/dwz.contextmenu.js | kewkew1026/dwz | ccf68014eb121a9d2a07b312b1bbddc990913c1c | [
"Apache-2.0"
] | null | null | null | /**
* @author zhanghuihua@msn.com
*/
(function($){
var menu, shadow, hash;
$.fn.extend({
contextMenu: function(id, options){
var op = $.extend({
shadow : true,
bindings:{},
ctrSub:null
}, options
);
if (!menu) {
menu = $('<div id="contextmenu"></div>').appendTo('body').hide();
}
if (!shadow) {
shadow = $('<div id="contextmenuShadow"></div>').appendTo('body').hide();
}
hash = hash || [];
hash.push({
id : id,
shadow: op.shadow,
bindings: op.bindings || {},
ctrSub: op.ctrSub
});
var index = hash.length - 1;
$(this).bind('contextmenu', function(e) {
display(index, this, e, op);
return false;
});
return this;
}
});
function display(index, trigger, e, options) {
var cur = hash[index];
var content = $(DWZ.frag[cur.id]);
// Send the content to the menu
menu.html(content);
$.each(cur.bindings, function(id, func) {
$("[rel='"+id+"']", menu).bind('click', function(e) {
hide();
func($(trigger), $("#"+cur.id));
});
});
var posX = e.pageX;
var posY = e.pageY;
if ($(window).width() < posX + menu.width()) posX -= menu.width();
if ($(window).height() < posY + menu.height()) posY -= menu.height();
menu.css({'left':posX,'top':posY}).show();
if (cur.shadow) shadow.css({width:menu.width(),height:menu.height(),left:posX+3,top:posY+3}).show();
$(document).one('click', hide);
if ($.isFunction(cur.ctrSub)) {cur.ctrSub($(trigger), $("#"+cur.id));}
}
function hide() {
menu.hide();
shadow.hide();
}
})(jQuery);
| 28.452055 | 108 | 0.419355 |
3d9a3740f80aa447b18636b9af55f2df37c0766b | 121 | js | JavaScript | _/Section 4/grunt-project/js/modules/feature.js | paullewallencom/grunt-978-1-7858-8880-9 | 994dcab512348d6da4c126a75640a66362342072 | [
"Apache-2.0"
] | null | null | null | _/Section 4/grunt-project/js/modules/feature.js | paullewallencom/grunt-978-1-7858-8880-9 | 994dcab512348d6da4c126a75640a66362342072 | [
"Apache-2.0"
] | null | null | null | _/Section 4/grunt-project/js/modules/feature.js | paullewallencom/grunt-978-1-7858-8880-9 | 994dcab512348d6da4c126a75640a66362342072 | [
"Apache-2.0"
] | null | null | null | define(function () {
'use strict';
// a simple module
return {
version: '0.1.0'
};
});
| 13.444444 | 25 | 0.429752 |
3d9bdaecc31daafb650fb28b46992c798f171bb5 | 323 | js | JavaScript | lib/defaultWidgets.js | zenflow/apos-my-site | 47d7be4a290cbf8e79d378ff4ae8f5155c2183ac | [
"MIT"
] | null | null | null | lib/defaultWidgets.js | zenflow/apos-my-site | 47d7be4a290cbf8e79d378ff4ae8f5155c2183ac | [
"MIT"
] | null | null | null | lib/defaultWidgets.js | zenflow/apos-my-site | 47d7be4a290cbf8e79d378ff4ae8f5155c2183ac | [
"MIT"
] | null | null | null | function defaultWidgets({ fullWidthWidgets = true } = {}) {
return {
"@apostrophecms/rich-text": {},
"@apostrophecms/image": {},
"@apostrophecms/video": {},
"@apostrophecms/form": {},
container: {},
...(fullWidthWidgets && {
columns: {},
}),
};
}
module.exports = { defaultWidgets };
| 21.533333 | 59 | 0.560372 |
3d9c012648ebb334641dac808a3ce8e6a91de1a1 | 2,289 | js | JavaScript | src/create/index.js | AndreMaz/moleculer-cli | 3d0ba8fd1969cfec62cc9e69b9a3a2b3c74333df | [
"MIT"
] | null | null | null | src/create/index.js | AndreMaz/moleculer-cli | 3d0ba8fd1969cfec62cc9e69b9a3a2b3c74333df | [
"MIT"
] | null | null | null | src/create/index.js | AndreMaz/moleculer-cli | 3d0ba8fd1969cfec62cc9e69b9a3a2b3c74333df | [
"MIT"
] | null | null | null | /*
* moleculer-cli
* Copyright (c) 2018 MoleculerJS (https://github.com/moleculerjs/moleculer-cli)
* MIT Licensed
*/
const fs = require("fs");
const path = require("path");
const inquirer = require("inquirer");
const render = require("consolidate").handlebars.render;
const { fail } = require("../utils");
/**
* Yargs command
*/
module.exports = {
command: "create <module>",
describe: "Create a Moleculer module (service, middleware)",
handler(opts) {
if (opts.module.toLowerCase() == "service")
return addService(opts);
else {
fail("Invalid module type. Available modules: service");
}
}
};
/**
* Service generator
*
* @param {any} opts
* @returns
*/
function addService(opts) {
let values = Object.assign({}, opts);
return Promise.resolve()
.then(() => {
return inquirer.prompt([
{
type: "input",
name: "serviceFolder",
message: "Service directory",
default: "./services",
validate(input) {
if (!fs.existsSync(path.resolve(input)))
return `The '${input}' directory is not exists! Full path: ${path.resolve(input)}`;
return true;
}
},
{
type: "input",
name: "serviceName",
message: "Service name",
default: "test"
}
]).then(answers => {
Object.assign(values, answers);
const newServicePath = path.join(values.serviceFolder, values.serviceName + ".service.js");
values.newServicePath = newServicePath;
if (fs.existsSync(newServicePath)) {
return inquirer.prompt([{
type: "confirm",
name: "sure",
message: "The file is exists! Overwrite?",
default: false
}]).then(({ sure }) => {
if (!sure)
fail("Aborted");
});
}
});
})
.then(() => {
const templatePath = path.join(__dirname, "service.template");
const template = fs.readFileSync(templatePath, "utf8");
return new Promise((resolve, reject) => {
render(template, values, function (err, res) {
if (err)
return reject(err);
const { newServicePath } = values;
console.log(`Create new service file to '${newServicePath}'...`);
fs.writeFileSync(path.resolve(newServicePath), res, "utf8");
resolve();
});
});
})
// Error handler
.catch(err => fail(err));
} | 22.89 | 95 | 0.601573 |
3d9c22b8caa39db2688b75e84dd18b74b686f448 | 2,365 | js | JavaScript | frontend/src/components/UserTable.js | Lekesoldat/BACkup | 196eed818b7693b7cc4cde0507dd5fa2b947a8a2 | [
"MIT"
] | null | null | null | frontend/src/components/UserTable.js | Lekesoldat/BACkup | 196eed818b7693b7cc4cde0507dd5fa2b947a8a2 | [
"MIT"
] | 7 | 2021-03-09T23:13:37.000Z | 2022-02-26T20:15:46.000Z | frontend/src/components/UserTable.js | Lekesoldat/BACkup | 196eed818b7693b7cc4cde0507dd5fa2b947a8a2 | [
"MIT"
] | null | null | null | import React from 'react';
import { navigate } from '@reach/router';
import styled from 'styled-components';
import useRequest from '../hooks/useRequest';
const Table = styled.table`
border: 1px solid black;
border-collapse: collapse;
`;
const Row = styled.tr`
&:hover {
background-color: #e4e4e4;
cursor: pointer;
}
`;
const Th = styled.th`
border: 1px solid black;
padding: 1rem;
`;
const Td = styled.td`
text-align: center;
border: 1px solid black;
padding: 1rem;
`;
// A component for dynamically rendering users.
const UserTable = ({ data }) => {
const { request: startSession } = useRequest({
lazy: true,
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
});
return (
<>
<Table>
<thead>
<tr>
<Th>Name</Th>
<Th>Weight</Th>
<Th>Gender</Th>
<Th>Total Sessions</Th>
<Th>Total Drinks</Th>
<Th>Average</Th>
</tr>
</thead>
<tbody>
{data.map(u => {
return (
<Row
key={u.id}
onClick={async () => {
// Start a new drinking session when selecting the user.
await startSession({
path: `/api/users/${u.id}/session`
});
// Navigate to the tracker when the session is created.
await navigate(`/tracker/${u.id}`);
}}
>
<Td>{u.name}</Td>
<Td>{u.weight}</Td>
<Td>{u.gender}</Td>
<Td>{u.sessions.length}</Td>
<Td>
{u.sessions.reduce(
(prev, curr) => prev + curr.drinks.length,
0
)}
</Td>
<Td>
{!u.sessions.length
? 0
: Math.round(
u.sessions.reduce(
(prev, curr) => prev + curr.drinks.length,
0
) / u.sessions.length
)}
</Td>
</Row>
);
})}
</tbody>
</Table>
</>
);
};
export default UserTable;
| 24.132653 | 74 | 0.42537 |
3d9d2c9268e3f79e39c1279f2119cdb896a9f1cf | 643 | js | JavaScript | app/home/home.js | suneetsasidharan/RG-Blackbird | 78b0fc47a738e3d2e58698aa34e409cb7850a007 | [
"MIT"
] | null | null | null | app/home/home.js | suneetsasidharan/RG-Blackbird | 78b0fc47a738e3d2e58698aa34e409cb7850a007 | [
"MIT"
] | null | null | null | app/home/home.js | suneetsasidharan/RG-Blackbird | 78b0fc47a738e3d2e58698aa34e409cb7850a007 | [
"MIT"
] | null | null | null | 'use strict';
angular.module('myApp.home', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'home/home.html',
controller: 'HomeCtrl'
});
}])
.controller('HomeCtrl', ['$scope', function($scope) {
$scope.triggers = [{id:'trigger1'}];
$scope.addTrigger = function(){
var newItemNo = $scope.triggers.length+1;
$scope.triggers.push({'id':'trigger'+newItemNo});
};
$scope.removeTrigger = function() {
var lastItem = $scope.triggers.length-1;
$scope.triggers.splice(lastItem);
};
}]); | 24.730769 | 61 | 0.580093 |
3d9d7bea446e4f9a0edceed0f38e81c9ecb45ea9 | 2,506 | js | JavaScript | public/prism/prism-apex.min.js | ArmandPhilippot/apcom | 52404177c07a2aab7fc894362fb3060dff2431a0 | [
"MIT"
] | null | null | null | public/prism/prism-apex.min.js | ArmandPhilippot/apcom | 52404177c07a2aab7fc894362fb3060dff2431a0 | [
"MIT"
] | null | null | null | public/prism/prism-apex.min.js | ArmandPhilippot/apcom | 52404177c07a2aab7fc894362fb3060dff2431a0 | [
"MIT"
] | null | null | null | !(function (e) {
var t =
/\b(?:(?:after|before)(?=\s+[a-z])|abstract|activate|and|any|array|as|asc|autonomous|begin|bigdecimal|blob|boolean|break|bulk|by|byte|case|cast|catch|char|class|collect|commit|const|continue|currency|date|datetime|decimal|default|delete|desc|do|double|else|end|enum|exception|exit|export|extends|final|finally|float|for|from|get(?=\s*[{};])|global|goto|group|having|hint|if|implements|import|in|inner|insert|instanceof|int|integer|interface|into|join|like|limit|list|long|loop|map|merge|new|not|null|nulls|number|object|of|on|or|outer|override|package|parallel|pragma|private|protected|public|retrieve|return|rollback|select|set|short|sObject|sort|static|string|super|switch|synchronized|system|testmethod|then|this|throw|time|transaction|transient|trigger|try|undelete|update|upsert|using|virtual|void|webservice|when|where|while|(?:inherited|with|without)\s+sharing)\b/i,
n =
'\\b(?:(?=[a-z_]\\w*\\s*[<\\[])|(?!<keyword>))[A-Z_]\\w*(?:\\s*\\.\\s*[A-Z_]\\w*)*\\b(?:\\s*(?:\\[\\s*\\]|<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>))*'.replace(
/<keyword>/g,
function () {
return t.source;
}
);
function i(e) {
return RegExp(
e.replace(/<CLASS-NAME>/g, function () {
return n;
}),
'i'
);
}
var a = { keyword: t, punctuation: /[()\[\]{};,:.<>]/ };
e.languages.apex = {
comment: e.languages.clike.comment,
string: e.languages.clike.string,
sql: {
pattern: /((?:[=,({:]|\breturn)\s*)\[[^\[\]]*\]/i,
lookbehind: !0,
greedy: !0,
alias: 'language-sql',
inside: e.languages.sql,
},
annotation: { pattern: /@\w+\b/, alias: 'punctuation' },
'class-name': [
{
pattern: i(
'(\\b(?:class|enum|extends|implements|instanceof|interface|new|trigger\\s+\\w+\\s+on)\\s+)<CLASS-NAME>'
),
lookbehind: !0,
inside: a,
},
{
pattern: i('(\\(\\s*)<CLASS-NAME>(?=\\s*\\)\\s*[\\w(])'),
lookbehind: !0,
inside: a,
},
{ pattern: i('<CLASS-NAME>(?=\\s*\\w+\\s*[;=,(){:])'), inside: a },
],
trigger: {
pattern: /(\btrigger\s+)\w+\b/i,
lookbehind: !0,
alias: 'class-name',
},
keyword: t,
function: /\b[a-z_]\w*(?=\s*\()/i,
boolean: /\b(?:false|true)\b/i,
number: /(?:\B\.\d+|\b\d+(?:\.\d+|L)?)\b/i,
operator: /[!=](?:==?)?|\?\.?|&&|\|\||--|\+\+|[-+*/^&|]=?|:|<<?=?|>{1,3}=?/,
punctuation: /[()\[\]{};,.]/,
};
})(Prism);
| 42.474576 | 879 | 0.537111 |
3d9df0bf1e10d88ce4e963ab8aa838b4db5e3e60 | 1,760 | js | JavaScript | src/dom-mutation.js | willlma/hibou-highlighter | c446ba6092c98865b66eb168045e97ffed898bfb | [
"MIT"
] | null | null | null | src/dom-mutation.js | willlma/hibou-highlighter | c446ba6092c98865b66eb168045e97ffed898bfb | [
"MIT"
] | null | null | null | src/dom-mutation.js | willlma/hibou-highlighter | c446ba6092c98865b66eb168045e97ffed898bfb | [
"MIT"
] | null | null | null | //@flow
const affectedElems = new WeakMap();
export function getLocation(textNode: Text) {
const parent = textNode.parentNode || document.body;
let nodeIndex = [].indexOf.call(parent.childNodes, textNode);
const affected = affectedElems.get(parent);
if (!affected) return {
index: nodeIndex,
offset: 0
};
// leaving for...in until I can test
for (let index in affected) {
index *= 1;
let splits = affected[index];
if (index > nodeIndex) break;
if (nodeIndex >= splits.length + index)
nodeIndex -= splits.length;
else if (nodeIndex > index) return {
index: index,
offset: splits[nodeIndex - index - 1]
};
if (index === nodeIndex) {
const len = splits.length;
return {
index: nodeIndex,
offset: len ? splits[len - 1] : 0
};
}
}
/*const index = affected.findIndex((splits, i: number) => {
if (i > nodeIndex) return false;
if (nodeIndex >= splits.length + i) nodeIndex -= splits.length;
if (nodeIndex >= i) return true;
return false;
});
// can this evr happen?
if (nodeIndex > index)*/
return {
index: nodeIndex,
offset: 0
};
}
export function splitText(node: Text, offset: number) {
if (!offset || offset === node.data.length) return node;
const parentNode = { node };
const newNode = node.splitText(offset);
const location: { index: number, offset: number } = getLocation(node);
let affected = affectedElems.get(parentNode);
if (!affected) {
affected = [];
affectedElems.set(parentNode, affected);
}
if (!affected[location.index]) affected[location.index] = [];
affected[location.index].push(location.offset + offset);
affected[location.index].sort((a, b) => a - b);
return newNode;
}
| 29.333333 | 72 | 0.632955 |
3d9e5e77fc3ee980892d39f267db1d0d94849e36 | 139 | js | JavaScript | server/src/utils/logger.js | ziaboby/boilerplates | dd7b0b52b057d492a75148bb866b9dc19c4bd323 | [
"MIT"
] | null | null | null | server/src/utils/logger.js | ziaboby/boilerplates | dd7b0b52b057d492a75148bb866b9dc19c4bd323 | [
"MIT"
] | null | null | null | server/src/utils/logger.js | ziaboby/boilerplates | dd7b0b52b057d492a75148bb866b9dc19c4bd323 | [
"MIT"
] | null | null | null | module.exports = (type, isError, ...props) => {
if (isError) props.unshift('Error')
props.unshift(type)
console.log(...props)
} | 27.8 | 47 | 0.618705 |
3da21a445f2867d8370d5c470c864c2ec4df0ff3 | 7,310 | js | JavaScript | client/js/upload.js | jimdrie/thelounge | aa84e13656d459c52be9705d131373557d542aa9 | [
"MIT"
] | null | null | null | client/js/upload.js | jimdrie/thelounge | aa84e13656d459c52be9705d131373557d542aa9 | [
"MIT"
] | 1 | 2021-09-26T20:05:32.000Z | 2021-09-26T20:07:38.000Z | client/js/upload.js | jimdrie/thelounge | aa84e13656d459c52be9705d131373557d542aa9 | [
"MIT"
] | null | null | null | "use strict";
import {update as updateCursor} from "undate";
import socket from "./socket";
import store from "./store";
class Uploader {
init() {
this.xhr = null;
this.fileQueue = [];
this.tokenKeepAlive = null;
document.addEventListener("dragenter", (e) => this.dragEnter(e));
document.addEventListener("dragover", (e) => this.dragOver(e));
document.addEventListener("dragleave", (e) => this.dragLeave(e));
document.addEventListener("drop", (e) => this.drop(e));
document.addEventListener("paste", (e) => this.paste(e));
socket.on("upload:auth", (token) => this.uploadNextFileInQueue(token));
}
mounted() {
this.overlay = document.getElementById("upload-overlay");
this.uploadProgressbar = document.getElementById("upload-progressbar");
}
dragOver(event) {
// Prevent dragover event completely and do nothing with it
// This stops the browser from trying to guess which cursor to show
event.preventDefault();
}
dragEnter(event) {
event.preventDefault();
// relatedTarget is the target where we entered the drag from
// when dragging from another window, the target is null, otherwise its a DOM element
if (!event.relatedTarget && event.dataTransfer.types.includes("Files")) {
this.overlay.classList.add("is-dragover");
}
}
dragLeave(event) {
event.preventDefault();
// If relatedTarget is null, that means we are no longer dragging over the page
if (!event.relatedTarget) {
this.overlay.classList.remove("is-dragover");
}
}
drop(event) {
event.preventDefault();
this.overlay.classList.remove("is-dragover");
let files;
if (event.dataTransfer.items) {
files = Array.from(event.dataTransfer.items)
.filter((item) => item.kind === "file")
.map((item) => item.getAsFile());
} else {
files = Array.from(event.dataTransfer.files);
}
this.triggerUpload(files);
}
paste(event) {
const items = event.clipboardData.items;
const files = [];
for (const item of items) {
if (item.kind === "file") {
files.push(item.getAsFile());
}
}
if (files.length === 0) {
return;
}
event.preventDefault();
this.triggerUpload(files);
}
triggerUpload(files) {
if (!files.length) {
return;
}
if (!store.state.isConnected) {
this.handleResponse({
error: `You are currently disconnected, unable to initiate upload process.`,
});
return;
}
const wasQueueEmpty = this.fileQueue.length === 0;
const maxFileSize = store.state.serverConfiguration.fileUploadMaxFileSize;
for (const file of files) {
if (maxFileSize > 0 && file.size > maxFileSize) {
this.handleResponse({
error: `File ${file.name} is over the maximum allowed size`,
});
continue;
}
this.fileQueue.push(file);
}
// if the queue was empty and we added some files to it, and there currently
// is no upload in process, request a token to start the upload process
if (wasQueueEmpty && this.xhr === null && this.fileQueue.length > 0) {
this.requestToken();
}
}
requestToken() {
socket.emit("upload:auth");
}
setProgress(value) {
this.uploadProgressbar.classList.toggle("upload-progressbar-visible", value > 0);
this.uploadProgressbar.style.width = value + "%";
}
uploadNextFileInQueue(token) {
const file = this.fileQueue.shift();
// Tell the server that we are still upload to this token
// so it does not become invalidated and fail the upload.
// This issue only happens if The Lounge is proxied through other software
// as it may buffer the upload before the upload request will be processed by The Lounge.
this.tokenKeepAlive = setInterval(() => socket.emit("upload:ping", token), 40 * 1000);
if (
store.state.settings.uploadCanvas &&
file.type.startsWith("image/") &&
!file.type.includes("svg") &&
file.type !== "image/gif"
) {
this.renderImage(file, (newFile) => this.performUpload(token, newFile));
} else {
this.performUpload(token, file);
}
}
renderImage(file, callback) {
const fileReader = new FileReader();
fileReader.onabort = () => callback(file);
fileReader.onerror = () => fileReader.abort();
fileReader.onload = () => {
const img = new Image();
img.onerror = () => callback(file);
img.onload = () => {
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
canvas.toBlob((blob) => {
callback(new File([blob], file.name));
}, file.type);
};
img.src = fileReader.result;
};
fileReader.readAsDataURL(file);
}
performUpload(token, file) {
this.xhr = new XMLHttpRequest();
this.xhr.upload.addEventListener(
"progress",
(e) => {
const percent = Math.floor((e.loaded / e.total) * 1000) / 10;
this.setProgress(percent);
},
false
);
this.xhr.onreadystatechange = () => {
if (this.xhr.readyState === XMLHttpRequest.DONE) {
let response;
try {
response = JSON.parse(this.xhr.responseText);
} catch (err) {
// This is just a safe guard and should not happen if server doesn't throw any errors.
// Browsers break the HTTP spec by aborting the request without reading any response data,
// if there is still data to be uploaded. Servers will only error in extreme cases like bad
// authentication or server-side errors.
response = {
error: `Upload aborted: HTTP ${this.xhr.status}`,
};
}
this.handleResponse(response);
this.xhr = null;
// this file was processed, if we still have files in the queue, upload the next one
if (this.fileQueue.length > 0) {
this.requestToken();
}
}
};
const formData = new FormData();
formData.append("file", file);
this.xhr.open("POST", `uploads/new/${token}`);
this.xhr.send(formData);
}
handleResponse(response) {
this.setProgress(0);
if (this.tokenKeepAlive) {
clearInterval(this.tokenKeepAlive);
this.tokenKeepAlive = null;
}
if (response.error) {
store.commit("currentUserVisibleError", response.error);
return;
}
if (response.url) {
this.insertUploadUrl(response.url);
}
}
insertUploadUrl(url) {
const fullURL = new URL(url, location).toString();
const textbox = document.getElementById("input");
const initStart = textbox.selectionStart;
// Get the text before the cursor, and add a space if it's not in the beginning
const headToCursor = initStart > 0 ? textbox.value.substr(0, initStart) + " " : "";
// Get the remaining text after the cursor
const cursorToTail = textbox.value.substr(initStart);
// Construct the value until the point where we want the cursor to be
const textBeforeTail = headToCursor + fullURL + " ";
updateCursor(textbox, textBeforeTail + cursorToTail);
// Set the cursor after the link and a space
textbox.selectionStart = textbox.selectionEnd = textBeforeTail.length;
}
// TODO: This is a temporary hack while Vue porting is finalized
abort() {
this.fileQueue = [];
if (this.xhr) {
this.xhr.abort();
this.xhr = null;
}
}
}
const instance = new Uploader();
export default {
abort: () => instance.abort(),
initialize: () => instance.init(),
mounted: () => instance.mounted(),
triggerUpload: (files) => instance.triggerUpload(files),
};
| 25.739437 | 96 | 0.668399 |
3da3671126bde7713549525980496b698e6e639e | 3,245 | js | JavaScript | src/index/scripts/containers/appContainer.js | Uzwername/order-explorer | 4858d53dca4227c2114936329444b449b5367cf3 | [
"MIT"
] | null | null | null | src/index/scripts/containers/appContainer.js | Uzwername/order-explorer | 4858d53dca4227c2114936329444b449b5367cf3 | [
"MIT"
] | null | null | null | src/index/scripts/containers/appContainer.js | Uzwername/order-explorer | 4858d53dca4227c2114936329444b449b5367cf3 | [
"MIT"
] | null | null | null | import React, {useState, useEffect} from "react";
import { OrdersContainer } from "IndexContainers/ordersContainer";
import { NavigationContainer } from "IndexContainers/navigationContainer";
import { OrderCard } from "IndexComponents/orderCard";
import { OrderDialog } from "IndexComponents/orderDialog";
import { getOrders } from "./../helpers/getOrders.js";
export const AppContainer = () => {
useEffect(() => {
/**
* Fetches (possibly new) orders
* each minute
*/
const interval = setInterval(
() => {
setOrders(
getOrders()
);
},
60000
);
return () => clearInterval(interval);
}, []);
// All possible orders
const [orders, setOrders] = useState( getOrders() );
/**
* Possible modes:
* 0: All Orders Tab
* 1: Stage View
* 2: Global Search Mode
*/
const [navMode, setNavMode] = React.useState(0);
// Modal state (modal is used insted of pages for the sake of easiness)
const [orderOpened, setOrderOpened] = React.useState({});
const handleOrderClose = () => {
// Deletes pseudo-id
history.replaceState(null, null, ` `);
setOrderOpened({});
};
const openOrderModal = e => {
const orderData = JSON.parse(
e.currentTarget.getAttribute(`data-order`)
);
// Adds pseudo-id to href to make page address differ.
window.location.href += `#orderID=${orderData.OrderID}`;
setOrderOpened( orderData );
};
/**
* Constructs object with
* all the same data +
* its visualisation.
*
* There is an option to
* assign prop directly on
* "orders", but this
* is not reccomended.
*/
const allOrders = orders.map(
e => {
// Clones e
let record = {...e};
// Adds visaulisation
record.View = (
<OrderCard
key = { e.OrderID }
order = { e }
handleClick = { openOrderModal }
/>
);
return record;
}
);
/**
* Returns all necessary
* visualisations.
*/
const [ordersToShow, setOrdersToShow] = useState(
allOrders.map( e => e.View )
);
/**
* Makes it easy to filter and/or
* sort records & update them
* with filtered and/or sorted
* results.
*/
const arrangeOrders = (filterFn, sortFn) => {
/**
* If none is function, returns.
*/
if (
typeof sortFn !== `function` &&
typeof filterFn !== `function`
) return;
/**
* To avoid undefined
* errors.
*/
let filteredOrders;
let sortedOrders;
/**
* Filters all orders
* if filterFn is present.
* Filtering is previous
* to sorting in order to
* possibly reduce time
* complexity.
*/
if ( filterFn ) {
filteredOrders = allOrders
.filter(
filterFn
);
}
/**
* Sorts either previously
* filteredOrders or all
* orders if filterFn was
* not provided.
*/
if ( sortFn ) {
sortedOrders = (filteredOrders || allOrders)
.sort(
sortFn
);
}
setOrdersToShow(
(sortedOrders || filteredOrders).map(
e => e.View
)
);
};
return (
<>
<NavigationContainer
handleShuffle = { arrangeOrders }
navMode = { navMode }
setNavMode = { setNavMode }
/>
<OrdersContainer
modality = { navMode }
>
{ ordersToShow }
</OrdersContainer>
<OrderDialog
order = { orderOpened }
handleClose = { handleOrderClose }
/>
</>
);
};
| 17.73224 | 74 | 0.619414 |
3da40b99be5da808d4743644eb2cdc7dbf27fab1 | 3,238 | js | JavaScript | dist/components/loading.component.js | magnolo/angular-tree-component | 9cfee4d1377a6f214403424716f434a0c75c5983 | [
"MIT"
] | null | null | null | dist/components/loading.component.js | magnolo/angular-tree-component | 9cfee4d1377a6f214403424716f434a0c75c5983 | [
"MIT"
] | null | null | null | dist/components/loading.component.js | magnolo/angular-tree-component | 9cfee4d1377a6f214403424716f434a0c75c5983 | [
"MIT"
] | null | null | null | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component, Input, TemplateRef, ViewEncapsulation } from '@angular/core';
import { TreeNode } from '../models/tree-node.model';
var LoadingComponent = /** @class */ (function () {
function LoadingComponent() {
}
__decorate([
Input(),
__metadata("design:type", TemplateRef)
], LoadingComponent.prototype, "template", void 0);
__decorate([
Input(),
__metadata("design:type", TreeNode)
], LoadingComponent.prototype, "node", void 0);
LoadingComponent = __decorate([
Component({
encapsulation: ViewEncapsulation.None,
selector: 'tree-loading-component',
template: "\n <span *ngIf=\"!template\">loading...</span>\n <ng-container\n [ngTemplateOutlet]=\"template\"\n [ngTemplateOutletContext]=\"{ $implicit: node }\">\n </ng-container>\n ",
})
], LoadingComponent);
return LoadingComponent;
}());
export { LoadingComponent };
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9hZGluZy5jb21wb25lbnQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9saWIvY29tcG9uZW50cy9sb2FkaW5nLmNvbXBvbmVudC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7QUFBQSxPQUFPLEVBQUUsU0FBUyxFQUFFLEtBQUssRUFBRSxXQUFXLEVBQUUsaUJBQWlCLEVBQUUsTUFBTSxlQUFlLENBQUM7QUFDakYsT0FBTyxFQUFFLFFBQVEsRUFBRSxNQUFNLDJCQUEyQixDQUFDO0FBYXJEO0lBQUE7SUFHQSxDQUFDO0lBRlU7UUFBUixLQUFLLEVBQUU7a0NBQVcsV0FBVztzREFBTTtJQUMzQjtRQUFSLEtBQUssRUFBRTtrQ0FBTyxRQUFRO2tEQUFDO0lBRmIsZ0JBQWdCO1FBWDVCLFNBQVMsQ0FBQztZQUNULGFBQWEsRUFBRSxpQkFBaUIsQ0FBQyxJQUFJO1lBQ3JDLFFBQVEsRUFBRSx3QkFBd0I7WUFDbEMsUUFBUSxFQUFFLGdNQU1UO1NBQ0YsQ0FBQztPQUNXLGdCQUFnQixDQUc1QjtJQUFELHVCQUFDO0NBQUEsQUFIRCxJQUdDO1NBSFksZ0JBQWdCIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHsgQ29tcG9uZW50LCBJbnB1dCwgVGVtcGxhdGVSZWYsIFZpZXdFbmNhcHN1bGF0aW9uIH0gZnJvbSAnQGFuZ3VsYXIvY29yZSc7XG5pbXBvcnQgeyBUcmVlTm9kZSB9IGZyb20gJy4uL21vZGVscy90cmVlLW5vZGUubW9kZWwnO1xuXG5AQ29tcG9uZW50KHtcbiAgZW5jYXBzdWxhdGlvbjogVmlld0VuY2Fwc3VsYXRpb24uTm9uZSxcbiAgc2VsZWN0b3I6ICd0cmVlLWxvYWRpbmctY29tcG9uZW50JyxcbiAgdGVtcGxhdGU6IGBcbiAgICA8c3BhbiAqbmdJZj1cIiF0ZW1wbGF0ZVwiPmxvYWRpbmcuLi48L3NwYW4+XG4gICAgPG5nLWNvbnRhaW5lclxuICAgICAgW25nVGVtcGxhdGVPdXRsZXRdPVwidGVtcGxhdGVcIlxuICAgICAgW25nVGVtcGxhdGVPdXRsZXRDb250ZXh0XT1cInsgJGltcGxpY2l0OiBub2RlIH1cIj5cbiAgICA8L25nLWNvbnRhaW5lcj5cbiAgYCxcbn0pXG5leHBvcnQgY2xhc3MgTG9hZGluZ0NvbXBvbmVudCB7XG4gIEBJbnB1dCgpIHRlbXBsYXRlOiBUZW1wbGF0ZVJlZjxhbnk+O1xuICBASW5wdXQoKSBub2RlOiBUcmVlTm9kZTtcbn1cbiJdfQ== | 98.121212 | 1,522 | 0.793082 |
3da50aa2892d9663736e673971421b4024e4911d | 544 | js | JavaScript | src/App.js | guibperes/vimeo-api | fee47dbd1c3392828b26a3e67debc2ab8834d415 | [
"MIT"
] | null | null | null | src/App.js | guibperes/vimeo-api | fee47dbd1c3392828b26a3e67debc2ab8834d415 | [
"MIT"
] | null | null | null | src/App.js | guibperes/vimeo-api | fee47dbd1c3392828b26a3e67debc2ab8834d415 | [
"MIT"
] | null | null | null | import React, { Component } from 'react'
import { BrowserRouter, Switch, Route } from 'react-router-dom'
import Header from './components/Header'
import Home from './pages/Home'
import Error404 from './pages/Error404'
export default class App extends Component {
render () {
return (
<BrowserRouter>
<div>
<Header />
<Switch>
<Route path='/' exact component={Home} />
<Route path='*' component={Error404} />
</Switch>
</div>
</BrowserRouter>
)
}
}
| 23.652174 | 63 | 0.579044 |
3da7af06f7a0a77f0d6681e02d843393b8082ab8 | 951 | js | JavaScript | lib/helpers/assert.js | joriewong/factory-web | 4e9a1c4eea9a96d56a000d77823606b01589740c | [
"MIT"
] | null | null | null | lib/helpers/assert.js | joriewong/factory-web | 4e9a1c4eea9a96d56a000d77823606b01589740c | [
"MIT"
] | null | null | null | lib/helpers/assert.js | joriewong/factory-web | 4e9a1c4eea9a96d56a000d77823606b01589740c | [
"MIT"
] | null | null | null | "use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertFbiPaths = exports.assertFactoryTemplate = void 0;
const assert_1 = __importDefault(require("assert"));
const assertFactoryTemplate = (factory) => {
const assertFailLog = 'fbi factory.template field must one of "micro-main", "micro-react", "micro-vue", "react", "vue"';
const assertIsOk = factory &&
factory.template &&
['micro-main', 'micro-react', 'micro-vue', 'react', 'vue'].includes(factory.template);
assert_1.default(assertIsOk, assertFailLog);
};
exports.assertFactoryTemplate = assertFactoryTemplate;
const assertFbiPaths = () => {
const assertFailLog = '';
const assertIsOk = true;
assert_1.default(assertIsOk, assertFailLog);
};
exports.assertFbiPaths = assertFbiPaths;
| 43.227273 | 124 | 0.700315 |
3da7d4e514d9c8d8d723eb0b10b720ac3fd40c97 | 526 | js | JavaScript | test/fixtures/test-duration.test.js | sttk/fav-test.console-reporter | ae6b4d33fbec9fdac7bd1e5b10045054f0641000 | [
"MIT"
] | null | null | null | test/fixtures/test-duration.test.js | sttk/fav-test.console-reporter | ae6b4d33fbec9fdac7bd1e5b10045054f0641000 | [
"MIT"
] | null | null | null | test/fixtures/test-duration.test.js | sttk/fav-test.console-reporter | ae6b4d33fbec9fdac7bd1e5b10045054f0641000 | [
"MIT"
] | null | null | null | 'use strict';
describe('durations', function() {
this.slow(10000);
describe('when slow', function() {
it('should highlight in red', function(done) {
this.slow(200);
setTimeout(done, 201);
});
});
describe('when reasonable', function() {
it('should highlight in yellow', function(done) {
this.slow(400);
setTimeout(done, 201);
});
});
describe('when fast', function() {
it('should highlight in green', function(done) {
setTimeout(done, 200);
});
});
});
| 19.481481 | 53 | 0.579848 |
3da901040c626f0e0047e5379693b6f550d4b7f6 | 3,709 | js | JavaScript | bin/update_ons.js | poihierro/postcodes | 48b0451b392fdb89149deaf64adf39eaa52f597d | [
"MIT"
] | null | null | null | bin/update_ons.js | poihierro/postcodes | 48b0451b392fdb89149deaf64adf39eaa52f597d | [
"MIT"
] | null | null | null | bin/update_ons.js | poihierro/postcodes | 48b0451b392fdb89149deaf64adf39eaa52f597d | [
"MIT"
] | null | null | null | #!/usr/bin/env node
console.log("Postcodes.io ONS Postcode Directory Update Script");
var fs = require("fs");
var path = require("path");
var async = require("async");
var start = process.hrtime();
var prompt = require("prompt");
var sourceFile = process.argv[2];
var env = process.env.NODE_ENV || "development";
var Base = require(path.join(__dirname, "../app/models"));
var config = require(path.join(__dirname, "../config/config"))(env);
var Postcode = require(path.join(__dirname, "../app/models/postcode.js"));
var District = require(path.join(__dirname, "../app/models/district.js"));
var Ward = require(path.join(__dirname, "../app/models/ward.js"));
var Nuts = require(path.join(__dirname, "../app/models/nuts.js"));
var County = require(path.join(__dirname, "../app/models/county.js"));
var Parish = require(path.join(__dirname, "../app/models/parish.js"));
var Ccg = require(path.join(__dirname, "../app/models/ccg.js"));
var Outcode = require(path.join(__dirname, "../app/models/outcode.js"));
// Performing checks
Postcode.relation = "postcodes_new";
if (!sourceFile) {
throw new Error("Aborting Import. No source file specified");
}
function dropRelation (callback) {
console.log("Nuking old postcode database...");
Postcode._destroyRelation(callback);
}
function createRelation (callback) {
console.log("Creaing new postcode database as postcodes_new...");
Postcode._createRelation(callback);
}
function recreateIndexes(callback) {
console.log("Rebuilding indexes...");
Postcode.createIndexes(callback);
}
function importRawCsv (callback) {
console.log("Importing CSV data from", sourceFile);
Postcode.seedPostcodes(sourceFile, callback);
}
function populateLocation (callback) {
console.log("Populating location data into postcodes_new...");
Postcode.populateLocation(callback);
}
function setupSupportTables (callback) {
console.log("Setting up support tables...");
var instructions = [
District._setupTable.bind(District),
County._setupTable.bind(County),
Ccg._setupTable.bind(Ccg),
Ward._setupTable.bind(Ward),
Nuts._setupTable.bind(Nuts),
Parish._setupTable.bind(Parish)
];
async.series(instructions, callback);
}
function setupOutcodeTable(callback) {
console.log("Building outcodes table...");
Outcode._setupTable(callback);
}
function createPostgisExtension(callback) {
console.log("Enabling POSTGIS extension...")
Postcode._query("CREATE EXTENSION IF NOT EXISTS postgis", callback);
}
function clearPostcodeArchive(callback) {
console.log("Archiving old postcode table as postcodes_archive");
Postcode._query("DROP TABLE IF EXISTS postcodes_archive CASCADE", callback);
}
function archiveOldPostcodes(callback) {
console.log("Archiving current postcode");
Postcode._query("ALTER TABLE postcodes RENAME TO postcodes_archive", callback);
}
function renameNewPostcodes(callback) {
console.log("Loading in new postcodes table");
Postcode._query("ALTER TABLE postcodes_new RENAME TO postcodes", callback);
}
var executionStack = [dropRelation,
setupSupportTables,
createRelation,
importRawCsv,
populateLocation,
recreateIndexes,
clearPostcodeArchive,
archiveOldPostcodes,
renameNewPostcodes,
setupOutcodeTable];
function startImport () {
async.series(executionStack, function (error, result) {
if (error) {
console.log("Unable to complete import process due to error", error);
console.log("Dropping newly created relation")
process.exit(1);
}
console.log("Finished update process");
console.log("Remember to drop backup table postcodes_archive if you don't require it");
process.exit(0);
});
}
startImport();
| 31.168067 | 89 | 0.728229 |
3daaee5bcf6c487f9c406b47763e5f0f76376bce | 1,037 | js | JavaScript | src/components/newsletters.js | dchoinie/ulcmn2 | 82414401fbbceaf537ca14767299406292b7b07c | [
"MIT"
] | null | null | null | src/components/newsletters.js | dchoinie/ulcmn2 | 82414401fbbceaf537ca14767299406292b7b07c | [
"MIT"
] | null | null | null | src/components/newsletters.js | dchoinie/ulcmn2 | 82414401fbbceaf537ca14767299406292b7b07c | [
"MIT"
] | null | null | null | import React from "react"
import { StaticQuery, graphql } from "gatsby"
import Newsletter from "./newsletter"
const getNewsletters = graphql`
{
newsletters: allContentfulNewsletter(sort: { fields: date, order: DESC }) {
edges {
node {
contentful_id
date(formatString: "MMMM DD, YYYY")
slug
issueNumber
newsletter {
file {
url
}
}
}
}
}
}
`
const newsletters = () => {
return (
<div>
<StaticQuery
query={getNewsletters}
render={data => {
return (
<div className="info-grid">
{data.newsletters.edges.map(({ node: newsletter }) => {
return (
<Newsletter
key={newsletter.contentful_id}
newsletter={newsletter}
/>
)
})}
</div>
)
}}
/>
</div>
)
}
export default newsletters
| 20.74 | 79 | 0.450338 |
3dafc1ffaa04db28879052c2f6221982e68690cc | 325 | js | JavaScript | web/rainmaker/dev-packages/egov-ui-kit-dev/src/redux/auth/middleware.js | vicky-velocis/Dummy-CSC-frontend | 22dd98906ee4701214ddcfd331e0a59908e001e8 | [
"MIT"
] | null | null | null | web/rainmaker/dev-packages/egov-ui-kit-dev/src/redux/auth/middleware.js | vicky-velocis/Dummy-CSC-frontend | 22dd98906ee4701214ddcfd331e0a59908e001e8 | [
"MIT"
] | null | null | null | web/rainmaker/dev-packages/egov-ui-kit-dev/src/redux/auth/middleware.js | vicky-velocis/Dummy-CSC-frontend | 22dd98906ee4701214ddcfd331e0a59908e001e8 | [
"MIT"
] | null | null | null | import { refreshTokenRequest } from "egov-ui-kit/redux/auth/actions";
const auth = (store) => (next) => (action) => {
const { type } = action;
if (/(_ERROR|_FAILURE)$/.test(type) && action.error === "INVALID_TOKEN") {
store.dispatch(refreshTokenRequest());
} else {
next(action);
}
};
export default auth;
| 23.214286 | 76 | 0.627692 |
3db16bbdc9e2a6fe0820800a6582bb7f4b4755d6 | 435 | js | JavaScript | Assets/Scripts/Misc/ObjectHealth.js | aytona/VirtualRealityFPS | 631c78277ccd020f06e79bad1d3454f80edc96ec | [
"MIT"
] | null | null | null | Assets/Scripts/Misc/ObjectHealth.js | aytona/VirtualRealityFPS | 631c78277ccd020f06e79bad1d3454f80edc96ec | [
"MIT"
] | null | null | null | Assets/Scripts/Misc/ObjectHealth.js | aytona/VirtualRealityFPS | 631c78277ccd020f06e79bad1d3454f80edc96ec | [
"MIT"
] | 1 | 2018-08-25T22:15:04.000Z | 2018-08-25T22:15:04.000Z | /**
* Script written by Jackson Medeiros (BlackStorm)
* Do not remove this
**/
var hitPoints = 100.0;
var prefab : Transform;
function ApplyDamage (damage : float) {
if (hitPoints <= 0.0)
return;
hitPoints -= damage;
if (hitPoints <= 0.0)
{
Detonate();
}
}
function Detonate() {
if (prefab)
Instantiate (prefab, transform.position, transform.rotation);
Destroy(gameObject);
}
@script RequireComponent (Rigidbody) | 15 | 63 | 0.682759 |
3db20fc0e574e2d3ce250654e292a8b008c28858 | 499 | js | JavaScript | client/components/display/shop/shop_orders.js | Taulantvokshi/POS-System | e496aef07ac3bea0258af72989f28a28434cdd00 | [
"MIT"
] | null | null | null | client/components/display/shop/shop_orders.js | Taulantvokshi/POS-System | e496aef07ac3bea0258af72989f28a28434cdd00 | [
"MIT"
] | null | null | null | client/components/display/shop/shop_orders.js | Taulantvokshi/POS-System | e496aef07ac3bea0258af72989f28a28434cdd00 | [
"MIT"
] | null | null | null | import React, {useState, useEffect} from 'react'
import {connect} from 'react-redux'
import {ShopSingleOrder} from '../../../components'
import socket from '../../../socket'
const ShopOrders = ({orders}) => {
return (
<div className="single_order">
{orders.map(order => {
return <ShopSingleOrder key={order.id} order={order} />
})}
</div>
)
}
const mapState = state => {
return {
orders: state.orders.orders
}
}
export default connect(mapState)(ShopOrders)
| 22.681818 | 63 | 0.631263 |
3db2407293408f3dc47ecf44636f886f0cb4982e | 30,068 | js | JavaScript | unpackage/dist/dev/mp-weixin/components/cu-bar/cu-bar.js | bancangyanyu/avatar | 29a8443f79c73edfd78e4a056eb984ef48bba14e | [
"MIT"
] | null | null | null | unpackage/dist/dev/mp-weixin/components/cu-bar/cu-bar.js | bancangyanyu/avatar | 29a8443f79c73edfd78e4a056eb984ef48bba14e | [
"MIT"
] | null | null | null | unpackage/dist/dev/mp-weixin/components/cu-bar/cu-bar.js | bancangyanyu/avatar | 29a8443f79c73edfd78e4a056eb984ef48bba14e | [
"MIT"
] | null | null | null | (global["webpackJsonp"] = global["webpackJsonp"] || []).push([["components/cu-bar/cu-bar"],[
/* 0 */,
/* 1 */,
/* 2 */,
/* 3 */,
/* 4 */,
/* 5 */,
/* 6 */,
/* 7 */,
/* 8 */,
/* 9 */,
/* 10 */,
/* 11 */,
/* 12 */,
/* 13 */
/*!**********************************************************!*\
!*** D:/xxx/software-share/components/cu-bar/cu-bar.vue ***!
\**********************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _cu_bar_vue_vue_type_template_id_3f1ea144___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./cu-bar.vue?vue&type=template&id=3f1ea144& */ 14);
/* harmony import */ var _cu_bar_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cu-bar.vue?vue&type=script&lang=js& */ 16);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _cu_bar_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _cu_bar_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _cu_bar_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./cu-bar.vue?vue&type=style&index=0&lang=scss& */ 18);
/* harmony import */ var _software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/runtime/componentNormalizer.js */ 11);
var renderjs
/* normalize component */
var component = Object(_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__["default"])(
_cu_bar_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"],
_cu_bar_vue_vue_type_template_id_3f1ea144___WEBPACK_IMPORTED_MODULE_0__["render"],
_cu_bar_vue_vue_type_template_id_3f1ea144___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"],
false,
null,
null,
null,
false,
_cu_bar_vue_vue_type_template_id_3f1ea144___WEBPACK_IMPORTED_MODULE_0__["components"],
renderjs
)
component.options.__file = "components/cu-bar/cu-bar.vue"
/* harmony default export */ __webpack_exports__["default"] = (component.exports);
/***/ }),
/* 14 */
/*!*****************************************************************************************!*\
!*** D:/xxx/software-share/components/cu-bar/cu-bar.vue?vue&type=template&id=3f1ea144& ***!
\*****************************************************************************************/
/*! exports provided: render, staticRenderFns, recyclableRender, components */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_template_id_3f1ea144___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--16-0!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/webpack-uni-mp-loader/lib/template.js!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-uni-app-loader/page-meta.js!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!./cu-bar.vue?vue&type=template&id=3f1ea144& */ 15);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_template_id_3f1ea144___WEBPACK_IMPORTED_MODULE_0__["render"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_template_id_3f1ea144___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "recyclableRender", function() { return _software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_template_id_3f1ea144___WEBPACK_IMPORTED_MODULE_0__["recyclableRender"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "components", function() { return _software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_template_id_3f1ea144___WEBPACK_IMPORTED_MODULE_0__["components"]; });
/***/ }),
/* 15 */
/*!*****************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--16-0!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/template.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-uni-app-loader/page-meta.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!D:/xxx/software-share/components/cu-bar/cu-bar.vue?vue&type=template&id=3f1ea144& ***!
\*****************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! exports provided: render, staticRenderFns, recyclableRender, components */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "recyclableRender", function() { return recyclableRender; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "components", function() { return components; });
var components
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
}
var recyclableRender = false
var staticRenderFns = []
render._withStripped = true
/***/ }),
/* 16 */
/*!***********************************************************************************!*\
!*** D:/xxx/software-share/components/cu-bar/cu-bar.vue?vue&type=script&lang=js& ***!
\***********************************************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _software_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/babel-loader/lib!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--12-1!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/webpack-uni-mp-loader/lib/script.js!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!./cu-bar.vue?vue&type=script&lang=js& */ 17);
/* harmony import */ var _software_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_software_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _software_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _software_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony default export */ __webpack_exports__["default"] = (_software_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0___default.a);
/***/ }),
/* 17 */
/*!******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/babel-loader/lib!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--12-1!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/script.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!D:/xxx/software-share/components/cu-bar/cu-bar.vue?vue&type=script&lang=js& ***!
\******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });exports.default = void 0; //
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var _default =
{
name: 'bar',
props: {
title: {
type: String,
default: '' },
Tcolor: {
type: String,
default: '#0d419d' },
color: {
type: String,
default: 'blue' },
extra: {
type: String,
default: '' },
Ticon: {
type: String,
default: 'titles' },
Eicon: {
type: String,
default: '1' },
icon: {
type: String,
default: '' } },
data: function data() {
return {};
},
methods: {
onExtra: function onExtra() {
this.$emit('click');
} } };exports.default = _default;
/***/ }),
/* 18 */
/*!********************************************************************************************!*\
!*** D:/xxx/software-share/components/cu-bar/cu-bar.vue?vue&type=style&index=0&lang=scss& ***!
\********************************************************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _software_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_software_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_8_oneOf_1_2_software_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_software_HBuilderX_plugins_uniapp_cli_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_8_oneOf_1_5_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/mini-css-extract-plugin/dist/loader.js??ref--8-oneOf-1-0!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/css-loader/dist/cjs.js??ref--8-oneOf-1-1!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/stylePostLoader.js!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--8-oneOf-1-2!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/postcss-loader/src??ref--8-oneOf-1-3!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/sass-loader/dist/cjs.js??ref--8-oneOf-1-4!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--8-oneOf-1-5!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!../../../../software/HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!./cu-bar.vue?vue&type=style&index=0&lang=scss& */ 19);
/* harmony import */ var _software_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_software_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_8_oneOf_1_2_software_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_software_HBuilderX_plugins_uniapp_cli_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_8_oneOf_1_5_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_software_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_software_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_8_oneOf_1_2_software_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_software_HBuilderX_plugins_uniapp_cli_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_8_oneOf_1_5_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _software_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_software_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_8_oneOf_1_2_software_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_software_HBuilderX_plugins_uniapp_cli_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_8_oneOf_1_5_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _software_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_software_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_8_oneOf_1_2_software_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_software_HBuilderX_plugins_uniapp_cli_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_8_oneOf_1_5_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony default export */ __webpack_exports__["default"] = (_software_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_software_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_8_oneOf_1_2_software_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_3_software_HBuilderX_plugins_uniapp_cli_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_4_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_8_oneOf_1_5_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_software_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_cu_bar_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default.a);
/***/ }),
/* 19 */
/*!**********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/mini-css-extract-plugin/dist/loader.js??ref--8-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--8-oneOf-1-1!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--8-oneOf-1-2!./node_modules/postcss-loader/src??ref--8-oneOf-1-3!./node_modules/sass-loader/dist/cjs.js??ref--8-oneOf-1-4!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--8-oneOf-1-5!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!D:/xxx/software-share/components/cu-bar/cu-bar.vue?vue&type=style&index=0&lang=scss& ***!
\**********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
if(false) { var cssReload; }
/***/ })
]]);
//# sourceMappingURL=../../../.sourcemap/mp-weixin/components/cu-bar/cu-bar.js.map
;(global["webpackJsonp"] = global["webpackJsonp"] || []).push([
'components/cu-bar/cu-bar-create-component',
{
'components/cu-bar/cu-bar-create-component':(function(module, exports, __webpack_require__){
__webpack_require__('1')['createComponent'](__webpack_require__(13))
})
},
[['components/cu-bar/cu-bar-create-component']]
]);
| 134.232143 | 2,412 | 0.750964 |
3db6c4289a47762dc9ea8eadbea416f647c3fa89 | 1,147 | js | JavaScript | static/assets/svg/human/humanClothes/pythonDir/shirt2.svg.js | masterer/erintuitive_networking | 99d0b4e919e8c9cc8c1f3f204e745c9ede86d62d | [
"MIT"
] | null | null | null | static/assets/svg/human/humanClothes/pythonDir/shirt2.svg.js | masterer/erintuitive_networking | 99d0b4e919e8c9cc8c1f3f204e745c9ede86d62d | [
"MIT"
] | null | null | null | static/assets/svg/human/humanClothes/pythonDir/shirt2.svg.js | masterer/erintuitive_networking | 99d0b4e919e8c9cc8c1f3f204e745c9ede86d62d | [
"MIT"
] | null | null | null | var item = `<svg class="shirt" width="86" height="380" viewBox="202.715 584.407 86.5933 380.048" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg"> <defs id="svgEditorDefs"> <path id="svgEditorClosePathDefs" fill="moccasin" style="stroke-width: 0px; stroke: none; fill-opacity: 1;" class="shirt"/> </defs> <rect id="svgEditorBackground" x="202.71499633789062" y="584.4310302734375" width="86.59329986572266" height="115.80899810791016" style="fill: none; stroke: none;" class="shirt"/> <polygon id="e7_polygon" style="stroke: none; stroke-width: 0px;" points="254.828 683.96 247.215 684.916 244.518 727.947 245.893 727.947 247.955 690.833" fill="black" transform="matrix(-0.52 0 0 1.46972 403.612 -317.826)" class="shirt"/> <polygon id="e2_polygon" style="stroke-width: 0px; stroke: none;" points="236.324 654.435 204.02 670.242 206.082 779.524 210.206 778.149 215.017 686.737 208.832 792.583 278.937 793.957 274.126 684.676 276.532 778.665 277.562 778.149 290.621 778.837 289.075 671.617 259.005 654.434 259.349 792.927 246.633 791.897 239.417 792.927" fill="red" class="shirt"/></svg>`;
$("#relativeContainer").append(item); | 573.5 | 1,109 | 0.727986 |
3db90e9561f4a002ae25a2e532f9244ae0dd9f6a | 774 | js | JavaScript | app/main.js | jeffsui/myreact | 74af50442cb760a692a079e23c1a50aab0794904 | [
"MIT"
] | null | null | null | app/main.js | jeffsui/myreact | 74af50442cb760a692a079e23c1a50aab0794904 | [
"MIT"
] | null | null | null | app/main.js | jeffsui/myreact | 74af50442cb760a692a079e23c1a50aab0794904 | [
"MIT"
] | null | null | null | //main.js
/*'use strict'
require('!style!css!./style.css')
var component = require('./component.js');
// document.write(component());
document.body.innerHTML=component();*/
import Hello from './Hello.jsx' ;
//import World from './World.jsx' ;
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component{
constructor(props){
super(props);
}
render(){
return (
<div className="container">
<h1>Hello React</h1>
</div>
)
}
}
// ReactDOM.render(
// <App />,
// document.querySelector('#container')
// );
const app = document.createElement('div');
document.body.appendChild(app);
ReactDOM.render(<App />,app);
// ReactDOM.render(<Hello />,document.body) | 23.454545 | 43 | 0.611111 |
3dba4b1d204db98af40bfab21c1365cf79bdbdd0 | 440 | js | JavaScript | Documentation/html/search/all_0.js | AntoineHX/OMPL_Planning | 60b5fbb90799d89635956580bc2f596ca4db658f | [
"MIT"
] | null | null | null | Documentation/html/search/all_0.js | AntoineHX/OMPL_Planning | 60b5fbb90799d89635956580bc2f596ca4db658f | [
"MIT"
] | null | null | null | Documentation/html/search/all_0.js | AntoineHX/OMPL_Planning | 60b5fbb90799d89635956580bc2f596ca4db658f | [
"MIT"
] | null | null | null | var searchData=
[
['checking_5fbox',['Checking_Box',['../struct_checking___box.html',1,'']]],
['checkpath',['checkPath',['../class_o_m_p_l___planner.html#a3e94f89db54c6b2c302b46ea2140d56b',1,'OMPL_Planner']]],
['controller',['Controller',['../classcontroller__turtlebot_1_1_controller.html',1,'controller_turtlebot']]],
['controller',['Controller',['../classcontroller__quadrotor_1_1_controller.html',1,'controller_quadrotor']]]
];
| 55 | 117 | 0.745455 |
3dbab0a256f688279b5ba2e70e6be58f6544c19e | 37 | js | JavaScript | src/grapqhl/queries.js | thehashrocket/react-apollo-client | 884be3f6a760bf7372e4c3d3eb6bb8d94814fd0b | [
"MIT"
] | null | null | null | src/grapqhl/queries.js | thehashrocket/react-apollo-client | 884be3f6a760bf7372e4c3d3eb6bb8d94814fd0b | [
"MIT"
] | 5 | 2021-03-10T06:21:34.000Z | 2022-02-26T23:07:08.000Z | src/grapqhl/queries.js | thehashrocket/react-apollo-client | 884be3f6a760bf7372e4c3d3eb6bb8d94814fd0b | [
"MIT"
] | null | null | null | import { gql } from 'apollo-boost';
| 12.333333 | 35 | 0.648649 |
3dbb865a077ec707961aca920b4e88bfe7d98a7b | 16,419 | js | JavaScript | docs/build/p-g9hna2fo.system.entry.js | leoruhland/stenciljs-ionic-menu | 6e2345be5ca3a4a5471814e9351cf534a17b54d1 | [
"MIT"
] | null | null | null | docs/build/p-g9hna2fo.system.entry.js | leoruhland/stenciljs-ionic-menu | 6e2345be5ca3a4a5471814e9351cf534a17b54d1 | [
"MIT"
] | null | null | null | docs/build/p-g9hna2fo.system.entry.js | leoruhland/stenciljs-ionic-menu | 6e2345be5ca3a4a5471814e9351cf534a17b54d1 | [
"MIT"
] | null | null | null | var __awaiter=this&&this.__awaiter||function(t,e,n,i){return new(n||(n=Promise))(function(r,o){function s(t){try{a(i.next(t))}catch(t){o(t)}}function u(t){try{a(i["throw"](t))}catch(t){o(t)}}function a(t){t.done?r(t.value):new n(function(e){e(t.value)}).then(s,u)}a((i=i.apply(t,e||[])).next())})};var __generator=this&&this.__generator||function(t,e){var n={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},i,r,o,s;return s={next:u(0),throw:u(1),return:u(2)},typeof Symbol==="function"&&(s[Symbol.iterator]=function(){return this}),s;function u(t){return function(e){return a([t,e])}}function a(s){if(i)throw new TypeError("Generator is already executing.");while(n)try{if(i=1,r&&(o=s[0]&2?r["return"]:s[0]?r["throw"]||((o=r["return"])&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;if(r=0,o)s=[s[0]&2,o.value];switch(s[0]){case 0:case 1:o=s;break;case 4:n.label++;return{value:s[1],done:false};case 5:n.label++;r=s[1];s=[0];continue;case 7:s=n.ops.pop();n.trys.pop();continue;default:if(!(o=n.trys,o=o.length>0&&o[o.length-1])&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!o||s[1]>o[0]&&s[1]<o[3])){n.label=s[1];break}if(s[0]===6&&n.label<o[1]){n.label=o[1];o=s;break}if(o&&n.label<o[2]){n.label=o[2];n.ops.push(s);break}if(o[2])n.ops.pop();n.trys.pop();continue}s=e.call(t,n)}catch(t){s=[6,t];r=0}finally{i=o=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:true}}};System.register(["./p-d4bf7031.system.js","./p-bcf479c1.system.js","./p-17730780.system.js","./p-ea7a022a.system.js"],function(t){"use strict";var e,n,i,r,o,s,u,a,l,c,f,h;return{setters:[function(t){e=t.r;n=t.f;i=t.c;r=t.h;o=t.H;s=t.e;u=t.d},function(t){a=t.h},function(t){l=t.o;c=t.c},function(t){f=t.u;h=t.t}],execute:function(){var d=function(){function t(t){var i=this;e(this,t);this.inToolbar=false;this.inItem=false;this.buttonType="button";this.disabled=false;this.routerDirection="forward";this.strong=false;this.type="button";this.handleClick=function(t){if(i.type==="button"){l(i.href,t,i.routerDirection)}else if(a(i.el)){var e=i.el.closest("form");if(e){t.preventDefault();var n=document.createElement("button");n.type=i.type;n.style.display="none";e.appendChild(n);n.click();n.remove()}}};this.onFocus=function(){i.ionFocus.emit()};this.onBlur=function(){i.ionBlur.emit()};this.ionFocus=n(this,"ionFocus",7);this.ionBlur=n(this,"ionBlur",7)}t.prototype.componentWillLoad=function(){this.inToolbar=!!this.el.closest("ion-buttons");this.inItem=!!this.el.closest("ion-item")||!!this.el.closest("ion-item-divider")};Object.defineProperty(t.prototype,"hasIconOnly",{get:function(){return!!this.el.querySelector('ion-icon[slot="icon-only"]')},enumerable:true,configurable:true});Object.defineProperty(t.prototype,"rippleType",{get:function(){var t=this.fill===undefined||this.fill==="clear";if(t&&this.hasIconOnly&&this.inToolbar){return"unbounded"}return"bounded"},enumerable:true,configurable:true});t.prototype.render=function(){var t;var e=i(this);var n=this,s=n.buttonType,u=n.type,a=n.disabled,l=n.rel,f=n.target,h=n.size,d=n.href,b=n.color,p=n.expand,y=n.hasIconOnly,v=n.shape,m=n.strong;var _=h===undefined&&this.inItem?"small":h;var g=d===undefined?"button":"a";var w=g==="button"?{type:u}:{download:this.download,href:d,rel:l,target:f};var T=this.fill;if(T===undefined){T=this.inToolbar?"clear":"solid"}return r(o,{onClick:this.handleClick,"aria-disabled":a?"true":null,class:Object.assign({},c(b),(t={},t[e]=true,t[s]=true,t[s+"-"+p]=p!==undefined,t[s+"-"+_]=_!==undefined,t[s+"-"+v]=v!==undefined,t[s+"-"+T]=true,t[s+"-strong"]=m,t["button-has-icon-only"]=y,t["button-disabled"]=a,t["ion-activatable"]=true,t["ion-focusable"]=true,t))},r(g,Object.assign({},w,{class:"button-native",disabled:a,onFocus:this.onFocus,onBlur:this.onBlur}),r("span",{class:"button-inner"},r("slot",{name:"icon-only"}),r("slot",{name:"start"}),r("slot",null),r("slot",{name:"end"})),e==="md"&&r("ion-ripple-effect",{type:this.rippleType})))};Object.defineProperty(t.prototype,"el",{get:function(){return s(this)},enumerable:true,configurable:true});Object.defineProperty(t,"style",{get:function(){return":host{--overflow:hidden;--ripple-color:currentColor;--border-width:initial;--border-color:initial;--border-style:initial;--color-hover:initial;--box-shadow:none;display:inline-block;width:auto;color:var(--color);font-family:var(--ion-font-family,inherit);text-align:center;text-decoration:none;text-overflow:ellipsis;white-space:nowrap;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;vertical-align:top;vertical-align:-webkit-baseline-middle;pointer-events:auto;-webkit-font-kerning:none;font-kerning:none}:host(.button-disabled){--opacity:.5;pointer-events:none}:host(.button-disabled) .button-native{cursor:default;pointer-events:none}:host(.button-solid){--background:var(--ion-color-primary,#3880ff);--background-focused:var(--ion-color-primary-shade,#3171e0);--background-hover:var(--ion-color-primary-tint,#4c8dff);--color:var(--ion-color-primary-contrast,#fff);--color-activated:var(--ion-color-primary-contrast,#fff);--color-focused:var(--ion-color-primary-contrast,#fff)}:host(.button-solid.ion-color) .button-native{background:var(--ion-color-base);color:var(--ion-color-contrast)}:host(.button-solid.ion-color.ion-focused) .button-native{background:var(--ion-color-shade)}:host(.button-outline){--border-color:var(--ion-color-primary,#3880ff);--background:transparent;--color:var(--ion-color-primary,#3880ff);--color-focused:var(--ion-color-primary,#3880ff)}:host(.button-outline.ion-color) .button-native{border-color:var(--ion-color-base);background:transparent;color:var(--ion-color-base)}:host(.button-outline.ion-focused.ion-color) .button-native{background:rgba(var(--ion-color-base-rgb),.1);color:var(--ion-color-base)}:host(.button-clear){--border-width:0;--background:transparent;--color:var(--ion-color-primary,#3880ff)}:host(.button-clear.ion-color) .button-native{background:transparent;color:var(--ion-color-base)}:host(.button-clear.ion-focused.ion-color) .button-native{background:rgba(var(--ion-color-base-rgb),.1);color:var(--ion-color-base)}:host(.button-clear.activated.ion-color) .button-native{background:transparent}:host(.button-block){display:block}:host(.button-block) .button-native{margin-left:0;margin-right:0;display:block;width:100%;clear:both;contain:content}:host(.button-block) .button-native:after{clear:both}:host(.button-full){display:block}:host(.button-full) .button-native{margin-left:0;margin-right:0;display:block;width:100%;contain:content}:host(.button-full:not(.button-round)) .button-native{border-radius:0;border-right-width:0;border-left-width:0}.button-native{border-radius:var(--border-radius);-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;margin-left:0;margin-right:0;margin-top:0;margin-bottom:0;padding-left:var(--padding-start);padding-right:var(--padding-end);padding-top:var(--padding-top);padding-bottom:var(--padding-bottom);font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;letter-spacing:inherit;text-decoration:inherit;text-overflow:inherit;text-transform:inherit;text-align:inherit;white-space:inherit;color:inherit;display:block;position:relative;width:100%;height:100%;-webkit-transition:var(--transition);transition:var(--transition);border-width:var(--border-width);border-style:var(--border-style);border-color:var(--border-color);outline:none;background:var(--background);line-height:1;-webkit-box-shadow:var(--box-shadow);box-shadow:var(--box-shadow);contain:layout style;cursor:pointer;opacity:var(--opacity);overflow:var(--overflow);z-index:0;-webkit-box-sizing:border-box;box-sizing:border-box;-webkit-appearance:none;-moz-appearance:none;appearance:none}\@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){.button-native{padding-left:unset;padding-right:unset;-webkit-padding-start:var(--padding-start);padding-inline-start:var(--padding-start);-webkit-padding-end:var(--padding-end);padding-inline-end:var(--padding-end)}}.button-native::-moz-focus-inner{border:0}.button-inner{display:-ms-flexbox;display:flex;-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-negative:0;flex-shrink:0;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:100%;height:100%}::slotted(ion-icon){font-size:1.4em;pointer-events:none}::slotted(ion-icon[slot=start]){margin-left:-.3em;margin-right:.3em;margin-top:0;margin-bottom:0}\@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){::slotted(ion-icon[slot=start]){margin-left:unset;margin-right:unset;-webkit-margin-start:-.3em;margin-inline-start:-.3em;-webkit-margin-end:.3em;margin-inline-end:.3em}}::slotted(ion-icon[slot=end]){margin-left:.3em;margin-right:-.2em;margin-top:0;margin-bottom:0}\@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){::slotted(ion-icon[slot=end]){margin-left:unset;margin-right:unset;-webkit-margin-start:.3em;margin-inline-start:.3em;-webkit-margin-end:-.2em;margin-inline-end:-.2em}}::slotted(ion-icon[slot=icon-only]){font-size:1.8em}ion-ripple-effect{color:var(--ripple-color)}:host(.ion-focused) .button-native{background:var(--background-focused);color:var(--color-focused)}:host(.activated) .button-native{background:var(--background-activated);color:var(--color-activated)}\@media (any-hover:hover){:host(:hover) .button-native{background:var(--background-hover);color:var(--color-hover)}}:host{--border-radius:4px;--padding-top:0;--padding-bottom:0;--padding-start:1.1em;--padding-end:1.1em;--transition:box-shadow 280ms cubic-bezier(.4,0,.2,1),background-color 15ms linear,color 15ms linear;margin-left:2px;margin-right:2px;margin-top:4px;margin-bottom:4px;height:36px;font-size:14px;font-weight:500;letter-spacing:.06em;text-transform:uppercase}\@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){:host{margin-left:unset;margin-right:unset;-webkit-margin-start:2px;margin-inline-start:2px;-webkit-margin-end:2px;margin-inline-end:2px}}:host(.button-solid){--background-activated:var(--background);--box-shadow:0 3px 1px -2px rgba(0,0,0,0.2),0 2px 2px 0 rgba(0,0,0,0.14),0 1px 5px 0 rgba(0,0,0,0.12)}:host(.button-solid.activated){--box-shadow:0 5px 5px -3px rgba(0,0,0,0.2),0 8px 10px 1px rgba(0,0,0,0.14),0 3px 14px 2px rgba(0,0,0,0.12)}:host(.button-outline){--border-width:2px;--border-style:solid;--box-shadow:none;--background-activated:transparent;--background-focused:rgba(var(--ion-color-primary-rgb,56,128,255),0.1);--background-hover:rgba(var(--ion-color-primary-rgb,56,128,255),0.04);--color-activated:var(--ion-color-primary,#3880ff)}:host(.button-outline.activated.ion-color) .button-native{background:transparent}:host(.button-clear){--background-activated:transparent;--background-focused:rgba(var(--ion-color-primary-rgb,56,128,255),0.1);--background-hover:rgba(var(--ion-color-primary-rgb,56,128,255),0.04);--color-activated:var(--ion-color-primary,#3880ff);--color-focused:var(--ion-color-primary,#3880ff)}:host(.button-round){--border-radius:64px;--padding-top:0;--padding-start:26px;--padding-end:26px;--padding-bottom:0}:host(.button-large){--padding-top:0;--padding-start:1em;--padding-end:1em;--padding-bottom:0;height:2.8em;font-size:20px}:host(.button-small){--padding-top:0;--padding-start:0.9em;--padding-end:0.9em;--padding-bottom:0;height:2.1em;font-size:13px}:host(.button-strong){font-weight:700}::slotted(ion-icon[slot=icon-only]){padding-left:0;padding-right:0;padding-top:0;padding-bottom:0}\@media (any-hover:hover){:host(.button-solid.ion-color:hover) .button-native{background:var(--ion-color-tint)}:host(.button-clear.ion-color:hover) .button-native,:host(.button-outline.ion-color:hover) .button-native{background:rgba(var(--ion-color-base-rgb),.04)}}"},enumerable:true,configurable:true});return t}();t("ion_button",d);var b=function(){function t(t){var n=this;e(this,t);this.visible=false;this.disabled=false;this.autoHide=true;this.type="button";this.setVisibility=function(){return __awaiter(n,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:t=this;return[4,f(this.menu)];case 1:t.visible=e.sent();return[2]}})})};this.onClick=function(){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(t){switch(t.label){case 0:return[4,h(this.menu)];case 1:t.sent();return[2]}})})}}t.prototype.componentDidLoad=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){switch(t.label){case 0:return[4,this.setVisibility()];case 1:t.sent();return[2]}})})};t.prototype.visibilityChanged=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){switch(t.label){case 0:return[4,this.setVisibility()];case 1:t.sent();return[2]}})})};t.prototype.render=function(){var t;var e=this,n=e.color,s=e.disabled;var a=i(this);var l=u.get("menuIcon","menu");var f=this.autoHide&&!this.visible;var h={type:this.type};return r(o,{onClick:this.onClick,"aria-disabled":s?"true":null,"aria-hidden":f?"true":null,class:Object.assign((t={},t[a]=true,t),c(n),{button:true,"menu-button-hidden":f,"menu-button-disabled":s,"ion-activatable":true,"ion-focusable":true})},r("button",Object.assign({},h,{disabled:this.disabled,class:"button-native"}),r("slot",null,r("ion-icon",{icon:l,mode:a,lazy:false})),a==="md"&&r("ion-ripple-effect",{type:"unbounded"})))};Object.defineProperty(t,"style",{get:function(){return":host{--background:transparent;--color-focused:var(--color);--border-radius:initial;--padding-top:0;--padding-bottom:0;color:var(--color);text-align:center;text-decoration:none;text-overflow:ellipsis;text-transform:none;white-space:nowrap;-webkit-font-kerning:none;font-kerning:none}.button-native{border-radius:var(--border-radius);font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;letter-spacing:inherit;text-decoration:inherit;text-overflow:inherit;text-transform:inherit;text-align:inherit;white-space:inherit;color:inherit;margin-left:0;margin-right:0;margin-top:0;margin-bottom:0;padding-left:var(--padding-start);padding-right:var(--padding-end);padding-top:var(--padding-top);padding-bottom:var(--padding-bottom);-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:-ms-flexbox;display:flex;position:relative;-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-negative:0;flex-shrink:0;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:100%;height:100%;border:0;outline:none;background:var(--background);line-height:1;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;z-index:0;-webkit-appearance:none;-moz-appearance:none;appearance:none}\@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){.button-native{padding-left:unset;padding-right:unset;-webkit-padding-start:var(--padding-start);padding-inline-start:var(--padding-start);-webkit-padding-end:var(--padding-end);padding-inline-end:var(--padding-end)}}ion-icon{margin-left:0;margin-right:0;margin-top:0;margin-bottom:0;padding-left:0;padding-right:0;padding-top:0;padding-bottom:0;pointer-events:none}:host(.menu-button-hidden){display:none}:host(.menu-button-disabled){cursor:default;opacity:.5;pointer-events:none}\@media (any-hover:hover){:host(:hover) .button-native{background:var(--background-hover);color:var(--color-hover)}}:host(.ion-focused) .button-native{background:var(--background-focused);color:var(--color-focused)}:host(.ion-color) .button-native{color:var(--ion-color-base)}:host-context(ion-toolbar:not(.ion-color)){color:var(--ion-toolbar-color,var(--color))}:host{--background-focused:rgba(66,66,66,0.24);--background-hover:rgba(66,66,66,0.08);--border-radius:50%;--color:initial;--padding-start:8px;--padding-end:8px;width:48px;height:48px;font-size:24px}\@media (any-hover:hover){:host(.ion-color:hover) .button-native{background:rgba(var(--ion-color-base-rgb),.08)}}:host(.ion-color.ion-focused) .button-native{background:rgba(var(--ion-color-base-rgb),.24);color:var(--ion-color-base)}"},enumerable:true,configurable:true});return t}();t("ion_menu_button",b);var p=function(){function t(t){e(this,t)}t.prototype.render=function(){return r("p",null,"My name is ",this.name)};return t}();t("my_first_component",p)}}}); | 16,419 | 16,419 | 0.742554 |
3dbd3af596945d88a03b14fd3e20bbc644793e79 | 3,089 | js | JavaScript | app/public/js/view_members.app.js | kengibso/Team27-FinalProject-DS | 4934c10872aa23eeff01b5f8bf15662d745ef34f | [
"MIT"
] | null | null | null | app/public/js/view_members.app.js | kengibso/Team27-FinalProject-DS | 4934c10872aa23eeff01b5f8bf15662d745ef34f | [
"MIT"
] | null | null | null | app/public/js/view_members.app.js | kengibso/Team27-FinalProject-DS | 4934c10872aa23eeff01b5f8bf15662d745ef34f | [
"MIT"
] | null | null | null | var app = new Vue({
el: '#members',
data:{
memberList: [],
activeMember: {},
positionList: [],
newMember: {},
membercertification: [],
certificationList: []
},
created(){
this.fetchMember();
this.fetchPosition();
this.fetchCertification();
},
methods: {
fetchCertification: function(){
fetch('api/records/view_certifications.php')
.then(response => response.json())
.then(data => {
this.certificationList = data;
console.log(data);
});
},
fetchMemberCertification(){
fetch('api/records/view_member_certifications.php',{
method: 'POST',
body: JSON.stringify(this.activeMember),
headers: {
"Content-Type": "application/json; charset=utf-8"
}
})
.then(response => response.json())
.then(data => {
this.membercertification = data;
console.log(data);
});
console.log("creating (POSTing)...!");
console.log(this.activeMember);
},
editMember(){
fetch('api/records/edit_member.php',{
method: 'POST',
body: JSON.stringify(this.activeMember),
headers: {
"Content-Type": "application/json; charset=utf-8"
}
})
console.log("creating (POSTing)...!");
console.log(this.activeMember);
},
newMemberData(){
return {
firstName: "",
lastName: "",
positionID: "",
gender: "",
address: "",
dateOfBirth: "",
workPhone: "",
mobilePhone: "",
startDate: "",
radioNumber: "",
stationNumber: "",
email: "",
certificationID: "",
testDate: "",
}
},
createMember(){
fetch('api/records/update_members.php',{
method: 'POST',
body: JSON.stringify(this.newMember),
headers: {
"Content-Type": "application/json; charset=utf-8"
}
})
.then( response => response.json() )
.then( json => {
console.log ("Returned from post:", json);
this.memberList.push(json[json.length - 1]);
this.newMember = this.newMemberData();
});
console.log("creating (POSTing)...!");
console.log(this.newMember);
},
fetchPosition: function(){
fetch('api/records/view_positions.php')
.then(response => response.json())
.then(data => {
this.positionList = data;
console.log(data);
});
},
deleteMember(){
fetch('api/records/delete_member.php',{
method: 'POST',
body: JSON.stringify(this.activeMember),
headers: {
"Content-Type": "application/json; charset=utf-8"
}
})
console.log("creating (POSTing)...!");
console.log(this.activeMember);
},
fetchMember: function(){
fetch('api/records/view_members.php')
.then(response => response.json())
.then(data => {
this.memberList = data;
console.log(data);
});
}
}
})
| 20.189542 | 59 | 0.526708 |
3dbe47b4766ebcb4695636cab799bbc81ec04073 | 1,409 | js | JavaScript | server.js | remckee/weather-scraper-service | d86cd92cc5d8bd5b02b3efaba967574db9e47758 | [
"MIT"
] | null | null | null | server.js | remckee/weather-scraper-service | d86cd92cc5d8bd5b02b3efaba967574db9e47758 | [
"MIT"
] | null | null | null | server.js | remckee/weather-scraper-service | d86cd92cc5d8bd5b02b3efaba967574db9e47758 | [
"MIT"
] | null | null | null | import weather from './main.js';
import https from 'https';
import { WebSocketServer } from 'ws';
'use strict';
const url = 'https://api.openweathermap.org/data/2.5/weather?';
const port = 5524;
const wss = new WebSocketServer({ port: port });
console.log(`Listening on ${port}...`);
function get_units(temp_unit) {
var units = {};
if (temp_unit == 'C') {
units.unit = temp_unit;
units.system = "metric";
} else {
units.unit = 'F';
units.system = "imperial";
}
return units;
}
wss.on('connection', function connection(ws) {
console.log(`Client connected on port ${port}`);
ws.on('message', (request) => {
console.log('received request: \n%s', request);
var req = JSON.parse(request.toString());
var units = get_units(req.unit);
var params = {};
if (req.zip) {
params.zip = req.zip;
} else {
var loc = [req.city, req.state, req.country];
params.q = loc.join(',');
}
// To obtain the value for appid, create an account at
// https://home.openweathermap.org/users/sign_up
params.appid = "";
params.units = units.system;
console.log(params);
weather(url, params, units.unit, ws);
});
ws.on('close', () => {
console.log('Client has disconnected');
});
});
| 24.719298 | 63 | 0.549326 |
3dbf4f2f6d92b20d84f4b631400bea441d15b9ba | 4,018 | js | JavaScript | deep_copy.js | faranalytics/deep_copy | 76de370e558cf5fc540d9f92bf1458b8967641a2 | [
"MIT"
] | null | null | null | deep_copy.js | faranalytics/deep_copy | 76de370e558cf5fc540d9f92bf1458b8967641a2 | [
"MIT"
] | null | null | null | deep_copy.js | faranalytics/deep_copy | 76de370e558cf5fc540d9f92bf1458b8967641a2 | [
"MIT"
] | null | null | null | "use strict";
function bm(o) {
return function fn() {
var r = o.apply(this, arguments);
if (typeof r !== "undefined") {
if (!m.has(r)) {
r = deep(r)
}
return r
}
}
}
const m = new Map([[null, null]])
module.exports = function deep(copy) {
if (Object(copy) !== copy) {
return copy
}
(function fn(o) {
if (!m.has(o) && Object(o) === o) {
fn(Object.getPrototypeOf(o))
if (typeof o === "function") {
m.set(o, bm(o))
}
else if (o.constructor === Array || Array.isArray(o)) {
m.set(o, [])
}
else if (o.constructor === RegExp) {
m.set(o, new RegExp(o))
}
else {
m.set(o, {})
}
Object.getOwnPropertyNames(o).concat(Object.getOwnPropertySymbols(o)).forEach((k) => {
try {
let pd = Object.getOwnPropertyDescriptor(o, k)
Object.getOwnPropertyNames(pd).concat(Object.getOwnPropertySymbols(pd)).forEach((k) => {
try {
fn(pd[k])
}
catch (e) {
console.log(pd)
console.log(k)
}
})
fn(o[k])
}
catch (e) {
console.log(o)
console.log(k)
}
})
}
}(copy))
m.forEach((ov, ok) => {
if (ok !== null) {
Object.getOwnPropertyNames(ok).concat(Object.getOwnPropertySymbols(ok)).forEach((k) => {
try {
var pd = Object.getOwnPropertyDescriptor(ok, k)
Object.getOwnPropertyNames(pd).concat(Object.getOwnPropertySymbols(pd)).forEach((k) => {
if (Object(pd[k]) === pd[k]) {
let x = m.get(pd[k])
if (typeof x === "undefined") {
throw ("undefined");
}
else {
pd[k] = x;
}
}
})
if (Object(ok[k]) === ok[k]) {
if (pd.hasOwnProperty("value")) {
let x = m.get(ok[k])
if (typeof x === "undefined") {
throw ("undefined");
}
else {
pd["value"] = x;
}
}
Object.defineProperty(ov, k, pd)
}
else {
if (pd.hasOwnProperty("value")) {
pd["value"] = ok[k]
}
Object.defineProperty(ov, k, pd)
}
} catch (e) {
if (pd.hasOwnProperty("value")) {
pd["value"] = null
}
Object.defineProperty(ov, k, pd)
}
})
}
})
m.forEach((ov, ok) => {
if (ok !== null) {
let pstack = [Object.getPrototypeOf(ok)];
while (pstack.length) {
let pk = pstack.pop();
let pv = m.get(pk)
if (typeof pv === "undefined") {
throw ("undefined")
}
Object.setPrototypeOf(ov, pv)
ov = pv
if (pv !== null) {
pstack.push(Object.getPrototypeOf(pk))
}
}
}
})
return m.get(copy)
}
| 21.956284 | 108 | 0.32454 |
3dc0c021c6c0a99b153a15489c9103344fd2ad4f | 1,405 | js | JavaScript | src/features/Product/pathApi.js | thuong-resper/resper-shop | 764d4531e8eee7e2647c5fcad7df4ec16eb6703f | [
"MIT"
] | null | null | null | src/features/Product/pathApi.js | thuong-resper/resper-shop | 764d4531e8eee7e2647c5fcad7df4ec16eb6703f | [
"MIT"
] | null | null | null | src/features/Product/pathApi.js | thuong-resper/resper-shop | 764d4531e8eee7e2647c5fcad7df4ec16eb6703f | [
"MIT"
] | null | null | null | import { createAsyncThunk } from '@reduxjs/toolkit';
import productAPI from 'apis/productsApi';
export const getListProducts = createAsyncThunk('product/getListProducts', async (params) => {
const response = await productAPI.getListProducts(params);
return response;
});
export const getPremiumProducts = createAsyncThunk('product/getPremiumProducts', async (params) => {
const response = await productAPI.getPremiumProducts(params);
return response;
});
export const getListProductsMan = createAsyncThunk('product/getListProductsMan', async (params) => {
const response = await productAPI.getListProducts(params);
return response;
});
export const getListProductWoman = createAsyncThunk(
'product/getListProductWoman',
async (params) => {
const response = await productAPI.getListProducts(params);
return response;
}
);
export const getProductId = createAsyncThunk('product/getProductId', async (id) => {
const response = await productAPI.getProductId(id);
return response;
});
export const getRelated = createAsyncThunk('product/getRelated', async (params) => {
const response = await productAPI.getRelated(params);
return response;
});
export const getProductTrademarkType = createAsyncThunk('trademarkType', async (params) => {
const response = await productAPI.getProductTrademarkType(params);
return response;
});
| 34.268293 | 101 | 0.739502 |
3dc0fa77b707144954085a159c67eed7f69e5bc3 | 316 | js | JavaScript | JavaScript Fundmentals/02.Operators and Logic Flow Lab/06. Cone.js | dimitar9111/JavaScript-Core | 2b891138d9a5515071a0e3cd6697547377b71ccb | [
"MIT"
] | null | null | null | JavaScript Fundmentals/02.Operators and Logic Flow Lab/06. Cone.js | dimitar9111/JavaScript-Core | 2b891138d9a5515071a0e3cd6697547377b71ccb | [
"MIT"
] | null | null | null | JavaScript Fundmentals/02.Operators and Logic Flow Lab/06. Cone.js | dimitar9111/JavaScript-Core | 2b891138d9a5515071a0e3cd6697547377b71ccb | [
"MIT"
] | null | null | null | function printVolumeArea(radius, height) {
let volume = Math.PI * radius * radius * (height / 3);
let slant = height * height + radius * radius;
let area = Math.PI * radius * (radius + Math.sqrt(slant));
console.log(`volume = ${volume}`)
console.log(`area = ${area}`)
}
printVolumeArea(3, 5);
| 26.333333 | 62 | 0.620253 |
3dc1d32e8ea78622a0f05ff4beb5ce43c12dddb9 | 378 | js | JavaScript | src/constants.js | fossabot/parkrun.js | ec3f1d5aaae2baac86a8f61ebc76ed4b3fa9360c | [
"MIT"
] | null | null | null | src/constants.js | fossabot/parkrun.js | ec3f1d5aaae2baac86a8f61ebc76ed4b3fa9360c | [
"MIT"
] | null | null | null | src/constants.js | fossabot/parkrun.js | ec3f1d5aaae2baac86a8f61ebc76ed4b3fa9360c | [
"MIT"
] | null | null | null | /**
* Parkrun.JS Constants
*
* @static
* @readonly
*/
module.exports = {
api_base:
process.env.PLATFORM !== "WEB"
? "https://api.parkrun.com"
: "https://parkrun-proxy.x2.workers.dev/",
auth_raw:
"bmV0ZHJlYW1zLWlwaG9uZS1zMDE6Z2ZLYkRENk5Ka1lvRm1raXNSKGlWRm9wUUNLV3piUWVRZ1pBWlpLSw==",
user_agent: "parkrun/1.2.7 CFNetwork/1121.2.2 Darwin/19.3.0"
};
| 23.625 | 91 | 0.677249 |
3dc22c02190f8f21b809b870ba2554c720c6f413 | 26,665 | js | JavaScript | assets/js/shortcodes/shortcodes.js | iamacceptable/evedant | 9a08c8853fe78deba8b5b27b4b33ca180a137277 | [
"MIT"
] | null | null | null | assets/js/shortcodes/shortcodes.js | iamacceptable/evedant | 9a08c8853fe78deba8b5b27b4b33ca180a137277 | [
"MIT"
] | 1 | 2021-03-11T01:49:59.000Z | 2021-03-11T01:49:59.000Z | assets_frontend/js/js_edu/shortcodes/shortcodes.js | agustree/website_ci | 021c82a096a62767ccd8485ec27f40bb68ee6d91 | [
"MIT"
] | null | null | null | // Document ready actions for shortcodes
jQuery(document).ready(function(){
"use strict";
setTimeout(themerex_animation_shortcodes, 600);
});
// Animation
function themerex_animation_shortcodes() {
jQuery('[data-animation^="animated"]:not(.animated)').each(function() {
"use strict";
if (jQuery(this).offset().top < jQuery(window).scrollTop() + jQuery(window).height())
jQuery(this).addClass(jQuery(this).data('animation'));
});
}
// Shortcodes init
function themerex_init_shortcodes(container) {
// Accordion
if (container.find('.sc_accordion:not(.inited)').length > 0) {
container.find(".sc_accordion:not(.inited)").each(function () {
"use strict";
var init = jQuery(this).data('active');
if (isNaN(init)) init = 0;
else init = Math.max(0, init);
jQuery(this)
.addClass('inited')
.accordion({
active: init,
heightStyle: "content",
header: "> .sc_accordion_item > .sc_accordion_title",
create: function (event, ui) {
themerex_init_shortcodes(ui.panel);
if (window.themerex_init_hidden_elements) themerex_init_hidden_elements(ui.panel);
ui.header.each(function () {
jQuery(this).parent().addClass('sc_active');
});
},
activate: function (event, ui) {
themerex_init_shortcodes(ui.newPanel);
if (window.themerex_init_hidden_elements) themerex_init_hidden_elements(ui.newPanel);
ui.newHeader.each(function () {
jQuery(this).parent().addClass('sc_active');
});
ui.oldHeader.each(function () {
jQuery(this).parent().removeClass('sc_active');
});
}
});
});
}
// Contact form
if (container.find('.sc_contact_form:not(.inited) form').length > 0) {
container.find(".sc_contact_form:not(.inited) form")
.addClass('inited')
.submit(function(e) {
"use strict";
themerex_contact_form_validate(jQuery(this));
e.preventDefault();
return false;
});
}
//Countdown
if (container.find('.sc_countdown:not(.inited)').length > 0) {
container.find('.sc_countdown:not(.inited)')
.each(function () {
"use strict";
jQuery(this).addClass('inited');
var id = jQuery(this).attr('id');
var curDate = new Date();
var curDateTimeStr = curDate.getFullYear()+'-'+(curDate.getMonth()<9 ? '0' : '')+(curDate.getMonth()+1)+'-'+(curDate.getDate()<10 ? '0' : '')+curDate.getDate()
+' '+(curDate.getHours()<10 ? '0' : '')+curDate.getHours()+':'+(curDate.getMinutes()<10 ? '0' : '')+curDate.getMinutes()+':'+(curDate.getSeconds()<10 ? '0' : '')+curDate.getSeconds();
var interval = 1; //jQuery(this).data('interval');
var endDateStr = jQuery(this).data('date');
var endDateParts = endDateStr.split('-');
var endTimeStr = jQuery(this).data('time');
var endTimeParts = endTimeStr.split(':');
if (endTimeParts.length < 3) endTimeParts[2] = '00';
var endDateTimeStr = endDateStr+' '+endTimeStr;
if (curDateTimeStr < endDateTimeStr) {
jQuery(this).find('.sc_countdown_placeholder').countdown({
until: new Date(endDateParts[0], endDateParts[1]-1, endDateParts[2], endTimeParts[0], endTimeParts[1], endTimeParts[2]),
tickInterval: interval,
onTick: themerex_countdown
});
} else {
jQuery(this).find('.sc_countdown_placeholder').countdown({
since: new Date(endDateParts[0], endDateParts[1]-1, endDateParts[2], endTimeParts[0], endTimeParts[1], endTimeParts[2]),
tickInterval: interval,
onTick: themerex_countdown
});
}
});
}
// Emailer form
if (container.find('.sc_emailer:not(.inited)').length > 0) {
container.find(".sc_emailer:not(.inited)")
.addClass('inited')
.find('.sc_emailer_button')
.click(function(e) {
"use strict";
var form = jQuery(this).parents('form');
var parent = jQuery(this).parents('.sc_emailer');
if (parent.hasClass('sc_emailer_opened')) {
if (form.length>0 && form.find('input').val()!='') {
var group = jQuery(this).data('group');
var email = form.find('input').val();
var regexp = new RegExp(THEMEREX_GLOBALS['email_mask']);
if (!regexp.test(email)) {
form.find('input').get(0).focus();
themerex_message_warning(THEMEREX_GLOBALS['strings']['email_not_valid']);
} else {
jQuery.post(THEMEREX_GLOBALS['ajax_url'], {
action: 'emailer_submit',
nonce: THEMEREX_GLOBALS['ajax_nonce'],
group: group,
email: email
}).done(function(response) {
var rez = JSON.parse(response);
if (rez.error === '') {
themerex_message_info(THEMEREX_GLOBALS['strings']['email_confirm'].replace('%s', email));
form.find('input').val('');
} else {
themerex_message_warning(rez.error);
}
});
}
} else
form.get(0).submit();
} else {
parent.addClass('sc_emailer_opened');
}
e.preventDefault();
return false;
});
}
// Googlemap init
if (container.find('.sc_googlemap:not(.inited)').length > 0) {
container.find('.sc_googlemap:not(.inited)')
.each(function () {
"use strict";
if (jQuery(this).parents('div:hidden,article:hidden').length > 0) return;
var map = jQuery(this).addClass('inited');
var map_address = map.data('address');
var map_latlng = map.data('latlng');
var map_id = map.attr('id');
var map_zoom = map.data('zoom');
var map_style = map.data('style');
var map_descr = map.data('description');
var map_title = map.data('title');
var map_point = map.data('point');
themerex_googlemap_init( jQuery('#'+map_id).get(0), {address: map_address , latlng: map_latlng, style: map_style, zoom: map_zoom, description: map_descr, title: map_title, point: map_point});
});
}
// Infoboxes
if (container.find('.sc_infobox.sc_infobox_closeable:not(.inited)').length > 0) {
container.find('.sc_infobox.sc_infobox_closeable:not(.inited)')
.addClass('inited')
.click(function () {
jQuery(this).slideUp();
});
}
// Popup links
if (container.find('.popup_link:not(.inited)').length > 0) {
container.find('.popup_link:not(.inited)')
.addClass('inited')
.magnificPopup({
type: 'inline',
removalDelay: 500,
midClick: true,
callbacks: {
beforeOpen: function () {
this.st.mainClass = 'mfp-zoom-in';
},
open: function() {},
close: function() {}
}
});
}
// Search form
if (container.find('.search_wrap:not(.inited)').length > 0) {
container.find('.search_wrap:not(.inited)').each(function() {
jQuery(this).addClass('inited');
jQuery(this).find('.search_icon').click(function(e) {
"use strict";
var search_wrap = jQuery(this).parent();
if (!search_wrap.hasClass('search_fixed')) {
if (search_wrap.hasClass('search_opened')) {
search_wrap.find('.search_form_wrap').animate({'width': 'hide'}, 200, function() {
if (search_wrap.parents('.menu_main_wrap').length > 0)
search_wrap.parents('.menu_main_wrap').removeClass('search_opened');
});
search_wrap.find('.search_results').fadeOut();
search_wrap.removeClass('search_opened');
} else {
search_wrap.find('.search_form_wrap').animate({'width': 'show'}, 200, function() {
jQuery(this).parents('.search_wrap').addClass('search_opened');
jQuery(this).find('input').get(0).focus();
});
if (search_wrap.parents('.menu_main_wrap').length > 0)
search_wrap.parents('.menu_main_wrap').addClass('search_opened');
}
} else {
search_wrap.find('.search_field').val('');
search_wrap.find('.search_results').fadeOut();
}
e.preventDefault();
return false;
});
jQuery(this).find('.search_results_close').click(function(e) {
"use strict";
jQuery(this).parent().fadeOut();
e.preventDefault();
return false;
});
jQuery(this).on('click', '.search_submit,.search_more', function(e) {
"use strict";
if (jQuery(this).parents('.search_wrap').find('.search_field').val() != '')
jQuery(this).parents('.search_wrap').find('.search_form_wrap form').get(0).submit();
e.preventDefault();
return false;
});
if (jQuery(this).hasClass('search_ajax')) {
var ajax_timer = null;
jQuery(this).find('.search_field').keyup(function(e) {
"use strict";
var search_field = jQuery(this);
var s = search_field.val();
if (ajax_timer) {
clearTimeout(ajax_timer);
ajax_timer = null;
}
if (s.length >= THEMEREX_GLOBALS['ajax_search_min_length']) {
ajax_timer = setTimeout(function() {
jQuery.post(THEMEREX_GLOBALS['ajax_url'], {
action: 'ajax_search',
nonce: THEMEREX_GLOBALS['ajax_nonce'],
text: s
}).done(function(response) {
clearTimeout(ajax_timer);
ajax_timer = null;
var rez = JSON.parse(response);
if (rez.error === '') {
search_field.parents('.search_ajax').find('.search_results_content').empty().append(rez.data);
search_field.parents('.search_ajax').find('.search_results').fadeIn();
} else {
themerex_message_warning(THEMEREX_GLOBALS['strings']['search_error']);
}
});
}, THEMEREX_GLOBALS['ajax_search_delay']);
}
});
}
});
}
// Section Pan init
if (container.find('.sc_pan:not(.inited_pan)').length > 0) {
container.find('.sc_pan:not(.inited_pan)')
.each(function () {
"use strict";
if (jQuery(this).parents('div:hidden,article:hidden').length > 0) return;
var pan = jQuery(this).addClass('inited_pan');
var cont = pan.parent();
cont.mousemove(function(e) {
"use strict";
var anim = {};
var tm = 0;
var pw = pan.width(), ph = pan.height();
var cw = cont.width(), ch = cont.height();
var coff = cont.offset();
if (pan.hasClass('sc_pan_vertical'))
pan.css('top', -Math.floor((e.pageY - coff.top) / ch * (ph-ch)));
if (pan.hasClass('sc_pan_horizontal'))
pan.css('left', -Math.floor((e.pageX - coff.left) / cw * (pw-cw)));
});
cont.mouseout(function(e) {
pan.css({'left': 0, 'top': 0});
});
});
}
//Scroll
if (container.find('.sc_scroll:not(.inited)').length > 0) {
container.find('.sc_scroll:not(.inited)')
.each(function () {
"use strict";
if (jQuery(this).parents('div:hidden,article:hidden').length > 0) return;
THEMEREX_GLOBALS['scroll_init_counter'] = 0;
themerex_init_scroll_area(jQuery(this));
});
}
// Swiper Slider
if (container.find('.sc_slider_swiper:not(.inited)').length > 0) {
container.find('.sc_slider_swiper:not(.inited)')
.each(function () {
"use strict";
if (jQuery(this).parents('div:hidden,article:hidden').length > 0) return;
//if (jQuery(this).parents('.isotope_wrap:not(.inited)').length > 0) return;
jQuery(this).addClass('inited');
themerex_slider_autoheight(jQuery(this));
if (jQuery(this).parents('.sc_slider_pagination_area').length > 0) {
jQuery(this).parents('.sc_slider_pagination_area').find('.sc_slider_pagination .post_item').eq(0).addClass('active');
}
var id = jQuery(this).attr('id');
if (id == undefined) {
id = 'swiper_'+Math.random();
id = id.replace('.', '');
jQuery(this).attr('id', id);
}
jQuery(this).addClass(id);
jQuery(this).find('.slides .swiper-slide').css('position', 'relative');
if (THEMEREX_GLOBALS['swipers'] === undefined) THEMEREX_GLOBALS['swipers'] = {};
THEMEREX_GLOBALS['swipers'][id] = new Swiper('.'+id, {
calculateHeight: !jQuery(this).hasClass('sc_slider_height_fixed'),
resizeReInit: true,
autoResize: true,
loop: true,
grabCursor: true,
pagination: jQuery(this).hasClass('sc_slider_pagination') ? '#'+id+' .sc_slider_pagination_wrap' : false,
paginationClickable: true,
autoplay: jQuery(this).hasClass('sc_slider_noautoplay') ? false : (isNaN(jQuery(this).data('interval')) ? 7000 : jQuery(this).data('interval')),
autoplayDisableOnInteraction: false,
initialSlide: 0,
speed: 600,
// Autoheight on start
onFirstInit: function (slider){
var cont = jQuery(slider.container);
if (!cont.hasClass('sc_slider_height_auto')) return;
var li = cont.find('.swiper-slide').eq(1);
var h = li.data('height_auto');
if (h > 0) {
var pt = parseInt(li.css('paddingTop')), pb = parseInt(li.css('paddingBottom'));
li.height(h);
cont.height(h + (isNaN(pt) ? 0 : pt) + (isNaN(pb) ? 0 : pb));
cont.find('.swiper-wrapper').height(h + (isNaN(pt) ? 0 : pt) + (isNaN(pb) ? 0 : pb));
}
},
// Autoheight on slide change
onSlideChangeStart: function (slider){
var cont = jQuery(slider.container);
if (!cont.hasClass('sc_slider_height_auto')) return;
var idx = slider.activeIndex;
var li = cont.find('.swiper-slide').eq(idx);
var h = li.data('height_auto');
if (h > 0) {
var pt = parseInt(li.css('paddingTop')), pb = parseInt(li.css('paddingBottom'));
li.height(h);
cont.height(h + (isNaN(pt) ? 0 : pt) + (isNaN(pb) ? 0 : pb));
cont.find('.swiper-wrapper').height(h + (isNaN(pt) ? 0 : pt) + (isNaN(pb) ? 0 : pb));
}
},
// Change current item in 'full' or 'over' pagination wrap
onSlideChangeEnd: function (slider, dir) {
var cont = jQuery(slider.container);
if (cont.parents('.sc_slider_pagination_area').length > 0) {
var li = cont.parents('.sc_slider_pagination_area').find('.sc_slider_pagination .post_item');
var idx = slider.activeIndex > li.length ? 0 : slider.activeIndex-1;
themerex_change_active_pagination_in_slider(cont, idx);
}
}
});
jQuery(this).data('settings', {mode: 'horizontal'}); // VC hook
var curSlide = jQuery(this).find('.slides').data('current-slide');
if (curSlide > 0)
THEMEREX_GLOBALS['swipers'][id].swipeTo(curSlide-1);
themerex_prepare_slider_navi(jQuery(this));
});
}
//Skills init
if (container.find('.sc_skills_item:not(.inited)').length > 0) {
themerex_init_skills(container);
jQuery(window).scroll(function () { themerex_init_skills(container); });
}
//Skills type='arc' init
if (container.find('.sc_skills_arc:not(.inited)').length > 0) {
themerex_init_skills_arc(container);
jQuery(window).scroll(function () { themerex_init_skills_arc(container); });
}
// Tabs
if (container.find('.sc_tabs:not(.inited),.tabs_area:not(.inited)').length > 0) {
container.find('.sc_tabs:not(.inited),.tabs_area:not(.inited)').each(function () {
var init = jQuery(this).data('active');
if (isNaN(init)) init = 0;
else init = Math.max(0, init);
jQuery(this)
.addClass('inited')
.tabs({
active: init,
show: {
effect: 'fadeIn',
duration: 300
},
hide: {
effect: 'fadeOut',
duration: 300
},
create: function (event, ui) {
themerex_init_shortcodes(ui.panel);
if (window.themerex_init_hidden_elements) themerex_init_hidden_elements(ui.panel);
},
activate: function (event, ui) {
themerex_init_shortcodes(ui.newPanel);
if (window.themerex_init_hidden_elements) themerex_init_hidden_elements(ui.newPanel);
}
});
});
}
// Toggles
if (container.find('.sc_toggles .sc_toggles_title:not(.inited)').length > 0) {
container.find('.sc_toggles .sc_toggles_title:not(.inited)')
.addClass('inited')
.click(function () {
jQuery(this).toggleClass('ui-state-active').parent().toggleClass('sc_active');
jQuery(this).parent().find('.sc_toggles_content').slideToggle(300, function () {
themerex_init_shortcodes(jQuery(this).parent().find('.sc_toggles_content'));
if (window.themerex_init_hidden_elements) themerex_init_hidden_elements(jQuery(this).parent().find('.sc_toggles_content'));
});
});
}
//Zoom
if (container.find('.sc_zoom:not(.inited)').length > 0) {
container.find('.sc_zoom:not(.inited)')
.each(function () {
"use strict";
if (jQuery(this).parents('div:hidden,article:hidden').length > 0) return;
jQuery(this).addClass('inited');
jQuery(this).find('img').elevateZoom({
zoomType: "lens",
lensShape: "round",
lensSize: 200,
lensBorderSize: 4,
lensBorderColour: '#ccc'
});
});
}
}
// Scrolled areas
function themerex_init_scroll_area(obj) {
// Wait for images loading
if (!themerex_check_images_complete(obj) && THEMEREX_GLOBALS['scroll_init_counter']++ < 30) {
setTimeout(function() { themerex_init_scroll_area(obj); }, 200);
return;
}
// Start init scroll area
obj.addClass('inited');
var id = obj.attr('id');
if (id == undefined) {
id = 'scroll_'+Math.random();
id = id.replace('.', '');
obj.attr('id', id);
}
obj.addClass(id);
var bar = obj.find('#'+id+'_bar');
if (bar.length > 0 && !bar.hasClass(id+'_bar')) {
bar.addClass(id+'_bar');
}
// Init Swiper with scroll plugin
if (THEMEREX_GLOBALS['swipers'] === undefined) THEMEREX_GLOBALS['swipers'] = {};
THEMEREX_GLOBALS['swipers'][id] = new Swiper('.'+id, {
calculateHeight: false,
resizeReInit: true,
autoResize: true,
freeMode: true,
freeModeFluid: true,
grabCursor: true,
noSwiping: obj.hasClass('scroll-no-swiping'),
mode: obj.hasClass('sc_scroll_vertical') ? 'vertical' : 'horizontal',
slidesPerView: obj.hasClass('sc_scroll') ? 'auto' : 1,
mousewheelControl: true,
mousewheelAccelerator: 4, // Accelerate mouse wheel in Firefox 4+
scrollContainer: obj.hasClass('sc_scroll_vertical'),
scrollbar: {
container: '.'+id+'_bar',
hide: true,
draggable: true
}
})
obj.data('settings', {mode: 'horizontal'});
themerex_prepare_slider_navi(obj);
}
// Slider navigation
function themerex_prepare_slider_navi(slider) {
// Prev / Next
var navi = slider.find('> .sc_slider_controls_wrap, > .sc_scroll_controls_wrap');
if (navi.length == 0) navi = slider.siblings('.sc_slider_controls_wrap,.sc_scroll_controls_wrap');
if (navi.length > 0) {
navi.find('.sc_slider_prev,.sc_scroll_prev').click(function(e){
var swiper = jQuery(this).parents('.swiper-slider-container');
if (swiper.length == 0) swiper = jQuery(this).parents('.sc_slider_controls_wrap,.sc_scroll_controls_wrap').siblings('.swiper-slider-container');
var id = swiper.attr('id');
THEMEREX_GLOBALS['swipers'][id].swipePrev();
e.preventDefault();
return false;
});
navi.find('.sc_slider_next,.sc_scroll_next').click(function(e){
var swiper = jQuery(this).parents('.swiper-slider-container');
if (swiper.length == 0) swiper = jQuery(this).parents('.sc_slider_controls_wrap,.sc_scroll_controls_wrap').siblings('.swiper-slider-container');
var id = swiper.attr('id');
THEMEREX_GLOBALS['swipers'][id].swipeNext();
e.preventDefault();
return false;
});
}
// Pagination
navi = slider.siblings('.sc_slider_pagination');
if (navi.length > 0) {
navi.find('.post_item').click(function(e){
var swiper = jQuery(this).parents('.sc_slider_pagination_area').find('.swiper-slider-container');
var id = swiper.attr('id');
THEMEREX_GLOBALS['swipers'][id].swipeTo(jQuery(this).index());
e.preventDefault();
return false;
});
}
}
function themerex_change_active_pagination_in_slider(slider, idx) {
var pg = slider.parents('.sc_slider_pagination_area').find('.sc_slider_pagination');
if (pg.length==0) return;
pg.find('.post_item').removeClass('active').eq(idx).addClass('active');
var h = pg.height();
var off = pg.find('.active').offset().top - pg.offset().top;
var off2 = pg.find('.sc_scroll_wrapper').offset().top - pg.offset().top;
var h2 = pg.find('.active').height();
if (off < 0) {
pg.find('.sc_scroll_wrapper').css({'transform': 'translate3d(0px, 0px, 0px)', 'transition-duration': '0.3s'});
} else if (h <= off+h2) {
pg.find('.sc_scroll_wrapper').css({'transform': 'translate3d(0px, -'+(Math.abs(off2)+off-h/4)+'px, 0px)', 'transition-duration': '0.3s'});
}
}
// Sliders: Autoheight
function themerex_slider_autoheight(slider) {
if (slider.hasClass('.sc_slider_height_auto')) {
slider.find('.swiper-slide').each(function() {
if (jQuery(this).data('height_auto') == undefined) {
jQuery(this).attr('data-height_auto', jQuery(this).height());
}
});
}
}
// Skills init
function themerex_init_skills(container) {
if (arguments.length==0) var container = jQuery('body');
var scrollPosition = jQuery(window).scrollTop() + jQuery(window).height();
container.find('.sc_skills_item:not(.inited)').each(function () {
var skillsItem = jQuery(this);
var scrollSkills = skillsItem.offset().top;
if (scrollPosition > scrollSkills) {
skillsItem.addClass('inited');
var skills = skillsItem.parents('.sc_skills').eq(0);
var type = skills.data('type');
var total = (type=='pie' && skills.hasClass('sc_skills_compact_on')) ? skillsItem.find('.sc_skills_data .pie') : skillsItem.find('.sc_skills_total').eq(0);
var start = parseInt(total.data('start'));
var stop = parseInt(total.data('stop'));
var maximum = parseInt(total.data('max'));
var startPercent = Math.round(start/maximum*100);
var stopPercent = Math.round(stop/maximum*100);
var ed = total.data('ed');
var duration = parseInt(total.data('duration'));
var speed = parseInt(total.data('speed'));
var step = parseInt(total.data('step'));
if (type == 'bar') {
var dir = skills.data('dir');
var count = skillsItem.find('.sc_skills_count').eq(0);
if (dir=='horizontal')
count.css('width', startPercent + '%').animate({ width: stopPercent + '%' }, duration);
else if (dir=='vertical')
count.css('height', startPercent + '%').animate({ height: stopPercent + '%' }, duration);
themerex_animate_skills_counter(start, stop, speed-(dir!='unknown' ? 5 : 0), step, ed, total);
} else if (type == 'counter') {
themerex_animate_skills_counter(start, stop, speed - 5, step, ed, total);
} else if (type == 'pie') {
var steps = parseInt(total.data('steps'));
var bg_color = total.data('bg_color');
var border_color = total.data('border_color');
var cutout = parseInt(total.data('cutout'));
var easing = total.data('easing');
var options = {
segmentShowStroke: true,
segmentStrokeColor: border_color,
segmentStrokeWidth: 1,
percentageInnerCutout : cutout,
animationSteps: steps,
animationEasing: easing,
animateRotate: true,
animateScale: false,
};
var pieData = [];
total.each(function() {
var color = jQuery(this).data('color');
var stop = parseInt(jQuery(this).data('stop'));
var stopPercent = Math.round(stop/maximum*100);
pieData.push({
value: stopPercent,
color: color
});
});
if (total.length == 1) {
themerex_animate_skills_counter(start, stop, Math.round(1500/steps), step, ed, total);
pieData.push({
value: 100-stopPercent,
color: bg_color
});
}
var canvas = skillsItem.find('canvas');
canvas.attr({width: skillsItem.width(), height: skillsItem.width()}).css({width: skillsItem.width(), height: skillsItem.height()});
new Chart(canvas.get(0).getContext("2d")).Doughnut(pieData, options);
}
}
});
}
// Skills counter animation
function themerex_animate_skills_counter(start, stop, speed, step, ed, total) {
start = Math.min(stop, start + step);
total.text(start+ed);
if (start < stop) {
setTimeout(function () {
themerex_animate_skills_counter(start, stop, speed, step, ed, total);
}, speed);
}
}
// Skills arc init
function themerex_init_skills_arc(container) {
if (arguments.length==0) var container = jQuery('body');
container.find('.sc_skills_arc:not(.inited)').each(function () {
var arc = jQuery(this);
arc.addClass('inited');
var items = arc.find('.sc_skills_data .arc');
var canvas = arc.find('.sc_skills_arc_canvas').eq(0);
var legend = arc.find('.sc_skills_legend').eq(0);
var w = Math.round(arc.width() - legend.width());
var c = Math.floor(w/2);
var o = {
random: function(l, u){
return Math.floor((Math.random()*(u-l+1))+l);
},
diagram: function(){
var r = Raphael(canvas.attr('id'), w, w),
rad = hover = Math.round(w/2/items.length),
step = Math.round(((w-20)/2-rad)/items.length),
stroke = Math.round(w/9/items.length),
speed = 400;
r.circle(c, c, Math.round(w/2)).attr({ stroke: 'none', fill: THEMEREX_GLOBALS['theme_skin_bg'] ? THEMEREX_GLOBALS['theme_skin_bg'] : '#ffffff' });
var title = r.text(c, c, arc.data('subtitle')).attr({
font: 'lighter '+Math.round(rad*0.7)+'px "'+THEMEREX_GLOBALS['theme_font']+'"',
fill: '#888888'
}).toFront();
rad -= Math.round(step/2);
r.customAttributes.arc = function(value, color, rad){
var v = 3.6 * value,
alpha = v == 360 ? 359.99 : v,
rand = o.random(91, 240),
a = (rand-alpha) * Math.PI/180,
b = rand * Math.PI/180,
sx = c + rad * Math.cos(b),
sy = c - rad * Math.sin(b),
x = c + rad * Math.cos(a),
y = c - rad * Math.sin(a),
path = [['M', sx, sy], ['A', rad, rad, 0, +(alpha > 180), 1, x, y]];
return { path: path, stroke: color }
}
items.each(function(i){
var t = jQuery(this),
color = t.find('.color').val(),
value = t.find('.percent').val(),
text = t.find('.text').text();
rad += step;
var z = r.path().attr({ arc: [value, color, rad], 'stroke-width': stroke });
z.mouseover(function(){
this.animate({ 'stroke-width': hover, opacity: .75 }, 1000, 'elastic');
if (Raphael.type != 'VML') //solves IE problem
this.toFront();
title.stop().animate({ opacity: 0 }, speed, '>', function(){
this.attr({ text: (text ? text + '\n' : '') + value + '%' }).animate({ opacity: 1 }, speed, '<');
});
}).mouseout(function(){
this.stop().animate({ 'stroke-width': stroke, opacity: 1 }, speed*4, 'elastic');
title.stop().animate({ opacity: 0 }, speed, '>', function(){
title.attr({ text: arc.data('subtitle') }).animate({ opacity: 1 }, speed, '<');
});
});
});
}
}
o.diagram();
});
}
// Countdown update
function themerex_countdown(dt) {
var counter = jQuery(this).parent();
for (var i=3; i<dt.length; i++) {
var v = (dt[i]<10 ? '0' : '') + dt[i];
counter.find('.sc_countdown_item').eq(i-3).find('.sc_countdown_digits span').addClass('hide');
for (var ch=v.length-1; ch>=0; ch--) {
counter.find('.sc_countdown_item').eq(i-3).find('.sc_countdown_digits span').eq(ch+(i==3 && v.length<3 ? 1 : 0)).removeClass('hide').text(v.substr(ch, 1));
}
}
} | 35.696118 | 195 | 0.630789 |
3dc3551a7280bb0d3d33aaf23e2e80b17ca03e33 | 249 | js | JavaScript | src/crud/delete.js | prince-neres/adopt-dogs | a5b15ba841fca553f939062a1ec40903ed41dad1 | [
"MIT"
] | null | null | null | src/crud/delete.js | prince-neres/adopt-dogs | a5b15ba841fca553f939062a1ec40903ed41dad1 | [
"MIT"
] | null | null | null | src/crud/delete.js | prince-neres/adopt-dogs | a5b15ba841fca553f939062a1ec40903ed41dad1 | [
"MIT"
] | null | null | null | const remove = (id) => {
$(`#${id}`).parent().parent().parent().fadeOut();
$.ajax({
url: "http://localhost:3000/dogs/delete",
type: "DELETE",
data: JSON.stringify({
id: id,
}),
contentType: "application/json",
});
};
| 20.75 | 51 | 0.526104 |
3dc41430c7388c508708042a5604bdb870585ef6 | 1,983 | js | JavaScript | client/views/directory/DirectoryPage.js | djcruz93/Rocket.Chat | b1a9d229c0fc292ed2f4b3423b8b820d6b88001f | [
"MIT"
] | null | null | null | client/views/directory/DirectoryPage.js | djcruz93/Rocket.Chat | b1a9d229c0fc292ed2f4b3423b8b820d6b88001f | [
"MIT"
] | null | null | null | client/views/directory/DirectoryPage.js | djcruz93/Rocket.Chat | b1a9d229c0fc292ed2f4b3423b8b820d6b88001f | [
"MIT"
] | 1 | 2021-03-26T06:38:31.000Z | 2021-03-26T06:38:31.000Z | import { Tabs } from '@rocket.chat/fuselage';
import React, { useEffect, useCallback } from 'react';
import Page from '../../components/Page';
import { useRoute, useRouteParameter } from '../../contexts/RouterContext';
import { useSetting } from '../../contexts/SettingsContext';
import { useTranslation } from '../../contexts/TranslationContext';
import ChannelsTab from './ChannelsTab';
import TeamsTab from './TeamsTab';
import UserTab from './UserTab';
function DirectoryPage() {
const t = useTranslation();
const defaultTab = useSetting('Accounts_Directory_DefaultView');
const federationEnabled = useSetting('FEDERATION_Enabled');
const tab = useRouteParameter('tab');
const directoryRoute = useRoute('directory');
const handleTabClick = useCallback((tab) => () => directoryRoute.push({ tab }), [directoryRoute]);
useEffect(() => {
if (!tab || (tab === 'external' && !federationEnabled)) {
return directoryRoute.replace({ tab: defaultTab });
}
}, [directoryRoute, tab, federationEnabled, defaultTab]);
return (
<Page>
<Page.Header title={t('Directory')} />
<Tabs flexShrink={0}>
<Tabs.Item selected={tab === 'channels'} onClick={handleTabClick('channels')}>
{t('Channels')}
</Tabs.Item>
<Tabs.Item selected={tab === 'users'} onClick={handleTabClick('users')}>
{t('Users')}
</Tabs.Item>
<Tabs.Item selected={tab === 'teams'} onClick={handleTabClick('teams')}>
{t('Teams')}
</Tabs.Item>
{federationEnabled && (
<Tabs.Item selected={tab === 'external'} onClick={handleTabClick('external')}>
{t('External_Users')}
</Tabs.Item>
)}
</Tabs>
<Page.Content>
{(tab === 'users' && <UserTab />) ||
(tab === 'channels' && <ChannelsTab />) ||
(tab === 'teams' && <TeamsTab />) ||
(federationEnabled && tab === 'external' && <UserTab workspace='external' />)}
</Page.Content>
</Page>
);
}
DirectoryPage.displayName = 'DirectoryPage';
export default DirectoryPage;
| 31.983871 | 99 | 0.645487 |
3dc46c01f9dcf98f505760052186e846d0f27405 | 11,865 | js | JavaScript | skyline/components/com_jce/editor/tiny_mce/plugins/upload/editor_plugin.js | rchavezriosjr/SkyLineWebPage | 76e71a278f9473e5e969190b98bdfbddb9fcaa49 | [
"MIT"
] | null | null | null | skyline/components/com_jce/editor/tiny_mce/plugins/upload/editor_plugin.js | rchavezriosjr/SkyLineWebPage | 76e71a278f9473e5e969190b98bdfbddb9fcaa49 | [
"MIT"
] | null | null | null | skyline/components/com_jce/editor/tiny_mce/plugins/upload/editor_plugin.js | rchavezriosjr/SkyLineWebPage | 76e71a278f9473e5e969190b98bdfbddb9fcaa49 | [
"MIT"
] | null | null | null | /* jce - 2.7.14 | 2019-06-13 | https://www.joomlacontenteditor.net | Copyright (C) 2006 - 2019 Ryan Demmer. All rights reserved | GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html */
!function(){function uid(){var i,guid=(new Date).getTime().toString(32);for(i=0;i<5;i++)guid+=Math.floor(65535*Math.random()).toString(32);return"wf_"+guid+(counter++).toString(32)}var each=tinymce.each,extend=tinymce.extend,JSON=tinymce.util.JSON,RangeUtils=tinymce.dom.RangeUtils,counter=0,supportDragDrop=!!(window.ProgressEvent&&window.FileReader&&window.FormData)&&!tinymce.isOpera,mimes={};!function(mime_data){var i,y,ext,items=mime_data.split(/,/);for(i=0;i<items.length;i+=2)for(ext=items[i+1].split(/ /),y=0;y<ext.length;y++)mimes[ext[y]]=items[i]}("application/msword,doc dot,application/pdf,pdf,application/pgp-signature,pgp,application/postscript,ps ai eps,application/rtf,rtf,application/vnd.ms-excel,xls xlb,application/vnd.ms-powerpoint,ppt pps pot,application/zip,zip,application/x-shockwave-flash,swf swfl,application/vnd.openxmlformats-officedocument.wordprocessingml.document,docx,application/vnd.openxmlformats-officedocument.wordprocessingml.template,dotx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,xlsx,application/vnd.openxmlformats-officedocument.presentationml.presentation,pptx,application/vnd.openxmlformats-officedocument.presentationml.template,potx,application/vnd.openxmlformats-officedocument.presentationml.slideshow,ppsx,application/x-javascript,js,application/json,json,audio/mpeg,mpga mpega mp2 mp3,audio/x-wav,wav,audio/mp4,m4a,image/bmp,bmp,image/gif,gif,image/jpeg,jpeg jpg jpe,image/photoshop,psd,image/png,png,image/svg+xml,svg svgz,image/tiff,tiff tif,text/plain,asc txt text diff log,text/html,htm html xhtml,text/css,css,text/csv,csv,text/rtf,rtf,video/mpeg,mpeg mpg mpe,video/quicktime,qt mov,video/mp4,mp4,video/x-m4v,m4v,video/x-flv,flv,video/x-ms-wmv,wmv,video/avi,avi,video/webm,webm,video/vnd.rn-realvideo,rv,application/vnd.oasis.opendocument.formula-template,otf,application/octet-stream,exe");var state={STOPPED:1,STARTED:2,QUEUED:1,UPLOADING:2,FAILED:4,DONE:5,GENERIC_ERROR:-100,HTTP_ERROR:-200,IO_ERROR:-300,SECURITY_ERROR:-400};tinymce.create("tinymce.plugins.Upload",{files:[],plugins:[],init:function(ed,url){function cancel(){ed.dom.bind(ed.getBody(),"dragover",function(e){var dataTransfer=e.dataTransfer;dataTransfer&&dataTransfer.files&&dataTransfer.files.length&&e.preventDefault()}),ed.dom.bind(ed.getBody(),"drop",function(e){var dataTransfer=e.dataTransfer;dataTransfer&&dataTransfer.files&&dataTransfer.files.length&&e.preventDefault()})}var self=this;self.editor=ed,self.plugin_url=url,ed.onPreInit.add(function(){each(ed.plugins,function(o,k){ed.getParam(k+"_upload")&&tinymce.is(o.getUploadURL,"function")&&tinymce.is(o.insertUploadedFile,"function")&&self.plugins.push(o)}),ed.settings.compress.css||ed.dom.loadCSS(url+"/css/content.css"),ed.parser.addNodeFilter("img",function(nodes){for(var node,cls,data,i=nodes.length;i--;)node=nodes[i],cls=node.attr("class"),data=node.attr("data-mce-upload-marker"),(cls&&cls.indexOf("upload-placeholder")!=-1||data)&&(0==self.plugins.length?node.remove():self._createUploadMarker(node))}),ed.serializer.addNodeFilter("img",function(nodes){for(var node,cls,i=nodes.length;i--;)node=nodes[i],cls=node.attr("class"),cls&&/mce-item-uploadmarker/.test(cls)&&(cls=cls.replace(/(?:^|\s)mce-item-(upload|uploadmarker)(?!\S)/g,""),cls+=" upload-placeholder",node.attr({"data-mce-src":"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",class:tinymce.trim(cls)}))})}),ed.onInit.add(function(){function bindUploadEvents(ed){each(ed.dom.select("img.mce-item-uploadmarker",ed.getBody()),function(n){0==self.plugins.length?ed.dom.remove(n):self._bindUploadMarkerEvents(ed,n)})}function cancelEvent(e){e.preventDefault(),e.stopPropagation()}return supportDragDrop?0==self.plugins.length?void cancel():(ed.selection.onSetContent.add(function(){bindUploadEvents(ed)}),ed.onSetContent.add(function(){bindUploadEvents(ed)}),ed.onFullScreen&&ed.onFullScreen.add(function(editor){bindUploadEvents(editor)}),ed.dom.bind(ed.getBody(),"dragover",function(e){e.dataTransfer.dropEffect=tinymce.VK.metaKeyPressed(e)?"copy":"move"}),void ed.dom.bind(ed.getBody(),"drop",function(e){var dataTransfer=e.dataTransfer;dataTransfer&&dataTransfer.files&&dataTransfer.files.length&&(each(dataTransfer.files,function(file){var rng=RangeUtils.getCaretRangeFromPoint(e.clientX,e.clientY,ed.getDoc());rng&&(ed.selection.setRng(rng),rng=null),self.addFile(file)}),cancelEvent(e)),self.files.length&&each(self.files,function(file){self.upload(file)}),tinymce.isGecko&&"IMG"==e.target.nodeName&&cancelEvent(e)})):void cancel()}),self.FilesAdded=new tinymce.util.Dispatcher(this),self.UploadProgress=new tinymce.util.Dispatcher(this),self.FileUploaded=new tinymce.util.Dispatcher(this),self.UploadError=new tinymce.util.Dispatcher(this),this.settings={multipart:!0,multi_selection:!0,file_data_name:"file",filters:[]},self.FileUploaded.add(function(file,o){function showError(error){return ed.windowManager.alert(error||ed.getLang("upload.response_error","Invalid Upload Response")),ed.dom.remove(n),!1}var s,n=file.marker;if(n){if(!o||!o.response)return showError();var r,data=o.response;try{r=JSON.parse(data)}catch(e){return data.indexOf("{")!==-1&&(data="The server returned an invalid JSON response."),showError()}if(!r||!r.result)return showError();if(r.error){var txt=r.text||r.error;return ed.windowManager.alert(txt),ed.dom.remove(n),!1}if(file.status==state.DONE){if(file.uploader){var u=file.uploader,files=r.result.files||[],item=files.length?files[0]:{},obj=tinymce.extend({type:file.type,name:file.name},item);if(s=u.insertUploadedFile(obj)){var styles=ed.dom.getAttrib(n,"data-mce-style");if(styles&&(styles=ed.dom.styles.parse(styles),ed.dom.setStyles(s,styles)),ed.dom.hasClass(n,"mce-item-uploadmarker")&&ed.dom.setAttribs(s,{width:n.width||s.width,height:n.height||s.height}),ed.dom.replace(s,n))return ed.nodeChanged(),!0}}self.files.splice(tinymce.inArray(self.files,file),1)}ed.dom.remove(n)}}),self.UploadError.add(function(o){ed.windowManager.alert(o.code+" : "+o.message),o.file&&o.file.marker&&ed.dom.remove(o.file.marker)})},_bindUploadMarkerEvents:function(ed,marker){function removeUpload(){dom.setStyles("wf_upload_button",{top:"",left:"",display:"none",zIndex:""})}var self=this,dom=tinymce.DOM;ed.onNodeChange.add(removeUpload),ed.dom.bind(ed.getWin(),"scroll",removeUpload);var input=dom.get("wf_upload_input");if(!input){var btn=dom.add(dom.doc.body,"div",{id:"wf_upload_button",title:ed.getLang("upload.button_description","Click to upload a file")},'<label for="wf_upload_input">'+ed.getLang("upload.label","Upload")+"</label>");input=dom.add(btn,"input",{type:"file",id:"wf_upload_input"})}ed.dom.bind(marker,"mouseover",function(e){if(!ed.dom.getAttrib(marker,"data-mce-selected")){var vp=ed.dom.getViewPort(ed.getWin()),p1=dom.getRect(ed.getContentAreaContainer()),p2=ed.dom.getRect(marker);if(!(vp.y>p2.y+p2.h/2-25||vp.y<p2.y+p2.h/2+25-p1.h)){var x=Math.max(p2.x-vp.x,0)+p1.x,y=Math.max(p2.y-vp.y,0)+p1.y-Math.max(vp.y-p2.y,0),zIndex="mce_fullscreen"==ed.id?dom.get("mce_fullscreen_container").style.zIndex:0;dom.setStyles("wf_upload_button",{top:y+p2.h/2-27,left:x+p2.w/2-54,display:"block",zIndex:zIndex+1}),input.onchange=function(){if(input.files){var file=input.files[0];file&&(file.marker=marker,self.addFile(file)&&(ed.dom.addClass(marker,"loading"),self.upload(file),removeUpload()))}}}}}),ed.dom.bind(marker,"mouseout",function(e){!e.relatedTarget&&e.clientY>0||removeUpload()})},_createUploadMarker:function(n){var styles,ed=this.editor,src=n.attr("src")||"",style={},cls=[];if(!n.attr("alt")&&!/data:image/.test(src)){var alt=src.substring(src.length,src.lastIndexOf("/")+1);n.attr("alt",alt)}n.attr("style")&&(style=ed.dom.styles.parse(n.attr("style"))),n.attr("hspace")&&(style["margin-left"]=style["margin-right"]=n.attr("hspace")),n.attr("vspace")&&(style["margin-top"]=style["margin-bottom"]=n.attr("vspace")),n.attr("align")&&(style.float=n.attr("align")),n.attr("class")&&(cls=n.attr("class").replace(/\s*upload-placeholder\s*/,"").split(" ")),cls.push("mce-item-upload"),cls.push("mce-item-uploadmarker"),n.attr({src:"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",class:tinymce.trim(cls.join(" "))});var tmp=ed.dom.create("span",{style:style});(styles=ed.dom.getAttrib(tmp,"style"))&&n.attr({style:styles,"data-mce-style":styles})},buildUrl:function(url,items){var query="";return each(items,function(value,name){query+=(query?"&":"")+encodeURIComponent(name)+"="+encodeURIComponent(value)}),query&&(url+=(url.indexOf("?")>0?"&":"?")+query),url},addFile:function(file){var url,ed=this.editor,self=this;if(/\.(php|php(3|4|5)|phtml|pl|py|jsp|asp|htm|html|shtml|sh|cgi)\./i.test(file.name))return ed.windowManager.alert(ed.getLang("upload.file_extension_error","File type not supported")),!1;if(each(self.plugins,function(o,k){file.upload_url||(url=o.getUploadURL(file))&&(file.upload_url=url,file.uploader=o)}),file.upload_url){if(tinymce.is(file.uploader.getUploadConfig,"function")){var config=file.uploader.getUploadConfig();if(!new RegExp(".("+config.filetypes.join("|")+")$","i").test(file.name))return ed.windowManager.alert(ed.getLang("upload.file_extension_error","File type not supported")),!1;if(file.size){var max=parseInt(config.max_size)||1024;if(file.size>1024*max)return ed.windowManager.alert(ed.getLang("upload.file_size_error","File size exceeds maximum allowed size")),!1}}if(self.FilesAdded.dispatch(file),!file.marker){var w=300,h=300;ed.execCommand("mceInsertContent",!1,'<img id="__mce_tmp" class="mce-item-upload" />',{skip_undo:1}),/image\/(gif|png|jpeg|jpg)/.test(file.type)&&(w=h=Math.round(Math.sqrt(file.size)),w=Math.max(100,w),h=Math.max(100,h));var n=ed.dom.get("__mce_tmp");ed.dom.setAttrib(n,"id",""),n.style.width=w+"px",n.style.height=h+"px",file.marker=n}return ed.undoManager.add(),self.files.push(file),!0}return ed.windowManager.alert(ed.getLang("upload.file_extension_error","File type not supported")),!1},upload:function(file){function sendFile(bin){var xhr=new XMLHttpRequest,formData=new FormData;xhr.upload&&(xhr.upload.onprogress=function(e){e.lengthComputable&&(file.loaded=Math.min(file.size,e.loaded),self.UploadProgress.dispatch(file))}),xhr.onreadystatechange=function(){var httpStatus;if(4==xhr.readyState&&self.state!==state.STOPPED){try{httpStatus=xhr.status}catch(ex){httpStatus=0}httpStatus>=400?self.UploadError.dispatch({code:state.HTTP_ERROR,message:ed.getLang("upload.http_error","HTTP Error"),file:file,status:httpStatus}):(file.loaded=file.size,self.UploadProgress.dispatch(file),bin=formData=null,file.status=state.DONE,self.FileUploaded.dispatch(file,{response:xhr.responseText,status:httpStatus}))}};var name=file.target_name||file.name;name=name.replace(/[\+\\\/\?\#%&<>"\'=\[\]\{\},;@\^\(\)£€$]/g,""),extend(args,{name:name}),xhr.open("post",url,!0),each(self.settings.headers,function(value,name){xhr.setRequestHeader(name,value)}),each(extend(args,self.settings.multipart_params),function(value,name){formData.append(name,value)}),formData.append(self.settings.file_data_name,bin),xhr.send(formData)}var self=this,ed=this.editor,args={method:"upload",id:uid(),inline:1,component_id:ed.settings.component_id};args[ed.settings.token]="1";var url=file.upload_url;file.status!=state.DONE&&file.status!=state.FAILED&&self.state!=state.STOPPED&&(extend(args,{name:file.target_name||file.name}),sendFile(file))},getInfo:function(){return{longname:"Drag & Drop and Placeholder Upload",author:"Ryan Demmer",authorurl:"https://www.joomlacontenteditor.net",infourl:"https://www.joomlacontenteditor.net",version:"@@version@@"}}}),tinymce.PluginManager.add("upload",tinymce.plugins.Upload)}(); | 5,932.5 | 11,662 | 0.761231 |
3dc4e848033c1c2d97eb598d975c3dc77e3d6861 | 822 | js | JavaScript | src/greedy/models/tree.js | aperezliano/algorithms | 6beff10aca4322a1c90af4c37189349668cfe935 | [
"MIT"
] | null | null | null | src/greedy/models/tree.js | aperezliano/algorithms | 6beff10aca4322a1c90af4c37189349668cfe935 | [
"MIT"
] | null | null | null | src/greedy/models/tree.js | aperezliano/algorithms | 6beff10aca4322a1c90af4c37189349668cfe935 | [
"MIT"
] | null | null | null | module.exports = class Tree {
#root;
constructor(value) {
this.#root = new Node(value);
}
merge(b) {
this.#root = new Node(null, this.#root, b.getRoot());
return this;
}
getRoot() {
return this.#root;
}
getNodesMap() {
return this.#getNodesMapRec(this.#root, new Map(), []);
}
#getNodesMapRec(node, map, code) {
if (node.leftChild) {
map = this.#getNodesMapRec(node.leftChild, map, `${code}0`);
}
if (node.rightChild) {
map = this.#getNodesMapRec(node.rightChild, map, `${code}1`);
}
if (!node.leftChild && !node.rightChild) {
map.set(node.value, code);
}
return map;
}
};
class Node {
constructor(value, leftChild, rightChild) {
this.value = value;
this.leftChild = leftChild;
this.rightChild = rightChild;
}
}
| 19.571429 | 67 | 0.590024 |
3dc5cec508e8264a4fbb9b2dc03ffc17ec754fac | 1,151 | js | JavaScript | src/redux/eyeCheckDataSlice.js | FlamingPika/Wilson_ForeSee | ba28a1b62a133e0481ed024b978b944d6e698d34 | [
"MIT"
] | null | null | null | src/redux/eyeCheckDataSlice.js | FlamingPika/Wilson_ForeSee | ba28a1b62a133e0481ed024b978b944d6e698d34 | [
"MIT"
] | null | null | null | src/redux/eyeCheckDataSlice.js | FlamingPika/Wilson_ForeSee | ba28a1b62a133e0481ed024b978b944d6e698d34 | [
"MIT"
] | null | null | null | import { createSlice } from "@reduxjs/toolkit";
import moment from "moment";
const initialState = {
date: moment().startOf("day"),
height: 0,
glassesName: "",
vau: {
od: 0,
os: 0,
},
vaa: {
od: 0,
os: 0,
},
sph: {
od: 0,
os: 0,
},
cyl: {
od: 0,
os: 0,
},
axis: {
od: 0,
os: 0,
},
pd: 0,
};
/**
* Slice for eye check data
*/
export const eyeCheckDataSlice = createSlice({
name: "eyeCheckData",
// TODO default height and age should use current member values
initialState,
reducers: {
set: (state, action) => {
const payload = action.payload;
const updated = Object.keys(payload).map((key) => {
const value = payload[key];
if (value instanceof Object)
return { [key]: Object.assign(state[key], value) };
else return { [key]: value };
});
return Object.assign(state, ...updated);
},
reset: () => initialState,
print: (state) => console.debug(JSON.stringify(state, null, 2)),
},
});
export const { set, get, reset, print } = eyeCheckDataSlice.actions;
export default eyeCheckDataSlice.reducer;
| 19.183333 | 68 | 0.569939 |
3dc5e61649ab1c0c0dda3711218bb80fefd964c9 | 772 | js | JavaScript | src/graphql/queries/user/UserByUsernameQuery.js | cebartling/gummi-bears-web | e029d87d5d23e8f8a469cc03d440524fa3d179a9 | [
"MIT"
] | null | null | null | src/graphql/queries/user/UserByUsernameQuery.js | cebartling/gummi-bears-web | e029d87d5d23e8f8a469cc03d440524fa3d179a9 | [
"MIT"
] | 6 | 2021-03-24T19:39:43.000Z | 2022-02-19T00:33:11.000Z | src/graphql/queries/user/UserByUsernameQuery.js | cebartling/gummi-bears-web | e029d87d5d23e8f8a469cc03d440524fa3d179a9 | [
"MIT"
] | null | null | null | import {gql} from '@apollo/client';
const UserByUsernameQuery = gql`
query UserByUsername($username: String!) {
userByUsername(username: $username) {
id
firstName
lastName
username
userStocks {
id
stock {
id
name
symbol
latestDailyTimeSeriesEvent {
id
eventDate
openPrice
closePrice
highPrice
lowPrice
volume
}
}
}
}
}
`;
export default UserByUsernameQuery;
| 24.125 | 48 | 0.365285 |