text
stringlengths 2
1.05M
|
|---|
jest.dontMock('./NewspaperArticleForm');
import NewspaperArticleForm from './NewspaperArticleForm';
function setup(testProps = {}) {
const props = {
...testProps,
submitting: testProps.submitting || false, // : PropTypes.bool,
};
return getElement(NewspaperArticleForm, props);
}
describe('NewspaperArticleForm renders ', () => {
it('component', () => {
const wrapper = setup();
expect(toJson(wrapper)).toMatchSnapshot();
});
it('component with 8 input fields', () => {
const wrapper = setup();
expect(wrapper.find('Field').length).toEqual(8);
});
it('component with all fields disabled', () => {
const wrapper = setup({ submitting: true });
wrapper.find('Field').forEach(field => {
expect(field.props().disabled).toEqual(true);
});
});
});
|
/**
* Copyright (c) Human Brain Project
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from "react";
import View from "./_View";
import { GenericList, ActionIcon } from "hbp-quickfire";
import { Col, Row } from "react-bootstrap";
import injectStyles from "react-jss";
import countryInfos from "../MockupData/CountryInfos.json";
import SyntaxHighlighter from "react-syntax-highlighter/prism-light";
import darcula from "react-syntax-highlighter/styles/prism/darcula";
import { stripIndent } from "common-tags";
const properties = [
[`items`, `array`, `[]`, `Array of items to be displayed`],
[`expanded`, `boolean`, `false`, `Flag that determines if the panel is expanded by default`],
[`itemTitle`, `object`, `({ item }) => item`, `React component to render the title for individual items. Gets passed the item to be rendered as a prop`],
[`itemBody`, `object`, `null`, `react component to render the body for individual items. Gets passed the item to be rendered as a prop. Only necessary if you want a body to be displayed`],
[`actions`, `array`, `[]`, `An array of actions. An actions can be any react components that get rendered in the top right corner of the panel. For callback, implement the onClick which gets called with the selected item`],
];
let styles = {
h4: {
marginTop:"15px",
}
};
@injectStyles(styles)
export default class GenericListView extends View {
constructor(props) {
super(props);
}
render() {
const { classes } = this.props;
return (
<div>
<h2>Generic List</h2>
<p>A flexible generic list components that allows the display of a list of items</p>
<h3>Properties:</h3>
<View.ShowInfoProperties properties={properties} />
<h3>Examples:</h3>
<h4 className={classes.h4}>Basic usage</h4>
<Col xs={12}>
<GenericList items={[1, 2, 3]} />
<SyntaxHighlighter
language="jsx"
style={darcula}
>{`<GenericList items={[1, 2, 3]} />`}</SyntaxHighlighter>
</Col>
<Row/>
<h4 className={classes.h4}>Complex Example</h4>
<p>This example shows a list with an item body and actions</p>
<Col xs={12}>
<GenericList
items={countryInfos}
itemTitle={({ item }) => (
<div>
{item.name}
<br />
<span style={{ color: "gray", fontStyle: "italic" }}>
{`Population: ${item.inhabitants}`}
</span>
</div>
)}
itemBody={({ item }) => `Country Motto: ${item.motto}`}
expanded={true}
actions={[
<ActionIcon
icon={"heart-empty"}
style={{ color: "red" }}
onClick={item =>
alert(`Hi we're ${item.name} our motto is: ${item.motto}`)
}
/>
]}
/>
<SyntaxHighlighter language="jsx" style={darcula}>{stripIndent`
<GenericList
items={countryInfos}
itemTitle={({ item }) => (
<div>
{item.name}
<br />
<span style={{ color: "gray", fontStyle: "italic" }}>
{\`Population: \${item.inhabitants}\`}
</span>
</div>
)}
itemBody={({ item }) => \`Country Motto: \${item.motto}\`}
expanded={true}
actions={[
<ActionIcon
icon={"heart-empty"}
style={{ color: "red" }}
onClick={item =>
alert(\`Hi we're \${item.name} our motto is: \${item.motto}\`)
}
/>
]}
/>`}</SyntaxHighlighter>
</Col>
</div>
);
}
}
|
/* ------------------------------------------------------------------------------
*
* # D3.js - stacked and multiple bars
*
* Demo d3.js bar chart setup with animated transition between stacked and multiple bars
*
* Version: 1.0
* Latest update: August 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function () {
// Create Uniform checkbox
$(".stacked-multiple").uniform({
radioClass: 'choice'
});
// Initialize chart
stackedMultiples('#d3-bar-stacked-multiples', 400);
// Chart setup
function stackedMultiples(element, height) {
// Basic setup
// ------------------------------
// Define main variables
var d3Container = d3.select(element),
margin = {top: 5, right: 20, bottom: 20, left: 60},
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
height = height - margin.top - margin.bottom - 5;
// Format data
var parseDate = d3.time.format("%Y-%m").parse,
formatYear = d3.format("02d"),
formatDate = function(d) { return "Q" + ((d.getMonth() / 3 | 0) + 1) + formatYear(d.getFullYear() % 100); };
// Construct scales
// ------------------------------
// Horizontal
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .2);
// Vertical
var y = d3.scale.ordinal()
.rangeRoundBands([height, 0]);
var y0 = d3.scale.ordinal()
.rangeRoundBands([height, 0]);
var y1 = d3.scale.linear();
// Colors
var color = d3.scale.category20();
// Create axes
// ------------------------------
// Horizontal
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(formatDate);
// Vertical
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10, "%");
// Create chart
// ------------------------------
// Add SVG element
var container = d3Container.append("svg");
// Add SVG group
var svg = container
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Construct chart layout
// ------------------------------
// Nest
var nest = d3.nest()
.key(function(d) { return d.browser; });
// Stack
var stack = d3.layout.stack()
.values(function(d) { return d.values; })
.x(function(d) { return d.date; })
.y(function(d) { return d.value; })
.out(function(d, y0) { d.valueOffset = y0; });
// Load data
// ------------------------------
d3.tsv("assets/demo_data/d3/bars/bars_stacked_multiple.tsv", function(error, data) {
// Pull out values
data.forEach(function(d) {
d.date = parseDate(d.date);
d.value = +d.value;
});
// Nest values
var dataByGroup = nest.entries(data);
// Set input domains
// ------------------------------
// Stack
stack(dataByGroup);
// Horizontal
x.domain(dataByGroup[0].values.map(function(d) { return d.date; }));
// Vertical
y0.domain(dataByGroup.map(function(d) { return d.key; }));
y1.domain([0, d3.max(data, function(d) { return d.value; })]).range([y0.rangeBand(), 0]);
//
// Append chart elements
//
// Add bars
// ------------------------------
// Group bars
var group = svg.selectAll(".d3-bar-group")
.data(dataByGroup)
.enter()
.append("g")
.attr("class", "d3-bar-group")
.attr("transform", function(d) { return "translate(0," + y0(d.key) + ")"; });
// Append text
group.append("text")
.attr("class", "d3-group-label")
.attr("x", -12)
.attr("y", function(d) { return y1(d.values[0].value / 2); })
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d.key; });
// Add bars
group.selectAll(".d3-bar")
.data(function(d) { return d.values; })
.enter()
.append("rect")
.attr("class", "d3-bar")
.attr("x", function(d) { return x(d.date); })
.attr("y", function(d) { return y1(d.value); })
.attr("width", x.rangeBand())
.attr("height", function(d) { return y0.rangeBand() - y1(d.value); })
.style("fill", function(d) { return color(d.browser); });
// Append axes
// ------------------------------
// Horizontal
group.filter(function(d, i) { return !i; }).append("g")
.attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
.attr("transform", "translate(0," + (y0.rangeBand() + 1) + ")")
.call(xAxis);
// Vertical
var verticalAxis = svg.append("g")
.attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
.call(yAxis);
// Appent text label
verticalAxis.append("text")
.attr('class', 'browser-label')
.attr("x", -12)
.attr("y", 12)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("fill", "#999")
.style("font-size", 12)
.text("Browser");
// Setup layout change
// ------------------------------
// Add change event
d3.selectAll(".stacked-multiple").on("change", change);
// Change value on page load
var timeout = setTimeout(function() {
d3.select("input[value=\"stacked\"]").property("checked", true).each(change);
$.uniform.update();
}, 2000);
// Change function
function change() {
clearTimeout(timeout);
if (this.value === "multiples") transitionMultiples();
else transitionStacked();
}
// Transition to multiples
function transitionMultiples() {
var t = svg.transition().duration(750),
g = t.selectAll(".d3-bar-group").attr("transform", function(d) { return "translate(0," + y0(d.key) + ")"; });
g.selectAll(".d3-bar").attr("y", function(d) { return y1(d.value); });
g.select(".d3-group-label").attr("y", function(d) { return y1(d.values[0].value / 2); })
}
// Transition to stacked
function transitionStacked() {
var t = svg.transition().duration(750),
g = t.selectAll(".d3-bar-group").attr("transform", "translate(0," + y0(y0.domain()[0]) + ")");
g.selectAll(".d3-bar").attr("y", function(d) { return y1(d.value + d.valueOffset) });
g.select(".d3-group-label").attr("y", function(d) { return y1(d.values[0].value / 2 + d.values[0].valueOffset); })
}
});
// Resize chart
// ------------------------------
// Call function on window resize
$(window).on('resize', resize);
// Call function on sidebar width change
$('.sidebar-control').on('click', resize);
// Resize function
//
// Since D3 doesn't support SVG resize by default,
// we need to manually specify parts of the graph that need to
// be updated on window resize
function resize() {
// Layout variables
width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;
// Layout
// -------------------------
// Main svg width
container.attr("width", width + margin.left + margin.right);
// Width of appended group
svg.attr("width", width + margin.left + margin.right);
// Axes
// -------------------------
// Horizontal range
x.rangeRoundBands([0, width], .2);
// Horizontal axis
svg.selectAll('.d3-axis-horizontal').call(xAxis);
// Chart elements
// -------------------------
// Line path
svg.selectAll('.d3-bar').attr("x", function(d) { return x(d.date); }).attr("width", x.rangeBand());
}
}
});
|
webpackJsonp([18,19],{752:function(e,n,t){"use strict";function r(e,n,t){return n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}function o(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}function a(e,n){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!n||"object"!=typeof n&&"function"!=typeof n?e:n}function i(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function, not "+typeof n);e.prototype=Object.create(n&&n.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),n&&(Object.setPrototypeOf?Object.setPrototypeOf(e,n):e.__proto__=n)}var c=t(8),l=c&&c.__esModule?function(){return c["default"]}:function(){return c};t.d(l,"a",l);var u=function(){var e="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103;return function(n,t,r,o){var a=n&&n.defaultProps,i=arguments.length-3;if(t||0===i||(t={}),t&&a)for(var c in a)void 0===t[c]&&(t[c]=a[c]);else t||(t=a||{});if(1===i)t.children=o;else if(i>1){for(var l=Array(i),u=0;u<i;u++)l[u]=arguments[u+3];t.children=l}return{$$typeof:e,type:n,key:void 0===r?null:""+r,ref:null,props:t,_owner:null}}}(),f=function(){function e(e,n){for(var t=0;t<n.length;t++){var r=n[t];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(n,t,r){return t&&e(n.prototype,t),r&&e(n,r),n}}(),s=function(e){function n(e){o(this,n);var t=a(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t.state={clara:null},t}return i(n,e),f(n,[{key:"componentDidMount",value:function(){var e=this,n=claraplayer(this.refs.claraplayer);n.sceneIO.fetchAndUse("0cd9a9a2-c113-4b0d-ae91-baa86d3ded4a").then(function(){return e.setState({clara:n})}),["orbit","pan","zoom","home","fullscreen"].forEach(function(e){n.player.hideTool(e)})}},{key:"componentDidUpdate",value:function(){this.state.clara.player.resize()}},{key:"importScene",value:function(e){var n=this.state.clara,t=0;n.sceneIO.fetch(e).then(function(){var o=n.scene.find({from:{id:e},name:"Objects"}),a=n.scene.filter({from:{id:o},type:["PolyMesh","BinMesh","Null"]}),i=n.scene.find({type:"Objects"});n.sceneGraph.addNode({name:"Import Null",parent:i,type:"Null",plugs:{Transform:[["Transform",{translation:{x:0,y:(t+1)/2,z:0}}]]}}).then(function(e){n.sceneGraph.clone(a,r({},o,e)).then(function(e){console.log("new nodes",e)})})})}},{key:"render",value:function(){var e=this;return u("div",{},void 0,l.a.createElement("div",{ref:"claraplayer",style:{width:800,height:600}}),u("div",{},void 0,u("button",{onClick:function(n){return e.importScene("7f92faad-1cd0-4e75-b76c-c0c564e809f2")}},void 0,"import")))}}]),n}(c.Component);n["default"]=s}});
|
import React from 'react';
import { Grid, Row, Col } from 'react-bootstrap';
// import ProjectHeaderContainer from '../../containers/ProjectHeaderContainer';
import Header from '../../../../components/navigation/Header';
import ProjectFooterContainer from '../../containers/ProjectFooterContainer';
import './ProjectNotFound.css';
const ProjectNotFound = props => (
<div className="projectNotFound">
<Header />
<Grid>
<Row>
<Col md={12}>
<h1>This project was not found.</h1>
<p>
Head <a href="//orphe.us">back home.</a>
</p>
</Col>
</Row>
</Grid>
<ProjectFooterContainer />
</div>
);
export default ProjectNotFound;
|
// This file was automatically generated. Do not modify.
'use strict';
goog.provide('Blockly.Msg.oc');
goog.require('Blockly.Msg');
Blockly.Msg.ADD_COMMENT = "Apondre un comentari";
Blockly.Msg.CHANGE_VALUE_TITLE = "Modificar la valor :";
Blockly.Msg.CLEAN_UP = "Netejar los blòts";
Blockly.Msg.COLLAPSE_ALL = "Redusir los blòts";
Blockly.Msg.COLLAPSE_BLOCK = "Redusir lo blòt";
Blockly.Msg.COLOUR_BLEND_COLOUR1 = "color 1";
Blockly.Msg.COLOUR_BLEND_COLOUR2 = "color 2";
Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/"; // untranslated
Blockly.Msg.COLOUR_BLEND_RATIO = "ratio";
Blockly.Msg.COLOUR_BLEND_TITLE = "mesclar";
Blockly.Msg.COLOUR_BLEND_TOOLTIP = "Blends two colours together with a given ratio (0.0 - 1.0)."; // untranslated
Blockly.Msg.COLOUR_PICKER_HELPURL = "https://oc.wikipedia.org/wiki/Color";
Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Choose a colour from the palette."; // untranslated
Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; // untranslated
Blockly.Msg.COLOUR_RANDOM_TITLE = "color aleatòria";
Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Causir una color a l'azard.";
Blockly.Msg.COLOUR_RGB_BLUE = "blau";
Blockly.Msg.COLOUR_RGB_GREEN = "verd";
Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html"; // untranslated
Blockly.Msg.COLOUR_RGB_RED = "roge";
Blockly.Msg.COLOUR_RGB_TITLE = "colorar amb";
Blockly.Msg.COLOUR_RGB_TOOLTIP = "Create a colour with the specified amount of red, green, and blue. All values must be between 0 and 100."; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "break out of loop"; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "continue with next iteration of loop"; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Break out of the containing loop."; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Skip the rest of this loop, and continue with the next iteration."; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Warning: This block may only be used within a loop."; // untranslated
Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://github.com/google/blockly/wiki/Loops#for-each"; // untranslated
Blockly.Msg.CONTROLS_FOREACH_TITLE = "per cada element %1 dins la lista %2";
Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "For each item in a list, set the variable '%1' to the item, and then do some statements."; // untranslated
Blockly.Msg.CONTROLS_FOR_HELPURL = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated
Blockly.Msg.CONTROLS_FOR_TITLE = "comptar amb %1 de %2 a %3 per %4";
Blockly.Msg.CONTROLS_FOR_TOOLTIP = "Have the variable '%1' take on the values from the start number to the end number, counting by the specified interval, and do the specified blocks."; // untranslated
Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "Add a condition to the if block."; // untranslated
Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "Add a final, catch-all condition to the if block."; // untranslated
Blockly.Msg.CONTROLS_IF_HELPURL = "https://github.com/google/blockly/wiki/IfElse"; // untranslated
Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Add, remove, or reorder sections to reconfigure this if block."; // untranslated
Blockly.Msg.CONTROLS_IF_MSG_ELSE = "siquenon";
Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "siquenon se";
Blockly.Msg.CONTROLS_IF_MSG_IF = "se";
Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "If a value is true, then do some statements."; // untranslated
Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "If a value is true, then do the first block of statements. Otherwise, do the second block of statements."; // untranslated
Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements."; // untranslated
Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements. If none of the values are true, do the last block of statements."; // untranslated
Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://oc.wikipedia.org/wiki/For_loop";
Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "far";
Blockly.Msg.CONTROLS_REPEAT_TITLE = "repetir %1 còps";
Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Do some statements several times."; // untranslated
Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "repetir fins a";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "repetir tant que";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "While a value is false, then do some statements."; // untranslated
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "While a value is true, then do some statements."; // untranslated
Blockly.Msg.DELETE_ALL_BLOCKS = "Suprimir totes los %1 blòts ?";
Blockly.Msg.DELETE_BLOCK = "Suprimir lo blòt";
Blockly.Msg.DELETE_VARIABLE = "Delete the '%1' variable"; // untranslated
Blockly.Msg.DELETE_VARIABLE_CONFIRMATION = "Delete %1 uses of the '%2' variable?"; // untranslated
Blockly.Msg.DELETE_X_BLOCKS = "Suprimir %1 blòts";
Blockly.Msg.DICTS_CREATE_EMPTY_TITLE = "empty dictionary"; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_CONTAINER_TITLE_ADD = "Create Dictionary"; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_CONTAINER_TOOLTIP = ""; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_INPUT_WITH = "create dict with"; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_ITEM_KEY = "key"; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_ITEM_MAPPING = ":"; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_ITEM_TITLE = "key/value"; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_ITEM_TOOLTIP = ""; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_TOOLTIP = ""; // untranslated
Blockly.Msg.DICT_GET = "get key"; // untranslated
Blockly.Msg.DICT_GET_TO = "of"; // untranslated
Blockly.Msg.DICT_KEYS = "get all keys from"; // untranslated
Blockly.Msg.DISABLE_BLOCK = "Desactivar lo blòt";
Blockly.Msg.DUPLICATE_BLOCK = "Duplicar";
Blockly.Msg.ENABLE_BLOCK = "Activar lo blòt";
Blockly.Msg.EXPAND_ALL = "Desvolopar los blòts";
Blockly.Msg.EXPAND_BLOCK = "Desvolopar lo blòt";
Blockly.Msg.EXTERNAL_INPUTS = "Entradas extèrnas";
Blockly.Msg.HELP = "Ajuda";
Blockly.Msg.INLINE_INPUTS = "Entradas en linha";
Blockly.Msg.LISTS_APPEND = "append item"; // untranslated
Blockly.Msg.LISTS_APPEND_HELPURL = "http://google.com"; // untranslated
Blockly.Msg.LISTS_APPEND_TO = "to list"; // untranslated
Blockly.Msg.LISTS_APPEND_TOOLTIP = "Append an element to a list"; // untranslated
Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-empty-list"; // untranslated
Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "create empty list"; // untranslated
Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Returns a list, of length 0, containing no data records"; // untranslated
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "lista";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Add, remove, or reorder sections to reconfigure this list block."; // untranslated
Blockly.Msg.LISTS_CREATE_WITH_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "crear una lista amb";
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Add an item to the list."; // untranslated
Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "Create a list with any number of items."; // untranslated
Blockly.Msg.LISTS_GET_INDEX_FIRST = "primièr";
Blockly.Msg.LISTS_GET_INDEX_FROM_END = "# dempuèi la fin";
Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#"; // untranslated
Blockly.Msg.LISTS_GET_INDEX_GET = "obténer";
Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "obténer e suprimir";
Blockly.Msg.LISTS_GET_INDEX_LAST = "darrièr";
Blockly.Msg.LISTS_GET_INDEX_RANDOM = "aleatòri";
Blockly.Msg.LISTS_GET_INDEX_REMOVE = "suprimit";
Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "Returns the first item in a list."; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM = "Returns the item at the specified position in a list."; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "Returns the last item in a list."; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "Returns a random item in a list."; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "Removes and returns the first item in a list."; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM = "Removes and returns the item at the specified position in a list."; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "Removes and returns the last item in a list."; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "Removes and returns a random item in a list."; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "Removes the first item in a list."; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM = "Removes the item at the specified position in a list."; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "Removes the last item in a list."; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "Removes a random item in a list."; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "fins a # dempuèi la fin";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "fins a #";
Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "fins a la fin";
Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "get sub-list from first"; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "get sub-list from # from end"; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "get sub-list from #"; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "Creates a copy of the specified portion of a list."; // untranslated
Blockly.Msg.LISTS_INDEX_FROM_END_TOOLTIP = "%1 is the last item."; // untranslated
Blockly.Msg.LISTS_INDEX_FROM_START_TOOLTIP = "%1 is the first item."; // untranslated
Blockly.Msg.LISTS_INDEX_OF_FIRST = "find first occurrence of item"; // untranslated
Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated
Blockly.Msg.LISTS_INDEX_OF_LAST = "find last occurrence of item"; // untranslated
Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "Returns the index of the first/last occurrence of the item in the list. Returns %1 if item is not found."; // untranslated
Blockly.Msg.LISTS_INLIST = "dins la lista";
Blockly.Msg.LISTS_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated
Blockly.Msg.LISTS_ISEMPTY_TITLE = "%1 is empty"; // untranslated
Blockly.Msg.LISTS_ISEMPTY_TOOLTIP = "Returns true if the list is empty."; // untranslated
Blockly.Msg.LISTS_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated
Blockly.Msg.LISTS_LENGTH_TITLE = "length of %1"; // untranslated
Blockly.Msg.LISTS_LENGTH_TOOLTIP = "Returns the length of a list."; // untranslated
Blockly.Msg.LISTS_REPEAT_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg.LISTS_REPEAT_TITLE = "create list with item %1 repeated %2 times"; // untranslated
Blockly.Msg.LISTS_REPEAT_TOOLTIP = "Creates a list consisting of the given value repeated the specified number of times."; // untranslated
Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated
Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "coma";
Blockly.Msg.LISTS_SET_INDEX_INSERT = "inserir en";
Blockly.Msg.LISTS_SET_INDEX_SET = "metre";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "Inserts the item at the start of a list."; // untranslated
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM = "Inserts the item at the specified position in a list."; // untranslated
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Append the item to the end of a list."; // untranslated
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "Inserts the item randomly in a list."; // untranslated
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "Sets the first item in a list."; // untranslated
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM = "Sets the item at the specified position in a list."; // untranslated
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "Sets the last item in a list."; // untranslated
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "Sets a random item in a list."; // untranslated
Blockly.Msg.LISTS_SORT_HELPURL = "https://github.com/google/blockly/wiki/Lists#sorting-a-list"; // untranslated
Blockly.Msg.LISTS_SORT_ORDER_ASCENDING = "creissent";
Blockly.Msg.LISTS_SORT_ORDER_DESCENDING = "descreissent";
Blockly.Msg.LISTS_SORT_TITLE = "sort %1 %2 %3"; // untranslated
Blockly.Msg.LISTS_SORT_TOOLTIP = "Sort a copy of a list."; // untranslated
Blockly.Msg.LISTS_SORT_TYPE_IGNORECASE = "alphabetic, ignore case"; // untranslated
Blockly.Msg.LISTS_SORT_TYPE_NUMERIC = "numeric";
Blockly.Msg.LISTS_SORT_TYPE_TEXT = "alfabetic";
Blockly.Msg.LISTS_SPLIT_HELPURL = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists"; // untranslated
Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT = "make list from text"; // untranslated
Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST = "make text from list"; // untranslated
Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN = "Join a list of texts into one text, separated by a delimiter."; // untranslated
Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT = "Split text into a list of texts, breaking at each delimiter."; // untranslated
Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER = "with delimiter"; // untranslated
Blockly.Msg.LOGIC_BOOLEAN_FALSE = "fals";
Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated
Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "Returns either true or false."; // untranslated
Blockly.Msg.LOGIC_BOOLEAN_TRUE = "verai";
Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://en.wikipedia.org/wiki/Inequality_(mathematics)"; // untranslated
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Return true if both inputs equal each other."; // untranslated
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Return true if the first input is greater than the second input."; // untranslated
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Return true if the first input is greater than or equal to the second input."; // untranslated
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Return true if the first input is smaller than the second input."; // untranslated
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Return true if the first input is smaller than or equal to the second input."; // untranslated
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Return true if both inputs are not equal to each other."; // untranslated
Blockly.Msg.LOGIC_NEGATE_HELPURL = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated
Blockly.Msg.LOGIC_NEGATE_TITLE = "pas %1";
Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "Returns true if the input is false. Returns false if the input is true."; // untranslated
Blockly.Msg.LOGIC_NULL = "nul";
Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type"; // untranslated
Blockly.Msg.LOGIC_NULL_TOOLTIP = "Renvia nul.";
Blockly.Msg.LOGIC_OPERATION_AND = "e";
Blockly.Msg.LOGIC_OPERATION_HELPURL = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated
Blockly.Msg.LOGIC_OPERATION_OR = "o";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Return true if both inputs are true."; // untranslated
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Return true if at least one of the inputs is true."; // untranslated
Blockly.Msg.LOGIC_TERNARY_CONDITION = "tèst";
Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:"; // untranslated
Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "se fals";
Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "se verai";
Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "Check the condition in 'test'. If the condition is true, returns the 'if true' value; otherwise returns the 'if false' value."; // untranslated
Blockly.Msg.MATH_ADDITION_SYMBOL = "+"; // untranslated
Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://oc.wikipedia.org/wiki/Aritmetica";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "Return the sum of the two numbers."; // untranslated
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "Return the quotient of the two numbers."; // untranslated
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "Return the difference of the two numbers."; // untranslated
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "Return the product of the two numbers."; // untranslated
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "Return the first number raised to the power of the second number."; // untranslated
Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter"; // untranslated
Blockly.Msg.MATH_CHANGE_TITLE = "incrementar %1 per %2";
Blockly.Msg.MATH_CHANGE_TOOLTIP = "Add a number to variable '%1'."; // untranslated
Blockly.Msg.MATH_CONSTANT_HELPURL = "https://en.wikipedia.org/wiki/Mathematical_constant"; // untranslated
Blockly.Msg.MATH_CONSTANT_TOOLTIP = "Return one of the common constants: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), or ∞ (infinity)."; // untranslated
Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_%28graphics%29"; // untranslated
Blockly.Msg.MATH_CONSTRAIN_TITLE = "constrain %1 low %2 high %3"; // untranslated
Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Constrain a number to be between the specified limits (inclusive)."; // untranslated
Blockly.Msg.MATH_DIVISION_SYMBOL = "/"; // untranslated
Blockly.Msg.MATH_IS_DIVISIBLE_BY = "es devesible per";
Blockly.Msg.MATH_IS_EVEN = "es par";
Blockly.Msg.MATH_IS_NEGATIVE = "es negatiu";
Blockly.Msg.MATH_IS_ODD = "es impar";
Blockly.Msg.MATH_IS_POSITIVE = "es positiu";
Blockly.Msg.MATH_IS_PRIME = "es primièr";
Blockly.Msg.MATH_IS_TOOLTIP = "Check if a number is an even, odd, prime, whole, positive, negative, or if it is divisible by certain number. Returns true or false."; // untranslated
Blockly.Msg.MATH_IS_WHOLE = "es entièr";
Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation"; // untranslated
Blockly.Msg.MATH_MODULO_TITLE = "remainder of %1 ÷ %2"; // untranslated
Blockly.Msg.MATH_MODULO_TOOLTIP = "Return the remainder from dividing the two numbers."; // untranslated
Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×"; // untranslated
Blockly.Msg.MATH_NUMBER_HELPURL = "https://oc.wikipedia.org/wiki/Nombre";
Blockly.Msg.MATH_NUMBER_TOOLTIP = "Un nombre.";
Blockly.Msg.MATH_ONLIST_HELPURL = ""; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "mejana de la lista";
Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "maximum de la lista";
Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "mediana de la lista";
Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "minimum de la lista";
Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "modes of list"; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "random item of list"; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "standard deviation of list"; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "soma de la lista";
Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "Return the average (arithmetic mean) of the numeric values in the list."; // untranslated
Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "Return the largest number in the list."; // untranslated
Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "Return the median number in the list."; // untranslated
Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "Return the smallest number in the list."; // untranslated
Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "Return a list of the most common item(s) in the list."; // untranslated
Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "Return a random element from the list."; // untranslated
Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "Return the standard deviation of the list."; // untranslated
Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "Return the sum of all the numbers in the list."; // untranslated
Blockly.Msg.MATH_POWER_SYMBOL = "^"; // untranslated
Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; // untranslated
Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "random fraction"; // untranslated
Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "Return a random fraction between 0.0 (inclusive) and 1.0 (exclusive)."; // untranslated
Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; // untranslated
Blockly.Msg.MATH_RANDOM_INT_TITLE = "random integer from %1 to %2"; // untranslated
Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "Return a random integer between the two specified limits, inclusive."; // untranslated
Blockly.Msg.MATH_ROUND_HELPURL = "https://en.wikipedia.org/wiki/Rounding"; // untranslated
Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "arredondir";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "arredondir a l’inferior";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "arredondir al superior";
Blockly.Msg.MATH_ROUND_TOOLTIP = "Round a number up or down."; // untranslated
Blockly.Msg.MATH_SINGLE_HELPURL = "https://en.wikipedia.org/wiki/Square_root"; // untranslated
Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "absolut";
Blockly.Msg.MATH_SINGLE_OP_ROOT = "raiç carrada";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "Return the absolute value of a number."; // untranslated
Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "Return e to the power of a number."; // untranslated
Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "Return the natural logarithm of a number."; // untranslated
Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "Return the base 10 logarithm of a number."; // untranslated
Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "Return the negation of a number."; // untranslated
Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "Return 10 to the power of a number."; // untranslated
Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "Return the square root of a number."; // untranslated
Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-"; // untranslated
Blockly.Msg.MATH_TRIG_ACOS = "acos"; // untranslated
Blockly.Msg.MATH_TRIG_ASIN = "asin"; // untranslated
Blockly.Msg.MATH_TRIG_ATAN = "atan"; // untranslated
Blockly.Msg.MATH_TRIG_COS = "cos"; // untranslated
Blockly.Msg.MATH_TRIG_HELPURL = "https://en.wikipedia.org/wiki/Trigonometric_functions"; // untranslated
Blockly.Msg.MATH_TRIG_SIN = "sin"; // untranslated
Blockly.Msg.MATH_TRIG_TAN = "tan"; // untranslated
Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "Return the arccosine of a number."; // untranslated
Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "Return the arcsine of a number."; // untranslated
Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "Return the arctangent of a number."; // untranslated
Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "Return the cosine of a degree (not radian)."; // untranslated
Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "Return the sine of a degree (not radian)."; // untranslated
Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "Return the tangent of a degree (not radian)."; // untranslated
Blockly.Msg.NEW_VARIABLE = "Crear una variabla...";
Blockly.Msg.NEW_VARIABLE_TITLE = "Nom de la novèla variabla :";
Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; // untranslated
Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS = "allow statements"; // untranslated
Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "amb :";
Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Run the user-defined function '%1'."; // untranslated
Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Run the user-defined function '%1' and use its output."; // untranslated
Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS = "amb :";
Blockly.Msg.PROCEDURES_CREATE_DO = "Crear '%1'";
Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT = "Describe this function..."; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "far quicòm";
Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "a";
Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "Creates a function with no output."; // untranslated
Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "retorn";
Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "Creates a function with an output."; // untranslated
Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Warning: This function has duplicate parameters."; // untranslated
Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Highlight function definition"; // untranslated
Blockly.Msg.PROCEDURES_IFRETURN_HELPURL = "http://c2.com/cgi/wiki?GuardClause"; // untranslated
Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "If a value is true, then return a second value."; // untranslated
Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Warning: This block may be used only within a function definition."; // untranslated
Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "nom de l’entrada :";
Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP = "Add a parameter to the function."; // untranslated
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "entradas";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP = "Add, remove, or reorder inputs to this function."; // untranslated
Blockly.Msg.REDO = "Refar";
Blockly.Msg.REMOVE_COMMENT = "Suprimir un comentari";
Blockly.Msg.RENAME_VARIABLE = "Renomenar la variabla…";
Blockly.Msg.RENAME_VARIABLE_TITLE = "Renomenar totas las variablas '%1' a :";
Blockly.Msg.TEXT_APPEND_APPENDTEXT = "apondre lo tèxte";
Blockly.Msg.TEXT_APPEND_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_APPEND_TO = "a";
Blockly.Msg.TEXT_APPEND_TOOLTIP = "Append some text to variable '%1'."; // untranslated
Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "en minusculas";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "to Title Case"; // untranslated
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "en MAJUSCULAS";
Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "Return a copy of the text in a different case."; // untranslated
Blockly.Msg.TEXT_CHARAT_FIRST = "obténer la primièra letra";
Blockly.Msg.TEXT_CHARAT_FROM_END = "obténer la letra # dempuèi la fin";
Blockly.Msg.TEXT_CHARAT_FROM_START = "obténer la letra #";
Blockly.Msg.TEXT_CHARAT_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated
Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "dins lo tèxte";
Blockly.Msg.TEXT_CHARAT_LAST = "obténer la darrièra letra";
Blockly.Msg.TEXT_CHARAT_RANDOM = "obténer una letra a l'azard";
Blockly.Msg.TEXT_CHARAT_TAIL = ""; // untranslated
Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Renvia la letra a la posicion indicada.";
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Add an item to the text."; // untranslated
Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "jónher";
Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Add, remove, or reorder sections to reconfigure this text block."; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "to letter # from end"; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "fins a la letra #";
Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "to last letter"; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "dins lo tèxte";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "get substring from first letter"; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "get substring from letter # from end"; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "get substring from letter #"; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "Returns a specified portion of the text."; // untranslated
Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated
Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "dins lo tèxte";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "find first occurrence of text"; // untranslated
Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "find last occurrence of text"; // untranslated
Blockly.Msg.TEXT_INDEXOF_TAIL = ""; // untranslated
Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "Returns the index of the first/last occurrence of the first text in the second text. Returns %1 if text is not found."; // untranslated
Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated
Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 es void";
Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "Returns true if the provided text is empty."; // untranslated
Blockly.Msg.TEXT_JOIN_HELPURL = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated
Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "join strings"; // untranslated
Blockly.Msg.TEXT_JOIN_TOOLTIP = "Create a piece of text by joining together any number of items."; // untranslated
Blockly.Msg.TEXT_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_LENGTH_TITLE = "longor de %1";
Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Returns the number of letters (including spaces) in the provided text."; // untranslated
Blockly.Msg.TEXT_PRINT_HELPURL = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated
Blockly.Msg.TEXT_PRINT_TITLE = "afichar %1";
Blockly.Msg.TEXT_PRINT_TITLE_PRINT = "print"; // untranslated
Blockly.Msg.TEXT_PRINT_TOOLTIP = ""; // untranslated
Blockly.Msg.TEXT_PROMPT_HELPURL = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated
Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "Prompt for user for a number."; // untranslated
Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "Prompt for user for some text."; // untranslated
Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "prompt for number with message"; // untranslated
Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "prompt for text with message"; // untranslated
Blockly.Msg.TEXT_TEXT_HELPURL = "https://en.wikipedia.org/wiki/String_(computer_science)"; // untranslated
Blockly.Msg.TEXT_TEXT_TOOLTIP = "A letter, word, or line of text."; // untranslated
Blockly.Msg.TEXT_TRIM_HELPURL = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated
Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "strip both sides"; // untranslated
Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "strip left side"; // untranslated
Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "strip right side"; // untranslated
Blockly.Msg.TEXT_TRIM_TOOLTIP = "Return a copy of the text with spaces removed from one or both ends."; // untranslated
Blockly.Msg.TODAY = "Uèi";
Blockly.Msg.TYPE_CHECK = "type of"; // untranslated
Blockly.Msg.UNDO = "Anullar";
Blockly.Msg.VARIABLES_DEFAULT_NAME = "element";
Blockly.Msg.VARIABLES_GET_CREATE_SET = "Crear 'fixar %1'";
Blockly.Msg.VARIABLES_GET_HELPURL = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated
Blockly.Msg.VARIABLES_GET_TOOLTIP = "Returns the value of this variable."; // untranslated
Blockly.Msg.VARIABLES_SET = "fixar %1 a %2";
Blockly.Msg.VARIABLES_SET_CREATE_GET = "Create 'get %1'"; // untranslated
Blockly.Msg.VARIABLES_SET_HELPURL = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated
Blockly.Msg.VARIABLES_SET_TAIL = "="; // untranslated
Blockly.Msg.VARIABLES_SET_TITLE = "set"; // untranslated
Blockly.Msg.VARIABLES_SET_TOOLTIP = "Sets this variable to be equal to the input."; // untranslated
Blockly.Msg.VARIABLE_ALREADY_EXISTS = "A variable named '%1' already exists."; // untranslated
Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE;
Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF;
Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE;
Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE;
Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.VARIABLES_SET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO;
Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF;
Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL;
Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT = Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT;
|
/**
* @hello.js
*
* HelloJS is a client side Javascript SDK for making OAuth2 logins and subsequent REST calls.
*
* @author Andrew Dodson
* @website https://adodson.com/hello.js/
*
* @copyright Andrew Dodson, 2012 - 2015
* @license MIT: You are free to use and modify this code for any use, on the condition that this copyright notice remains.
*/
var hello = function(name) {
return hello.use(name);
};
hello.utils = {
// Extend the first object with the properties and methods of the second
extend: function(r /*, a[, b[, ...]] */) {
// Get the arguments as an array but ommit the initial item
Array.prototype.slice.call(arguments, 1).forEach(function(a) {
if (Array.isArray(r) && Array.isArray(a)) {
Array.prototype.push.apply(r, a);
}
else if (r && (r instanceof Object || typeof r === 'object') && a && (a instanceof Object || typeof a === 'object') && r !== a) {
for (var x in a) {
r[x] = hello.utils.extend(r[x], a[x]);
}
}
else {
if (Array.isArray(a)) {
// Clone it
a = a.slice(0);
}
r = a;
}
});
return r;
}
};
// Core library
hello.utils.extend(hello, {
settings: {
// OAuth2 authentication defaults
redirect_uri: window.location.href.split('#')[0],
response_type: 'token',
display: 'popup',
state: '',
// OAuth1 shim
// The path to the OAuth1 server for signing user requests
// Want to recreate your own? Checkout https://github.com/MrSwitch/node-oauth-shim
oauth_proxy: 'https://auth-server.herokuapp.com/proxy',
// API timeout in milliseconds
timeout: 20000,
// Popup Options
popup: {
resizable: 1,
scrollbars: 1,
width: 500,
height: 550
},
// Default scope
// Many services require atleast a profile scope,
// HelloJS automatially includes the value of provider.scope_map.basic
// If that's not required it can be removed via hello.settings.scope.length = 0;
scope: ['basic'],
// Scope Maps
// This is the default module scope, these are the defaults which each service is mapped too.
// By including them here it prevents the scope from being applied accidentally
scope_map: {
basic: ''
},
// Default service / network
default_service: null,
// Force authentication
// When hello.login is fired.
// (null): ignore current session expiry and continue with login
// (true): ignore current session expiry and continue with login, ask for user to reauthenticate
// (false): if the current session looks good for the request scopes return the current session.
force: null,
// Page URL
// When 'display=page' this property defines where the users page should end up after redirect_uri
// Ths could be problematic if the redirect_uri is indeed the final place,
// Typically this circumvents the problem of the redirect_url being a dumb relay page.
page_uri: window.location.href
},
// Service configuration objects
services: {},
// Use
// Define a new instance of the HelloJS library with a default service
use: function(service) {
// Create self, which inherits from its parent
var self = Object.create(this);
// Inherit the prototype from its parent
self.settings = Object.create(this.settings);
// Define the default service
if (service) {
self.settings.default_service = service;
}
// Create an instance of Events
self.utils.Event.call(self);
return self;
},
// Initialize
// Define the client_ids for the endpoint services
// @param object o, contains a key value pair, service => clientId
// @param object opts, contains a key value pair of options used for defining the authentication defaults
// @param number timeout, timeout in seconds
init: function(services, options) {
var utils = this.utils;
if (!services) {
return this.services;
}
// Define provider credentials
// Reformat the ID field
for (var x in services) {if (services.hasOwnProperty(x)) {
if (typeof (services[x]) !== 'object') {
services[x] = {id: services[x]};
}
}}
// Merge services if there already exists some
utils.extend(this.services, services);
// Update the default settings with this one.
if (options) {
utils.extend(this.settings, options);
// Do this immediatly incase the browser changes the current path.
if ('redirect_uri' in options) {
this.settings.redirect_uri = utils.url(options.redirect_uri).href;
}
}
return this;
},
// Login
// Using the endpoint
// @param network stringify name to connect to
// @param options object (optional) {display mode, is either none|popup(default)|page, scope: email,birthday,publish, .. }
// @param callback function (optional) fired on signin
login: function() {
// Create an object which inherits its parent as the prototype and constructs a new event chain.
var _this = this;
var utils = _this.utils;
var error = utils.error;
var promise = utils.Promise();
// Get parameters
var p = utils.args({network: 's', options: 'o', callback: 'f'}, arguments);
// Local vars
var url;
// Get all the custom options and store to be appended to the querystring
var qs = utils.diffKey(p.options, _this.settings);
// Merge/override options with app defaults
var opts = p.options = utils.merge(_this.settings, p.options || {});
// Merge/override options with app defaults
opts.popup = utils.merge(_this.settings.popup, p.options.popup || {});
// Network
p.network = p.network || _this.settings.default_service;
// Bind callback to both reject and fulfill states
promise.proxy.then(p.callback, p.callback);
// Trigger an event on the global listener
function emit(s, value) {
hello.emit(s, value);
}
promise.proxy.then(emit.bind(this, 'auth.login auth'), emit.bind(this, 'auth.failed auth'));
// Is our service valid?
if (typeof (p.network) !== 'string' || !(p.network in _this.services)) {
// Trigger the default login.
// Ahh we dont have one.
console.error('The provided network was not recognized', p.network, _this.services)
return promise.reject(error('invalid_network', 'The provided network was not recognized'));
}
var provider = _this.services[p.network];
// Create a global listener to capture events triggered out of scope
var callbackId = utils.globalEvent(function(obj) {
// The responseHandler returns a string, lets save this locally
if (obj) {
if (typeof (obj) == 'string') {
obj = JSON.parse(obj);
}
}
else {
obj = error('cancelled', 'The authentication was not completed');
}
// Handle these response using the local
// Trigger on the parent
if (!obj.error) {
// Save on the parent window the new credentials
// This fixes an IE10 bug i think... atleast it does for me.
utils.store(obj.network, obj);
// Fulfill a successful login
promise.fulfill({
network: obj.network,
authResponse: obj
});
}
else {
// Reject a successful login
promise.reject(obj);
}
});
var redirectUri = utils.url(opts.redirect_uri).href;
// May be a space-delimited list of multiple, complementary types
var responseType = provider.oauth.response_type || opts.response_type;
// Fallback to token if the module hasn't defined a grant url
if (/\bcode\b/.test(responseType) && !provider.oauth.grant) {
responseType = responseType.replace(/\bcode\b/, 'token');
}
// Query string parameters, we may pass our own arguments to form the querystring
p.qs = utils.merge(qs, {
client_id: encodeURIComponent(provider.id),
response_type: encodeURIComponent(responseType),
redirect_uri: encodeURIComponent(redirectUri),
state: {
client_id: provider.id,
network: p.network,
display: opts.display,
callback: callbackId,
state: opts.state,
redirect_uri: redirectUri
}
});
// Get current session for merging scopes, and for quick auth response
var session = utils.store(p.network);
// Scopes (authentication permisions)
// Ensure this is a string - IE has a problem moving Arrays between windows
// Append the setup scope
var SCOPE_SPLIT = /[,\s]+/;
// Include default scope settings (cloned).
var scope = _this.settings.scope ? [_this.settings.scope.toString()] : [];
// Extend the providers scope list with the default
var scopeMap = utils.merge(_this.settings.scope_map, provider.scope || {});
// Add user defined scopes...
if (opts.scope) {
scope.push(opts.scope.toString());
}
// Append scopes from a previous session.
// This helps keep app credentials constant,
// Avoiding having to keep tabs on what scopes are authorized
if (session && 'scope' in session && session.scope instanceof String) {
scope.push(session.scope);
}
// Join and Split again
scope = scope.join(',').split(SCOPE_SPLIT);
// Format remove duplicates and empty values
scope = utils.unique(scope).filter(filterEmpty);
// Save the the scopes to the state with the names that they were requested with.
p.qs.state.scope = scope.join(',');
// Map scopes to the providers naming convention
scope = scope.map(function(item) {
// Does this have a mapping?
return (item in scopeMap) ? scopeMap[item] : item;
});
// Stringify and Arrayify so that double mapped scopes are given the chance to be formatted
scope = scope.join(',').split(SCOPE_SPLIT);
// Again...
// Format remove duplicates and empty values
scope = utils.unique(scope).filter(filterEmpty);
// Join with the expected scope delimiter into a string
p.qs.scope = scope.join(provider.scope_delim || ',');
// Is the user already signed in with the appropriate scopes, valid access_token?
if (opts.force === false) {
if (session && 'access_token' in session && session.access_token && 'expires' in session && session.expires > ((new Date()).getTime() / 1e3)) {
// What is different about the scopes in the session vs the scopes in the new login?
var diff = utils.diff((session.scope || '').split(SCOPE_SPLIT), (p.qs.state.scope || '').split(SCOPE_SPLIT));
if (diff.length === 0) {
// OK trigger the callback
promise.fulfill({
unchanged: true,
network: p.network,
authResponse: session
});
// Nothing has changed
return promise;
}
}
}
// Page URL
if (opts.display === 'page' && opts.page_uri) {
// Add a page location, place to endup after session has authenticated
p.qs.state.page_uri = utils.url(opts.page_uri).href;
}
// Bespoke
// Override login querystrings from auth_options
if ('login' in provider && typeof (provider.login) === 'function') {
// Format the paramaters according to the providers formatting function
provider.login(p);
}
// Add OAuth to state
// Where the service is going to take advantage of the oauth_proxy
if (!/\btoken\b/.test(responseType) ||
parseInt(provider.oauth.version, 10) < 2 ||
(opts.display === 'none' && provider.oauth.grant && session && session.refresh_token)) {
// Add the oauth endpoints
p.qs.state.oauth = provider.oauth;
// Add the proxy url
p.qs.state.oauth_proxy = opts.oauth_proxy;
}
// Convert state to a string
p.qs.state = encodeURIComponent(JSON.stringify(p.qs.state));
// URL
if (parseInt(provider.oauth.version, 10) === 1) {
// Turn the request to the OAuth Proxy for 3-legged auth
url = utils.qs(opts.oauth_proxy, p.qs, encodeFunction);
}
// Refresh token
else if (opts.display === 'none' && provider.oauth.grant && session && session.refresh_token) {
// Add the refresh_token to the request
p.qs.refresh_token = session.refresh_token;
// Define the request path
url = utils.qs(opts.oauth_proxy, p.qs, encodeFunction);
}
else {
url = utils.qs(provider.oauth.auth, p.qs, encodeFunction);
}
// Broadcast this event as an auth:init
emit('auth.init', p);
// Execute
// Trigger how we want self displayed
if (opts.display === 'none') {
// Sign-in in the background, iframe
utils.iframe(url, redirectUri);
}
// Triggering popup?
else if (opts.display === 'popup') {
var popup = utils.popup(url, redirectUri, opts.popup);
var timer = setInterval(function() {
if (!popup || popup.closed) {
clearInterval(timer);
if (!promise.state) {
var response = error('cancelled', 'Login has been cancelled');
if (!popup) {
response = error('blocked', 'Popup was blocked');
}
response.network = p.network;
promise.reject(response);
}
}
}, 100);
}
else {
window.location = url;
}
return promise.proxy;
function encodeFunction(s) {return s;}
function filterEmpty(s) {return !!s;}
},
// Remove any data associated with a given service
// @param string name of the service
// @param function callback
logout: function() {
var _this = this;
var utils = _this.utils;
var error = utils.error;
// Create a new promise
var promise = utils.Promise();
var p = utils.args({name:'s', options: 'o', callback: 'f'}, arguments);
p.options = p.options || {};
// Add callback to events
promise.proxy.then(p.callback, p.callback);
// Trigger an event on the global listener
function emit(s, value) {
hello.emit(s, value);
}
promise.proxy.then(emit.bind(this, 'auth.logout auth'), emit.bind(this, 'error'));
// Network
p.name = p.name || this.settings.default_service;
p.authResponse = utils.store(p.name);
if (p.name && !(p.name in _this.services)) {
promise.reject(error('invalid_network', 'The network was unrecognized'));
}
else if (p.name && p.authResponse) {
// Define the callback
var callback = function(opts) {
// Remove from the store
utils.store(p.name, null);
// Emit events by default
promise.fulfill(hello.utils.merge({network:p.name}, opts || {}));
};
// Run an async operation to remove the users session
var _opts = {};
if (p.options.force) {
var logout = _this.services[p.name].logout;
if (logout) {
// Convert logout to URL string,
// If no string is returned, then this function will handle the logout async style
if (typeof (logout) === 'function') {
logout = logout(callback, p);
}
// If logout is a string then assume URL and open in iframe.
if (typeof (logout) === 'string') {
utils.iframe(logout);
_opts.force = null;
_opts.message = 'Logout success on providers site was indeterminate';
}
else if (logout === undefined) {
// The callback function will handle the response.
return promise.proxy;
}
}
}
// Remove local credentials
callback(_opts);
}
else {
promise.reject(error('invalid_session', 'There was no session to remove'));
}
return promise.proxy;
},
// Returns all the sessions that are subscribed too
// @param string optional, name of the service to get information about.
getAuthResponse: function(service) {
// If the service doesn't exist
service = service || this.settings.default_service;
if (!service || !(service in this.services)) {
return null;
}
return this.utils.store(service) || null;
},
// Events: placeholder for the events
events: {}
});
// Core utilities
hello.utils.extend(hello.utils, {
// Error
error: function(code, message) {
return {
error: {
code: code,
message: message
}
};
},
// Append the querystring to a url
// @param string url
// @param object parameters
qs: function(url, params, formatFunction) {
if (params) {
// Set default formatting function
formatFunction = formatFunction || encodeURIComponent;
// Override the items in the URL which already exist
for (var x in params) {
var str = '([\\?\\&])' + x + '=[^\\&]*';
var reg = new RegExp(str);
if (url.match(reg)) {
url = url.replace(reg, '$1' + x + '=' + formatFunction(params[x]));
delete params[x];
}
}
}
if (!this.isEmpty(params)) {
return url + (url.indexOf('?') > -1 ? '&' : '?') + this.param(params, formatFunction);
}
return url;
},
// Param
// Explode/encode the parameters of an URL string/object
// @param string s, string to decode
param: function(s, formatFunction) {
var b;
var a = {};
var m;
if (typeof (s) === 'string') {
formatFunction = formatFunction || decodeURIComponent;
m = s.replace(/^[\#\?]/, '').match(/([^=\/\&]+)=([^\&]+)/g);
if (m) {
for (var i = 0; i < m.length; i++) {
b = m[i].match(/([^=]+)=(.*)/);
a[b[1]] = formatFunction(b[2]);
}
}
return a;
}
else {
formatFunction = formatFunction || encodeURIComponent;
var o = s;
a = [];
for (var x in o) {if (o.hasOwnProperty(x)) {
if (o.hasOwnProperty(x)) {
a.push([x, o[x] === '?' ? '?' : formatFunction(o[x])].join('='));
}
}}
return a.join('&');
}
},
// Local storage facade
store: (function() {
var a = ['localStorage', 'sessionStorage'];
var i = -1;
var prefix = 'test';
// Set LocalStorage
var localStorage;
while (a[++i]) {
try {
// In Chrome with cookies blocked, calling localStorage throws an error
localStorage = window[a[i]];
localStorage.setItem(prefix + i, i);
localStorage.removeItem(prefix + i);
break;
}
catch (e) {
localStorage = null;
}
}
if (!localStorage) {
var cache = null;
localStorage = {
getItem: function(prop) {
prop = prop + '=';
var m = document.cookie.split(';');
for (var i = 0; i < m.length; i++) {
var _m = m[i].replace(/(^\s+|\s+$)/, '');
if (_m && _m.indexOf(prop) === 0) {
return _m.substr(prop.length);
}
}
return cache;
},
setItem: function(prop, value) {
cache = value;
document.cookie = prop + '=' + value;
}
};
// Fill the cache up
cache = localStorage.getItem('hello');
}
function get() {
var json = {};
try {
json = JSON.parse(localStorage.getItem('hello')) || {};
}
catch (e) {}
return json;
}
function set(json) {
localStorage.setItem('hello', JSON.stringify(json));
}
// Check if the browser support local storage
return function(name, value, days) {
// Local storage
var json = get();
if (name && value === undefined) {
return json[name] || null;
}
else if (name && value === null) {
try {
delete json[name];
}
catch (e) {
json[name] = null;
}
}
else if (name) {
json[name] = value;
}
else {
return json;
}
set(json);
return json || null;
};
})(),
// Create and Append new DOM elements
// @param node string
// @param attr object literal
// @param dom/string
append: function(node, attr, target) {
var n = typeof (node) === 'string' ? document.createElement(node) : node;
if (typeof (attr) === 'object') {
if ('tagName' in attr) {
target = attr;
}
else {
for (var x in attr) {if (attr.hasOwnProperty(x)) {
if (typeof (attr[x]) === 'object') {
for (var y in attr[x]) {if (attr[x].hasOwnProperty(y)) {
n[x][y] = attr[x][y];
}}
}
else if (x === 'html') {
n.innerHTML = attr[x];
}
// IE doesn't like us setting methods with setAttribute
else if (!/^on/.test(x)) {
n.setAttribute(x, attr[x]);
}
else {
n[x] = attr[x];
}
}}
}
}
if (target === 'body') {
(function self() {
if (document.body) {
document.body.appendChild(n);
}
else {
setTimeout(self, 16);
}
})();
}
else if (typeof (target) === 'object') {
target.appendChild(n);
}
else if (typeof (target) === 'string') {
document.getElementsByTagName(target)[0].appendChild(n);
}
return n;
},
// An easy way to create a hidden iframe
// @param string src
iframe: function(src) {
this.append('iframe', {src: src, style: {position:'absolute', left: '-1000px', bottom: 0, height: '1px', width: '1px'}}, 'body');
},
// Recursive merge two objects into one, second parameter overides the first
// @param a array
merge: function(/* Args: a, b, c, .. n */) {
var args = Array.prototype.slice.call(arguments);
args.unshift({});
return this.extend.apply(null, args);
},
// Makes it easier to assign parameters, where some are optional
// @param o object
// @param a arguments
args: function(o, args) {
var p = {};
var i = 0;
var t = null;
var x = null;
// 'x' is the first key in the list of object parameters
for (x in o) {if (o.hasOwnProperty(x)) {
break;
}}
// Passing in hash object of arguments?
// Where the first argument can't be an object
if ((args.length === 1) && (typeof (args[0]) === 'object') && o[x] != 'o!') {
// Could this object still belong to a property?
// Check the object keys if they match any of the property keys
for (x in args[0]) {if (o.hasOwnProperty(x)) {
// Does this key exist in the property list?
if (x in o) {
// Yes this key does exist so its most likely this function has been invoked with an object parameter
// Return first argument as the hash of all arguments
return args[0];
}
}}
}
// Else loop through and account for the missing ones.
for (x in o) {if (o.hasOwnProperty(x)) {
t = typeof (args[i]);
if ((typeof (o[x]) === 'function' && o[x].test(args[i])) || (typeof (o[x]) === 'string' && (
(o[x].indexOf('s') > -1 && t === 'string') ||
(o[x].indexOf('o') > -1 && t === 'object') ||
(o[x].indexOf('i') > -1 && t === 'number') ||
(o[x].indexOf('a') > -1 && t === 'object') ||
(o[x].indexOf('f') > -1 && t === 'function')
))
) {
p[x] = args[i++];
}
else if (typeof (o[x]) === 'string' && o[x].indexOf('!') > -1) {
return false;
}
}}
return p;
},
// Returns a URL instance
url: function(path) {
// If the path is empty
if (!path) {
return window.location;
}
// Chrome and FireFox support new URL() to extract URL objects
else if (window.URL && URL instanceof Function && URL.length !== 0) {
return new URL(path, window.location);
}
// Ugly shim, it works!
else {
var a = document.createElement('a');
a.href = path;
return a.cloneNode(false);
}
},
diff: function(a, b) {
return b.filter(function(item) {
return a.indexOf(item) === -1;
});
},
// Get the different hash of properties unique to `a`, and not in `b`
diffKey: function(a, b) {
if (a || !b) {
var r = {};
for (var x in a) {
// Does the property not exist?
if (!(x in b)) {
r[x] = a[x];
}
}
return r;
}
return a;
},
// Unique
// Remove duplicate and null values from an array
// @param a array
unique: function(a) {
if (!Array.isArray(a)) { return []; }
return a.filter(function(item, index) {
// Is this the first location of item
return a.indexOf(item) === index;
});
},
isEmpty: function(obj) {
// Scalar
if (!obj)
return true;
// Array
if (Array.isArray(obj)) {
return !obj.length;
}
else if (typeof (obj) === 'object') {
// Object
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
}
return true;
},
//jscs:disable
/*!
** Thenable -- Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable
** Copyright (c) 2013-2014 Ralf S. Engelschall <http://engelschall.com>
** Licensed under The MIT License <http://opensource.org/licenses/MIT>
** Source-Code distributed on <http://github.com/rse/thenable>
*/
Promise: (function(){
/* promise states [Promises/A+ 2.1] */
var STATE_PENDING = 0; /* [Promises/A+ 2.1.1] */
var STATE_FULFILLED = 1; /* [Promises/A+ 2.1.2] */
var STATE_REJECTED = 2; /* [Promises/A+ 2.1.3] */
/* promise object constructor */
var api = function (executor) {
/* optionally support non-constructor/plain-function call */
if (!(this instanceof api))
return new api(executor);
/* initialize object */
this.id = "Thenable/1.0.6";
this.state = STATE_PENDING; /* initial state */
this.fulfillValue = undefined; /* initial value */ /* [Promises/A+ 1.3, 2.1.2.2] */
this.rejectReason = undefined; /* initial reason */ /* [Promises/A+ 1.5, 2.1.3.2] */
this.onFulfilled = []; /* initial handlers */
this.onRejected = []; /* initial handlers */
/* provide optional information-hiding proxy */
this.proxy = {
then: this.then.bind(this)
};
/* support optional executor function */
if (typeof executor === "function")
executor.call(this, this.fulfill.bind(this), this.reject.bind(this));
};
/* promise API methods */
api.prototype = {
/* promise resolving methods */
fulfill: function (value) { return deliver(this, STATE_FULFILLED, "fulfillValue", value); },
reject: function (value) { return deliver(this, STATE_REJECTED, "rejectReason", value); },
/* "The then Method" [Promises/A+ 1.1, 1.2, 2.2] */
then: function (onFulfilled, onRejected) {
var curr = this;
var next = new api(); /* [Promises/A+ 2.2.7] */
curr.onFulfilled.push(
resolver(onFulfilled, next, "fulfill")); /* [Promises/A+ 2.2.2/2.2.6] */
curr.onRejected.push(
resolver(onRejected, next, "reject" )); /* [Promises/A+ 2.2.3/2.2.6] */
execute(curr);
return next.proxy; /* [Promises/A+ 2.2.7, 3.3] */
}
};
/* deliver an action */
var deliver = function (curr, state, name, value) {
if (curr.state === STATE_PENDING) {
curr.state = state; /* [Promises/A+ 2.1.2.1, 2.1.3.1] */
curr[name] = value; /* [Promises/A+ 2.1.2.2, 2.1.3.2] */
execute(curr);
}
return curr;
};
/* execute all handlers */
var execute = function (curr) {
if (curr.state === STATE_FULFILLED)
execute_handlers(curr, "onFulfilled", curr.fulfillValue);
else if (curr.state === STATE_REJECTED)
execute_handlers(curr, "onRejected", curr.rejectReason);
};
/* execute particular set of handlers */
var execute_handlers = function (curr, name, value) {
/* global process: true */
/* global setImmediate: true */
/* global setTimeout: true */
/* short-circuit processing */
if (curr[name].length === 0)
return;
/* iterate over all handlers, exactly once */
var handlers = curr[name];
curr[name] = []; /* [Promises/A+ 2.2.2.3, 2.2.3.3] */
var func = function () {
for (var i = 0; i < handlers.length; i++)
handlers[i](value); /* [Promises/A+ 2.2.5] */
};
/* execute procedure asynchronously */ /* [Promises/A+ 2.2.4, 3.1] */
if (typeof process === "object" && typeof process.nextTick === "function")
process.nextTick(func);
else if (typeof setImmediate === "function")
setImmediate(func);
else
setTimeout(func, 0);
};
/* generate a resolver function */
var resolver = function (cb, next, method) {
return function (value) {
if (typeof cb !== "function") /* [Promises/A+ 2.2.1, 2.2.7.3, 2.2.7.4] */
next[method].call(next, value); /* [Promises/A+ 2.2.7.3, 2.2.7.4] */
else {
var result;
try { result = cb(value); } /* [Promises/A+ 2.2.2.1, 2.2.3.1, 2.2.5, 3.2] */
catch (e) {
next.reject(e); /* [Promises/A+ 2.2.7.2] */
return;
}
resolve(next, result); /* [Promises/A+ 2.2.7.1] */
}
};
};
/* "Promise Resolution Procedure" */ /* [Promises/A+ 2.3] */
var resolve = function (promise, x) {
/* sanity check arguments */ /* [Promises/A+ 2.3.1] */
if (promise === x || promise.proxy === x) {
promise.reject(new TypeError("cannot resolve promise with itself"));
return;
}
/* surgically check for a "then" method
(mainly to just call the "getter" of "then" only once) */
var then;
if ((typeof x === "object" && x !== null) || typeof x === "function") {
try { then = x.then; } /* [Promises/A+ 2.3.3.1, 3.5] */
catch (e) {
promise.reject(e); /* [Promises/A+ 2.3.3.2] */
return;
}
}
/* handle own Thenables [Promises/A+ 2.3.2]
and similar "thenables" [Promises/A+ 2.3.3] */
if (typeof then === "function") {
var resolved = false;
try {
/* call retrieved "then" method */ /* [Promises/A+ 2.3.3.3] */
then.call(x,
/* resolvePromise */ /* [Promises/A+ 2.3.3.3.1] */
function (y) {
if (resolved) return; resolved = true; /* [Promises/A+ 2.3.3.3.3] */
if (y === x) /* [Promises/A+ 3.6] */
promise.reject(new TypeError("circular thenable chain"));
else
resolve(promise, y);
},
/* rejectPromise */ /* [Promises/A+ 2.3.3.3.2] */
function (r) {
if (resolved) return; resolved = true; /* [Promises/A+ 2.3.3.3.3] */
promise.reject(r);
}
);
}
catch (e) {
if (!resolved) /* [Promises/A+ 2.3.3.3.3] */
promise.reject(e); /* [Promises/A+ 2.3.3.3.4] */
}
return;
}
/* handle other values */
promise.fulfill(x); /* [Promises/A+ 2.3.4, 2.3.3.4] */
};
/* export API */
return api;
})(),
//jscs:enable
// Event
// A contructor superclass for adding event menthods, on, off, emit.
Event: function() {
var separator = /[\s\,]+/;
// If this doesn't support getPrototype then we can't get prototype.events of the parent
// So lets get the current instance events, and add those to a parent property
this.parent = {
events: this.events,
findEvents: this.findEvents,
parent: this.parent,
utils: this.utils
};
this.events = {};
// On, subscribe to events
// @param evt string
// @param callback function
this.on = function(evt, callback) {
if (callback && typeof (callback) === 'function') {
var a = evt.split(separator);
for (var i = 0; i < a.length; i++) {
// Has this event already been fired on this instance?
this.events[a[i]] = [callback].concat(this.events[a[i]] || []);
}
}
return this;
};
// Off, unsubscribe to events
// @param evt string
// @param callback function
this.off = function(evt, callback) {
this.findEvents(evt, function(name, index) {
if (!callback || this.events[name][index] === callback) {
this.events[name][index] = null;
}
});
return this;
};
// Emit
// Triggers any subscribed events
this.emit = function(evt /*, data, ... */) {
// Get arguments as an Array, knock off the first one
var args = Array.prototype.slice.call(arguments, 1);
args.push(evt);
// Handler
var handler = function(name, index) {
// Replace the last property with the event name
args[args.length - 1] = (name === '*' ? evt : name);
// Trigger
this.events[name][index].apply(this, args);
};
// Find the callbacks which match the condition and call
var _this = this;
while (_this && _this.findEvents) {
// Find events which match
_this.findEvents(evt + ',*', handler);
_this = _this.parent;
}
return this;
};
//
// Easy functions
this.emitAfter = function() {
var _this = this;
var args = arguments;
setTimeout(function() {
_this.emit.apply(_this, args);
}, 0);
return this;
};
this.findEvents = function(evt, callback) {
var a = evt.split(separator);
for (var name in this.events) {if (this.events.hasOwnProperty(name)) {
if (a.indexOf(name) > -1) {
for (var i = 0; i < this.events[name].length; i++) {
// Does the event handler exist?
if (this.events[name][i]) {
// Emit on the local instance of this
callback.call(this, name, i);
}
}
}
}}
};
return this;
},
// Global Events
// Attach the callback to the window object
// Return its unique reference
globalEvent: function(callback, guid) {
// If the guid has not been supplied then create a new one.
guid = guid || '_hellojs_' + parseInt(Math.random() * 1e12, 10).toString(36);
// Define the callback function
window[guid] = function() {
// Trigger the callback
try {
if (callback.apply(this, arguments)) {
delete window[guid];
}
}
catch (e) {
console.error(e);
}
};
return guid;
},
// Trigger a clientside popup
// This has been augmented to support PhoneGap
popup: function(url, redirectUri, options) {
var documentElement = document.documentElement;
// Multi Screen Popup Positioning (http://stackoverflow.com/a/16861050)
// Credit: http://www.xtf.dk/2011/08/center-new-popup-window-even-on.html
// Fixes dual-screen position Most browsers Firefox
if (options.height && options.top === undefined) {
var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;
var height = screen.height || window.innerHeight || documentElement.clientHeight;
options.top = parseInt((height - options.height) / 2, 10) + dualScreenTop;
}
if (options.width && options.left === undefined) {
var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
var width = screen.width || window.innerWidth || documentElement.clientWidth;
options.left = parseInt((width - options.width) / 2, 10) + dualScreenLeft;
}
// Convert options into an array
var optionsArray = [];
Object.keys(options).forEach(function(name) {
var value = options[name];
optionsArray.push(name + (value !== null ? '=' + value : ''));
});
// Call the open() function with the initial path
//
// OAuth redirect, fixes URI fragments from being lost in Safari
// (URI Fragments within 302 Location URI are lost over HTTPS)
// Loading the redirect.html before triggering the OAuth Flow seems to fix it.
//
// Firefox decodes URL fragments when calling location.hash.
// - This is bad if the value contains break points which are escaped
// - Hence the url must be encoded twice as it contains breakpoints.
if (navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1) {
url = redirectUri + '#oauth_redirect=' + encodeURIComponent(encodeURIComponent(url));
}
var popup = window.open(
url,
'_blank',
optionsArray.join(',')
);
if (popup && popup.focus) {
popup.focus();
}
return popup;
},
// OAuth and API response handler
responseHandler: function(window, parent) {
var _this = this;
var p;
var location = window.location;
// Is this an auth relay message which needs to call the proxy?
p = _this.param(location.search);
// OAuth2 or OAuth1 server response?
if (p && p.state && (p.code || p.oauth_token)) {
var state = JSON.parse(p.state);
// Add this path as the redirect_uri
p.redirect_uri = state.redirect_uri || location.href.replace(/[\?\#].*$/, '');
// Redirect to the host
var path = _this.qs(state.oauth_proxy, p);
location.assign(path);
return;
}
// Save session, from redirected authentication
// #access_token has come in?
//
// FACEBOOK is returning auth errors within as a query_string... thats a stickler for consistency.
// SoundCloud is the state in the querystring and the token in the hashtag, so we'll mix the two together
p = _this.merge(_this.param(location.search || ''), _this.param(location.hash || ''));
// If p.state
if (p && 'state' in p) {
// Remove any addition information
// E.g. p.state = 'facebook.page';
try {
var a = JSON.parse(p.state);
_this.extend(p, a);
}
catch (e) {
var stateDecoded = decodeURIComponent(p.state);
try {
var b = JSON.parse(stateDecoded);
_this.extend(p, b);
}
catch (e) {
console.error('Could not decode state parameter');
}
}
// Access_token?
if (('access_token' in p && p.access_token) && p.network) {
if (!p.expires_in || parseInt(p.expires_in, 10) === 0) {
// If p.expires_in is unset, set to 0
p.expires_in = 0;
}
p.expires_in = parseInt(p.expires_in, 10);
p.expires = ((new Date()).getTime() / 1e3) + (p.expires_in || (60 * 60 * 24 * 365));
// Lets use the "state" to assign it to one of our networks
authCallback(p, window, parent);
}
// Error=?
// &error_description=?
// &state=?
else if (('error' in p && p.error) && p.network) {
p.error = {
code: p.error,
message: p.error_message || p.error_description
};
// Let the state handler handle it
authCallback(p, window, parent);
}
// API call, or a cancelled login
// Result is serialized JSON string
else if (p.callback && p.callback in parent) {
// Trigger a function in the parent
var res = 'result' in p && p.result ? JSON.parse(p.result) : false;
// Trigger the callback on the parent
callback(parent, p.callback)(res);
closeWindow();
}
// If this page is still open
if (p.page_uri) {
location.assign(p.page_uri);
}
}
// OAuth redirect, fixes URI fragments from being lost in Safari
// (URI Fragments within 302 Location URI are lost over HTTPS)
// Loading the redirect.html before triggering the OAuth Flow seems to fix it.
else if ('oauth_redirect' in p) {
location.assign(decodeURIComponent(p.oauth_redirect));
return;
}
// Trigger a callback to authenticate
function authCallback(obj, window, parent) {
var cb = obj.callback;
var network = obj.network;
// Trigger the callback on the parent
_this.store(network, obj);
// If this is a page request it has no parent or opener window to handle callbacks
if (('display' in obj) && obj.display === 'page') {
return;
}
// Remove from session object
if (parent && cb && cb in parent) {
try {
delete obj.callback;
}
catch (e) {}
// Update store
_this.store(network, obj);
// Call the globalEvent function on the parent
// It's safer to pass back a string to the parent,
// Rather than an object/array (better for IE8)
var str = JSON.stringify(obj);
try {
callback(parent, cb)(str);
}
catch (e) {
// Error thrown whilst executing parent callback
}
}
closeWindow();
}
function callback(parent, callbackID) {
if (callbackID.indexOf('_hellojs_') !== 0) {
return function() {
throw 'Could not execute callback ' + callbackID;
};
}
return parent[callbackID];
}
function closeWindow() {
if (window.frameElement) {
// Inside an iframe, remove from parent
parent.document.body.removeChild(window.frameElement);
}
else {
// Close this current window
try {
window.close();
}
catch (e) {}
// IOS bug wont let us close a popup if still loading
if (window.addEventListener) {
window.addEventListener('load', function() {
window.close();
});
}
}
}
}
});
// Events
// Extend the hello object with its own event instance
hello.utils.Event.call(hello);
///////////////////////////////////
// Monitoring session state
// Check for session changes
///////////////////////////////////
(function(hello) {
// Monitor for a change in state and fire
var oldSessions = {};
// Hash of expired tokens
var expired = {};
// Listen to other triggers to Auth events, use these to update this
hello.on('auth.login, auth.logout', function(auth) {
if (auth && typeof (auth) === 'object' && auth.network) {
oldSessions[auth.network] = hello.utils.store(auth.network) || {};
}
});
(function self() {
var CURRENT_TIME = ((new Date()).getTime() / 1e3);
var emit = function(eventName) {
hello.emit('auth.' + eventName, {
network: name,
authResponse: session
});
};
// Loop through the services
for (var name in hello.services) {if (hello.services.hasOwnProperty(name)) {
if (!hello.services[name].id) {
// We haven't attached an ID so dont listen.
continue;
}
// Get session
var session = hello.utils.store(name) || {};
var provider = hello.services[name];
var oldSess = oldSessions[name] || {};
// Listen for globalEvents that did not get triggered from the child
if (session && 'callback' in session) {
// To do remove from session object...
var cb = session.callback;
try {
delete session.callback;
}
catch (e) {}
// Update store
// Removing the callback
hello.utils.store(name, session);
// Emit global events
try {
window[cb](session);
}
catch (e) {}
}
// Refresh token
if (session && ('expires' in session) && session.expires < CURRENT_TIME) {
// If auto refresh is possible
// Either the browser supports
var refresh = provider.refresh || session.refresh_token;
// Has the refresh been run recently?
if (refresh && (!(name in expired) || expired[name] < CURRENT_TIME)) {
// Try to resignin
hello.emit('notice', name + ' has expired trying to resignin');
hello.login(name, {display: 'none', force: false});
// Update expired, every 10 minutes
expired[name] = CURRENT_TIME + 600;
}
// Does this provider not support refresh
else if (!refresh && !(name in expired)) {
// Label the event
emit('expired');
expired[name] = true;
}
// If session has expired then we dont want to store its value until it can be established that its been updated
continue;
}
// Has session changed?
else if (oldSess.access_token === session.access_token &&
oldSess.expires === session.expires) {
continue;
}
// Access_token has been removed
else if (!session.access_token && oldSess.access_token) {
emit('logout');
}
// Access_token has been created
else if (session.access_token && !oldSess.access_token) {
emit('login');
}
// Access_token has been updated
else if (session.expires !== oldSess.expires) {
emit('update');
}
// Updated stored session
oldSessions[name] = session;
// Remove the expired flags
if (name in expired) {
delete expired[name];
}
}}
// Check error events
setTimeout(self, 1000);
})();
})(hello);
// EOF CORE lib
//////////////////////////////////
/////////////////////////////////////////
// API
// @param path string
// @param query object (optional)
// @param method string (optional)
// @param data object (optional)
// @param timeout integer (optional)
// @param callback function (optional)
hello.api = function() {
// Shorthand
var _this = this;
var utils = _this.utils;
var error = utils.error;
// Construct a new Promise object
var promise = utils.Promise();
// Arguments
var p = utils.args({path: 's!', query: 'o', method: 's', data: 'o', timeout: 'i', callback: 'f'}, arguments);
// Method
p.method = (p.method || 'get').toLowerCase();
// Headers
p.headers = p.headers || {};
// Query
p.query = p.query || {};
// If get, put all parameters into query
if (p.method === 'get' || p.method === 'delete') {
utils.extend(p.query, p.data);
p.data = {};
}
var data = p.data = p.data || {};
// Completed event callback
promise.then(p.callback, p.callback);
// Remove the network from path, e.g. facebook:/me/friends
// Results in { network : facebook, path : me/friends }
if (!p.path) {
return promise.reject(error('invalid_path', 'Missing the path parameter from the request'));
}
p.path = p.path.replace(/^\/+/, '');
var a = (p.path.split(/[\/\:]/, 2) || [])[0].toLowerCase();
if (a in _this.services) {
p.network = a;
var reg = new RegExp('^' + a + ':?\/?');
p.path = p.path.replace(reg, '');
}
// Network & Provider
// Define the network that this request is made for
p.network = _this.settings.default_service = p.network || _this.settings.default_service;
var o = _this.services[p.network];
// INVALID
// Is there no service by the given network name?
if (!o) {
return promise.reject(error('invalid_network', 'Could not match the service requested: ' + p.network));
}
// PATH
// As long as the path isn't flagged as unavaiable, e.g. path == false
if (!(!(p.method in o) || !(p.path in o[p.method]) || o[p.method][p.path] !== false)) {
return promise.reject(error('invalid_path', 'The provided path is not available on the selected network'));
}
// PROXY
// OAuth1 calls always need a proxy
if (!p.oauth_proxy) {
p.oauth_proxy = _this.settings.oauth_proxy;
}
if (!('proxy' in p)) {
p.proxy = p.oauth_proxy && o.oauth && parseInt(o.oauth.version, 10) === 1;
}
// TIMEOUT
// Adopt timeout from global settings by default
if (!('timeout' in p)) {
p.timeout = _this.settings.timeout;
}
// Format response
// Whether to run the raw response through post processing.
if (!('formatResponse' in p)) {
p.formatResponse = true;
}
// Get the current session
// Append the access_token to the query
p.authResponse = _this.getAuthResponse(p.network);
if (p.authResponse && p.authResponse.access_token) {
p.query.access_token = p.authResponse.access_token;
}
var url = p.path;
var m;
// Store the query as options
// This is used to populate the request object before the data is augmented by the prewrap handlers.
p.options = utils.clone(p.query);
// Clone the data object
// Prevent this script overwriting the data of the incoming object.
// Ensure that everytime we run an iteration the callbacks haven't removed some data
p.data = utils.clone(data);
// URL Mapping
// Is there a map for the given URL?
var actions = o[{'delete': 'del'}[p.method] || p.method] || {};
// Extrapolate the QueryString
// Provide a clean path
// Move the querystring into the data
if (p.method === 'get') {
var query = url.split(/[\?#]/)[1];
if (query) {
utils.extend(p.query, utils.param(query));
// Remove the query part from the URL
url = url.replace(/\?.*?(#|$)/, '$1');
}
}
// Is the hash fragment defined
if ((m = url.match(/#(.+)/, ''))) {
url = url.split('#')[0];
p.path = m[1];
}
else if (url in actions) {
p.path = url;
url = actions[url];
}
else if ('default' in actions) {
url = actions['default'];
}
// Redirect Handler
// This defines for the Form+Iframe+Hash hack where to return the results too.
p.redirect_uri = _this.settings.redirect_uri;
// Define FormatHandler
// The request can be procesed in a multitude of ways
// Here's the options - depending on the browser and endpoint
p.xhr = o.xhr;
p.jsonp = o.jsonp;
p.form = o.form;
// Make request
if (typeof (url) === 'function') {
// Does self have its own callback?
url(p, getPath);
}
else {
// Else the URL is a string
getPath(url);
}
return promise.proxy;
// If url needs a base
// Wrap everything in
function getPath(url) {
// Format the string if it needs it
url = url.replace(/\@\{([a-z\_\-]+)(\|.*?)?\}/gi, function(m, key, defaults) {
var val = defaults ? defaults.replace(/^\|/, '') : '';
if (key in p.query) {
val = p.query[key];
delete p.query[key];
}
else if (p.data && key in p.data) {
val = p.data[key];
delete p.data[key];
}
else if (!defaults) {
promise.reject(error('missing_attribute', 'The attribute ' + key + ' is missing from the request'));
}
return val;
});
// Add base
if (!url.match(/^https?:\/\//)) {
url = o.base + url;
}
// Define the request URL
p.url = url;
// Make the HTTP request with the curated request object
// CALLBACK HANDLER
// @ response object
// @ statusCode integer if available
utils.request(p, function(r, headers) {
// Is this a raw response?
if (!p.formatResponse) {
// Bad request? error statusCode or otherwise contains an error response vis JSONP?
if (typeof headers === 'object' ? (headers.statusCode >= 400) : (typeof r === 'object' && 'error' in r)) {
promise.reject(r);
}
else {
promise.fulfill(r);
}
return;
}
// Should this be an object
if (r === true) {
r = {success:true};
}
else if (!r) {
r = {};
}
// The delete callback needs a better response
if (p.method === 'delete') {
r = (!r || utils.isEmpty(r)) ? {success:true} : r;
}
// FORMAT RESPONSE?
// Does self request have a corresponding formatter
if (o.wrap && ((p.path in o.wrap) || ('default' in o.wrap))) {
var wrap = (p.path in o.wrap ? p.path : 'default');
var time = (new Date()).getTime();
// FORMAT RESPONSE
var b = o.wrap[wrap](r, headers, p);
// Has the response been utterly overwritten?
// Typically self augments the existing object.. but for those rare occassions
if (b) {
r = b;
}
}
// Is there a next_page defined in the response?
if (r && 'paging' in r && r.paging.next) {
// Add the relative path if it is missing from the paging/next path
if (r.paging.next[0] === '?') {
r.paging.next = p.path + r.paging.next;
}
// The relative path has been defined, lets markup the handler in the HashFragment
else {
r.paging.next += '#' + p.path;
}
}
// Dispatch to listeners
// Emit events which pertain to the formatted response
if (!r || 'error' in r) {
promise.reject(r);
}
else {
promise.fulfill(r);
}
});
}
};
// API utilities
hello.utils.extend(hello.utils, {
// Make an HTTP request
request: function(p, callback) {
var _this = this;
var error = _this.error;
// This has to go through a POST request
if (!_this.isEmpty(p.data) && !('FileList' in window) && _this.hasBinary(p.data)) {
// Disable XHR and JSONP
p.xhr = false;
p.jsonp = false;
}
// Check if the browser and service support CORS
var cors = this.request_cors(function() {
// If it does then run this...
return ((p.xhr === undefined) || (p.xhr && (typeof (p.xhr) !== 'function' || p.xhr(p, p.query))));
});
if (cors) {
formatUrl(p, function(url) {
var x = _this.xhr(p.method, url, p.headers, p.data, callback);
x.onprogress = p.onprogress || null;
// Windows Phone does not support xhr.upload, see #74
// Feature detect
if (x.upload && p.onuploadprogress) {
x.upload.onprogress = p.onuploadprogress;
}
});
return;
}
// Clone the query object
// Each request modifies the query object and needs to be tared after each one.
var _query = p.query;
p.query = _this.clone(p.query);
// Assign a new callbackID
p.callbackID = _this.globalEvent();
// JSONP
if (p.jsonp !== false) {
// Clone the query object
p.query.callback = p.callbackID;
// If the JSONP is a function then run it
if (typeof (p.jsonp) === 'function') {
p.jsonp(p, p.query);
}
// Lets use JSONP if the method is 'get'
if (p.method === 'get') {
formatUrl(p, function(url) {
_this.jsonp(url, callback, p.callbackID, p.timeout);
});
return;
}
else {
// It's not compatible reset query
p.query = _query;
}
}
// Otherwise we're on to the old school, iframe hacks and JSONP
if (p.form !== false) {
// Add some additional query parameters to the URL
// We're pretty stuffed if the endpoint doesn't like these
p.query.redirect_uri = p.redirect_uri;
p.query.state = JSON.stringify({callback:p.callbackID});
var opts;
if (typeof (p.form) === 'function') {
// Format the request
opts = p.form(p, p.query);
}
if (p.method === 'post' && opts !== false) {
formatUrl(p, function(url) {
_this.post(url, p.data, opts, callback, p.callbackID, p.timeout);
});
return;
}
}
// None of the methods were successful throw an error
callback(error('invalid_request', 'There was no mechanism for handling this request'));
return;
// Format URL
// Constructs the request URL, optionally wraps the URL through a call to a proxy server
// Returns the formatted URL
function formatUrl(p, callback) {
// Are we signing the request?
var sign;
// OAuth1
// Remove the token from the query before signing
if (p.authResponse && p.authResponse.oauth && parseInt(p.authResponse.oauth.version, 10) === 1) {
// OAUTH SIGNING PROXY
sign = p.query.access_token;
// Remove the access_token
delete p.query.access_token;
// Enfore use of Proxy
p.proxy = true;
}
// POST body to querystring
if (p.data && (p.method === 'get' || p.method === 'delete')) {
// Attach the p.data to the querystring.
_this.extend(p.query, p.data);
p.data = null;
}
// Construct the path
var path = _this.qs(p.url, p.query);
// Proxy the request through a server
// Used for signing OAuth1
// And circumventing services without Access-Control Headers
if (p.proxy) {
// Use the proxy as a path
path = _this.qs(p.oauth_proxy, {
path: path,
access_token: sign || '',
// This will prompt the request to be signed as though it is OAuth1
then: p.proxy_response_type || (p.method.toLowerCase() === 'get' ? 'redirect' : 'proxy'),
method: p.method.toLowerCase(),
suppress_response_codes: true
});
}
callback(path);
}
},
// Test whether the browser supports the CORS response
request_cors: function(callback) {
return 'withCredentials' in new XMLHttpRequest() && callback();
},
// Return the type of DOM object
domInstance: function(type, data) {
var test = 'HTML' + (type || '').replace(
/^[a-z]/,
function(m) {
return m.toUpperCase();
}
) + 'Element';
if (!data) {
return false;
}
if (window[test]) {
return data instanceof window[test];
}
else if (window.Element) {
return data instanceof window.Element && (!type || (data.tagName && data.tagName.toLowerCase() === type));
}
else {
return (!(data instanceof Object || data instanceof Array || data instanceof String || data instanceof Number) && data.tagName && data.tagName.toLowerCase() === type);
}
},
// Create a clone of an object
clone: function(obj) {
// Does not clone DOM elements, nor Binary data, e.g. Blobs, Filelists
if (obj === null || typeof (obj) !== 'object' || obj instanceof Date || 'nodeName' in obj || this.isBinary(obj) || (typeof FormData === 'function' && obj instanceof FormData)) {
return obj;
}
if (Array.isArray(obj)) {
// Clone each item in the array
return obj.map(this.clone.bind(this));
}
// But does clone everything else.
var clone = {};
for (var x in obj) {
clone[x] = this.clone(obj[x]);
}
return clone;
},
// XHR: uses CORS to make requests
xhr: function(method, url, headers, data, callback) {
var r = new XMLHttpRequest();
var error = this.error;
// Binary?
var binary = false;
if (method === 'blob') {
binary = method;
method = 'GET';
}
method = method.toUpperCase();
// Xhr.responseType 'json' is not supported in any of the vendors yet.
r.onload = function(e) {
var json = r.response;
try {
json = JSON.parse(r.responseText);
}
catch (_e) {
if (r.status === 401) {
json = error('access_denied', r.statusText);
}
}
var headers = headersToJSON(r.getAllResponseHeaders());
headers.statusCode = r.status;
callback(json || (method === 'GET' ? error('empty_response', 'Could not get resource') : {}), headers);
};
r.onerror = function(e) {
var json = r.responseText;
try {
json = JSON.parse(r.responseText);
}
catch (_e) {}
callback(json || error('access_denied', 'Could not get resource'));
};
var x;
// Should we add the query to the URL?
if (method === 'GET' || method === 'DELETE') {
data = null;
}
else if (data && typeof (data) !== 'string' && !(data instanceof FormData) && !(data instanceof File) && !(data instanceof Blob)) {
// Loop through and add formData
var f = new FormData();
for (x in data) if (data.hasOwnProperty(x)) {
if (data[x] instanceof HTMLInputElement) {
if ('files' in data[x] && data[x].files.length > 0) {
f.append(x, data[x].files[0]);
}
}
else if (data[x] instanceof Blob) {
f.append(x, data[x], data.name);
}
else {
f.append(x, data[x]);
}
}
data = f;
}
// Open the path, async
r.open(method, url, true);
if (binary) {
if ('responseType' in r) {
r.responseType = binary;
}
else {
r.overrideMimeType('text/plain; charset=x-user-defined');
}
}
// Set any bespoke headers
if (headers) {
for (x in headers) {
r.setRequestHeader(x, headers[x]);
}
}
r.send(data);
return r;
// Headers are returned as a string
function headersToJSON(s) {
var r = {};
var reg = /([a-z\-]+):\s?(.*);?/gi;
var m;
while ((m = reg.exec(s))) {
r[m[1]] = m[2];
}
return r;
}
},
// JSONP
// Injects a script tag into the DOM to be executed and appends a callback function to the window object
// @param string/function pathFunc either a string of the URL or a callback function pathFunc(querystringhash, continueFunc);
// @param function callback a function to call on completion;
jsonp: function(url, callback, callbackID, timeout) {
var _this = this;
var error = _this.error;
// Change the name of the callback
var bool = 0;
var head = document.getElementsByTagName('head')[0];
var operaFix;
var result = error('server_error', 'server_error');
var cb = function() {
if (!(bool++)) {
window.setTimeout(function() {
callback(result);
head.removeChild(script);
}, 0);
}
};
// Add callback to the window object
callbackID = _this.globalEvent(function(json) {
result = json;
return true;
// Mark callback as done
}, callbackID);
// The URL is a function for some cases and as such
// Determine its value with a callback containing the new parameters of this function.
url = url.replace(new RegExp('=\\?(&|$)'), '=' + callbackID + '$1');
// Build script tag
var script = _this.append('script', {
id: callbackID,
name: callbackID,
src: url,
async: true,
onload: cb,
onerror: cb,
onreadystatechange: function() {
if (/loaded|complete/i.test(this.readyState)) {
cb();
}
}
});
// Opera fix error
// Problem: If an error occurs with script loading Opera fails to trigger the script.onerror handler we specified
//
// Fix:
// By setting the request to synchronous we can trigger the error handler when all else fails.
// This action will be ignored if we've already called the callback handler "cb" with a successful onload event
if (window.navigator.userAgent.toLowerCase().indexOf('opera') > -1) {
operaFix = _this.append('script', {
text: 'document.getElementById(\'' + callbackID + '\').onerror();'
});
script.async = false;
}
// Add timeout
if (timeout) {
window.setTimeout(function() {
result = error('timeout', 'timeout');
cb();
}, timeout);
}
// TODO: add fix for IE,
// However: unable recreate the bug of firing off the onreadystatechange before the script content has been executed and the value of "result" has been defined.
// Inject script tag into the head element
head.appendChild(script);
// Append Opera Fix to run after our script
if (operaFix) {
head.appendChild(operaFix);
}
},
// Post
// Send information to a remote location using the post mechanism
// @param string uri path
// @param object data, key value data to send
// @param function callback, function to execute in response
post: function(url, data, options, callback, callbackID, timeout) {
var _this = this;
var error = _this.error;
var doc = document;
// This hack needs a form
var form = null;
var reenableAfterSubmit = [];
var newform;
var i = 0;
var x = null;
var bool = 0;
var cb = function(r) {
if (!(bool++)) {
callback(r);
}
};
// What is the name of the callback to contain
// We'll also use this to name the iframe
_this.globalEvent(cb, callbackID);
// Build the iframe window
var win;
try {
// IE7 hack, only lets us define the name here, not later.
win = doc.createElement('<iframe name="' + callbackID + '">');
}
catch (e) {
win = doc.createElement('iframe');
}
win.name = callbackID;
win.id = callbackID;
win.style.display = 'none';
// Override callback mechanism. Triggger a response onload/onerror
if (options && options.callbackonload) {
// Onload is being fired twice
win.onload = function() {
cb({
response: 'posted',
message: 'Content was posted'
});
};
}
if (timeout) {
setTimeout(function() {
cb(error('timeout', 'The post operation timed out'));
}, timeout);
}
doc.body.appendChild(win);
// If we are just posting a single item
if (_this.domInstance('form', data)) {
// Get the parent form
form = data.form;
// Loop through and disable all of its siblings
for (i = 0; i < form.elements.length; i++) {
if (form.elements[i] !== data) {
form.elements[i].setAttribute('disabled', true);
}
}
// Move the focus to the form
data = form;
}
// Posting a form
if (_this.domInstance('form', data)) {
// This is a form element
form = data;
// Does this form need to be a multipart form?
for (i = 0; i < form.elements.length; i++) {
if (!form.elements[i].disabled && form.elements[i].type === 'file') {
form.encoding = form.enctype = 'multipart/form-data';
form.elements[i].setAttribute('name', 'file');
}
}
}
else {
// Its not a form element,
// Therefore it must be a JSON object of Key=>Value or Key=>Element
// If anyone of those values are a input type=file we shall shall insert its siblings into the form for which it belongs.
for (x in data) if (data.hasOwnProperty(x)) {
// Is this an input Element?
if (_this.domInstance('input', data[x]) && data[x].type === 'file') {
form = data[x].form;
form.encoding = form.enctype = 'multipart/form-data';
}
}
// Do If there is no defined form element, lets create one.
if (!form) {
// Build form
form = doc.createElement('form');
doc.body.appendChild(form);
newform = form;
}
var input;
// Add elements to the form if they dont exist
for (x in data) if (data.hasOwnProperty(x)) {
// Is this an element?
var el = (_this.domInstance('input', data[x]) || _this.domInstance('textArea', data[x]) || _this.domInstance('select', data[x]));
// Is this not an input element, or one that exists outside the form.
if (!el || data[x].form !== form) {
// Does an element have the same name?
var inputs = form.elements[x];
if (input) {
// Remove it.
if (!(inputs instanceof NodeList)) {
inputs = [inputs];
}
for (i = 0; i < inputs.length; i++) {
inputs[i].parentNode.removeChild(inputs[i]);
}
}
// Create an input element
input = doc.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', x);
// Does it have a value attribute?
if (el) {
input.value = data[x].value;
}
else if (_this.domInstance(null, data[x])) {
input.value = data[x].innerHTML || data[x].innerText;
}
else {
input.value = data[x];
}
form.appendChild(input);
}
// It is an element, which exists within the form, but the name is wrong
else if (el && data[x].name !== x) {
data[x].setAttribute('name', x);
data[x].name = x;
}
}
// Disable elements from within the form if they weren't specified
for (i = 0; i < form.elements.length; i++) {
input = form.elements[i];
// Does the same name and value exist in the parent
if (!(input.name in data) && input.getAttribute('disabled') !== true) {
// Disable
input.setAttribute('disabled', true);
// Add re-enable to callback
reenableAfterSubmit.push(input);
}
}
}
// Set the target of the form
form.setAttribute('method', 'POST');
form.setAttribute('target', callbackID);
form.target = callbackID;
// Update the form URL
form.setAttribute('action', url);
// Submit the form
// Some reason this needs to be offset from the current window execution
setTimeout(function() {
form.submit();
setTimeout(function() {
try {
// Remove the iframe from the page.
//win.parentNode.removeChild(win);
// Remove the form
if (newform) {
newform.parentNode.removeChild(newform);
}
}
catch (e) {
try {
console.error('HelloJS: could not remove iframe');
}
catch (ee) {}
}
// Reenable the disabled form
for (var i = 0; i < reenableAfterSubmit.length; i++) {
if (reenableAfterSubmit[i]) {
reenableAfterSubmit[i].setAttribute('disabled', false);
reenableAfterSubmit[i].disabled = false;
}
}
}, 0);
}, 100);
},
// Some of the providers require that only multipart is used with non-binary forms.
// This function checks whether the form contains binary data
hasBinary: function(data) {
for (var x in data) if (data.hasOwnProperty(x)) {
if (this.isBinary(data[x])) {
return true;
}
}
return false;
},
// Determines if a variable Either Is or like a FormInput has the value of a Blob
isBinary: function(data) {
return data instanceof Object && (
(this.domInstance('input', data) && data.type === 'file') ||
('FileList' in window && data instanceof window.FileList) ||
('File' in window && data instanceof window.File) ||
('Blob' in window && data instanceof window.Blob));
},
// Convert Data-URI to Blob string
toBlob: function(dataURI) {
var reg = /^data\:([^;,]+(\;charset=[^;,]+)?)(\;base64)?,/i;
var m = dataURI.match(reg);
if (!m) {
return dataURI;
}
var binary = atob(dataURI.replace(reg, ''));
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: m[1]});
}
});
// EXTRA: Convert FormElement to JSON for POSTing
// Wrappers to add additional functionality to existing functions
(function(hello) {
// Copy original function
var api = hello.api;
var utils = hello.utils;
utils.extend(utils, {
// DataToJSON
// This takes a FormElement|NodeList|InputElement|MixedObjects and convers the data object to JSON.
dataToJSON: function(p) {
var _this = this;
var w = window;
var data = p.data;
// Is data a form object
if (_this.domInstance('form', data)) {
data = _this.nodeListToJSON(data.elements);
}
else if ('NodeList' in w && data instanceof NodeList) {
data = _this.nodeListToJSON(data);
}
else if (_this.domInstance('input', data)) {
data = _this.nodeListToJSON([data]);
}
// Is data a blob, File, FileList?
if (('File' in w && data instanceof w.File) ||
('Blob' in w && data instanceof w.Blob) ||
('FileList' in w && data instanceof w.FileList)) {
data = {file: data};
}
// Loop through data if it's not form data it must now be a JSON object
if (!('FormData' in w && data instanceof w.FormData)) {
for (var x in data) if (data.hasOwnProperty(x)) {
if ('FileList' in w && data[x] instanceof w.FileList) {
if (data[x].length === 1) {
data[x] = data[x][0];
}
}
else if (_this.domInstance('input', data[x]) && data[x].type === 'file') {
continue;
}
else if (_this.domInstance('input', data[x]) ||
_this.domInstance('select', data[x]) ||
_this.domInstance('textArea', data[x])) {
data[x] = data[x].value;
}
else if (_this.domInstance(null, data[x])) {
data[x] = data[x].innerHTML || data[x].innerText;
}
}
}
p.data = data;
return data;
},
// NodeListToJSON
// Given a list of elements extrapolate their values and return as a json object
nodeListToJSON: function(nodelist) {
var json = {};
// Create a data string
for (var i = 0; i < nodelist.length; i++) {
var input = nodelist[i];
// If the name of the input is empty or diabled, dont add it.
if (input.disabled || !input.name) {
continue;
}
// Is this a file, does the browser not support 'files' and 'FormData'?
if (input.type === 'file') {
json[input.name] = input;
}
else {
json[input.name] = input.value || input.innerHTML;
}
}
return json;
}
});
// Replace it
hello.api = function() {
// Get arguments
var p = utils.args({path: 's!', method: 's', data:'o', timeout: 'i', callback: 'f'}, arguments);
// Change for into a data object
if (p.data) {
utils.dataToJSON(p);
}
return api.call(this, p);
};
})(hello);
/////////////////////////////////////
//
// Save any access token that is in the current page URL
// Handle any response solicited through iframe hash tag following an API request
//
/////////////////////////////////////
hello.utils.responseHandler(window, window.opener || window.parent);
|
(this["webpackJsonp@coreui/coreui-free-react-admin-template"]=this["webpackJsonp@coreui/coreui-free-react-admin-template"]||[]).push([[13],{620:function(e,t,r){"use strict";r.d(t,"a",(function(){return j}));var n=r(44),c=r(20),i=r(158),s=r(1),a=r.n(s),o=r(619),l=function(e){var t=e.name,r=e.text,s=Object(i.a)(e,["name","text"]),a=t?"https://coreui.io/react/docs/components/".concat(t):e.href;return Object(c.jsx)("div",{className:"card-header-actions",children:Object(c.jsx)(o.db,Object(n.a)(Object(n.a)({},s),{},{href:a,rel:"noreferrer noopener",target:"_blank",className:"card-header-action",children:Object(c.jsx)("small",{className:"text-muted",children:r||"docs"})}))})},j=a.a.memo(l)},621:function(e,t,r){"use strict";r.d(t,"a",(function(){return c}));var n=r(624);function c(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"!==typeof Symbol&&Symbol.iterator in Object(e)){var r=[],n=!0,c=!1,i=void 0;try{for(var s,a=e[Symbol.iterator]();!(n=(s=a.next()).done)&&(r.push(s.value),!t||r.length!==t);n=!0);}catch(o){c=!0,i=o}finally{try{n||null==a.return||a.return()}finally{if(c)throw i}}return r}}(e,t)||Object(n.a)(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}},623:function(e,t,r){"use strict";function n(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}r.d(t,"a",(function(){return n}))},624:function(e,t,r){"use strict";r.d(t,"a",(function(){return c}));var n=r(623);function c(e,t){if(e){if("string"===typeof e)return Object(n.a)(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Object(n.a)(e,t):void 0}}},659:function(e,t,r){"use strict";r.r(t);var n=r(20),c=r(621),i=r(1),s=r.n(i),a=r(619),o=r(622),l=(r(620),Object(i.lazy)((function(){return Promise.all([r.e(1),r.e(23)]).then(r.bind(null,688))})));t.default=function(){var e=s.a.useState(!0),t=Object(c.a)(e,2),r=(t[0],t[1],s.a.useState(!0)),i=Object(c.a)(r,2);i[0],i[1];return Object(n.jsxs)(n.Fragment,{children:[Object(n.jsx)(l,{}),Object(n.jsx)(a.wb,{children:Object(n.jsx)(a.u,{xs:"12",md:"12",children:Object(n.jsxs)(a.j,{children:[Object(n.jsxs)(a.n,{children:["Data Input",Object(n.jsx)("small",{children:" Source"})]}),Object(n.jsx)(a.k,{children:Object(n.jsxs)(a.J,{action:"",method:"post",encType:"multipart/form-data",className:"form-horizontal",children:[Object(n.jsxs)(a.K,{row:!0,children:[Object(n.jsx)(a.u,{md:"3",children:Object(n.jsx)(a.cb,{htmlFor:"text-input",children:"Sender"})}),Object(n.jsxs)(a.u,{xs:"12",md:"9",children:[Object(n.jsx)(a.S,{id:"text-input",name:"text-input",placeholder:"Addresss"}),Object(n.jsx)(a.L,{children:" "})]})]}),Object(n.jsxs)(a.K,{row:!0,children:[Object(n.jsx)(a.u,{md:"3",children:Object(n.jsx)(a.cb,{htmlFor:"text-input",children:"Receiver"})}),Object(n.jsxs)(a.u,{xs:"12",md:"9",children:[Object(n.jsx)(a.S,{id:"text-input",name:"text-input",placeholder:"Addresss"}),Object(n.jsx)(a.L,{children:" "})]})]}),Object(n.jsxs)(a.K,{row:!0,children:[Object(n.jsx)(a.u,{md:"3",children:Object(n.jsx)(a.cb,{htmlFor:"text-input",children:"Price"})}),Object(n.jsxs)(a.u,{xs:"12",md:"9",children:[Object(n.jsx)(a.S,{id:"text-input",name:"text-input",placeholder:"Value"}),Object(n.jsx)(a.L,{children:" "})]})]})]})}),Object(n.jsxs)(a.l,{children:[Object(n.jsxs)(a.f,{type:"submit",size:"sm",color:"primary",children:[Object(n.jsx)(o.a,{name:"cil-scrubber"})," Submit"]}),Object(n.jsxs)(a.f,{type:"reset",size:"sm",color:"danger",children:[Object(n.jsx)(o.a,{name:"cil-ban"})," Reset"]})]})]})})})]})}}}]);
//# sourceMappingURL=13.e4b95eb2.chunk.js.map
|
import { quad, block } from './helpers'
const lightMaterial = {
lambertian: {
// albedo: [1, 1, 1],
albedo: [0, 0, 0],
// emittance: [20, 15, 10]
emittance: [10, 10, 10]
}
}
const skyMaterial = {
lambertian: {
// albedo: [0.2, 0.2, 0.2],
albedo: [0, 0, 0],
emittance: [0xdd / 255, 0xee / 255, 1]
// emittance: [0.1, 0.1, 0.1]
}
}
const glassMaterial = {
// transmissive: {
fresnelSpecularTransmissive: {
// albedo: [0.9, 0.9, 0.9],
albedo: [1, 1, 1],
// refractiveIndex: 1.8
refractiveIndex: 1.62
// refractiveIndex: 1.333
}
}
const waterMaterial = {
// transmissive: {
fresnelSpecularTransmissive: {
albedo: [1, 1, 1],
// albedo: [0.7, 0.9, 1],
// albedo: [1, 1, 1],
// refractiveIndex: 1.8
// refractiveIndex: 1.62
refractiveIndex: 1.333
}
}
const mirrorMaterial = {
specular: {
albedo: [0.9, 0.9, 0.9],
emittance: [0, 0, 0]
}
}
const whiteMaterial = {
lambertian: {
albedo: [0.8, 0.8, 0.8]
}
}
const redMaterial = {
lambertian: {
albedo: [0.75, 0.25, 0.25]
}
}
const greenMaterial = {
lambertian: {
albedo: [0.25, 0.75, 0.25]
}
}
const cornellBox = [
// LIGHT
...quad(lightMaterial)(
[0.25, 1.0, 0.25],
[-0.25, 1.0, 0.25],
[-0.25, 1.0, -0.25],
[0.25, 1.0, -0.25]
),
// CEILING
...quad(whiteMaterial)(
[-0.25, 1.0, 0.25],
[-1, 1.0, 1],
[-1, 1.0, -1],
[-0.25, 1.0, -0.25]
),
...quad(whiteMaterial)(
[1, 1.0, 1],
[0.25, 1.0, 0.25],
[0.25, 1.0, -0.25],
[1, 1.0, -1]
),
...quad(whiteMaterial)(
[1, 1.0, 1],
[-1, 1.0, 1],
[-0.25, 1.0, 0.25],
[0.25, 1.0, 0.25]
),
...quad(whiteMaterial)(
[0.25, 1.0, -0.25],
[-0.25, 1.0, -0.25],
[-1, 1.0, -1],
[1, 1.0, -1]
),
// FLOOR
...quad(whiteMaterial)(
[-1.0, -1.0, 1.0],
[1.0, -1.0, 1.0],
[1.0, -1.0, -1.0],
[-1.0, -1.0, -1.0]
),
// // BACK
...quad(whiteMaterial)(
[-1.0, 1.0, 1.0],
[1.0, 1.0, 1.0],
[1.0, -1.0, 1.0],
[-1.0, -1.0, 1.0]
),
// RIGHT
...quad(greenMaterial)(
[1.0, 1.0, 1.0],
[1.0, 1.0, -1.0],
[1.0, -1.0, -1.0],
[1.0, -1.0, 1.0]
),
// LEFT
...quad(redMaterial)(
[-1.0, 1.0, -1.0],
[-1.0, 1.0, 1.0],
[-1.0, -1.0, 1.0],
[-1.0, -1.0, -1.0]
)
]
const cheapCornellBox = [
// // LIGHT
// {
// sphere: {
// center: [0, 1, 0],
// radius: 0.25,
// material: lightMaterial
// }
// },
// {
// implicit: {
// distancefunction: [
// { dfBox: [0.2, 0.02, 0.2] },
// { dfTranslate: [0.05, 1.02, 0.05] }
// ],
// material: lightMaterial
// }
// },
// CEILING
{
plane: {
normal: [0, -1, 0],
d: -1,
// material: whiteMaterial
material: skyMaterial
}
},
// FLOOR
{
plane: {
normal: [0, 1, 0],
d: -1,
material: whiteMaterial
}
},
// // BACK
{
plane: {
normal: [0, 0, -1],
d: -1,
// material: mirrorMaterial
material: whiteMaterial
}
},
// // FRONT (BEHIND CAMERA)
{
plane: {
normal: [0, 0, 1],
d: -1,
material: {
lambertian: {
albedo: [0, 0, 0]
}
}
}
},
// RIGHT
{
plane: {
normal: [-1, 0, 0],
d: -1,
material: greenMaterial
}
},
// LEFT
{
plane: {
normal: [1, 0, 0],
d: -1,
material: redMaterial
}
}
]
const skyAndGround = [
// SKY
{
sphere: {
center: [0, 1, 0],
radius: 100,
material: skyMaterial
}
}
// {
// plane: {
// normal: [0, 1, 0],
// d: -1,
// material: {
// lambertian: {
// // albedo: [0xff / 255, 0xe7 / 255, 0xd9 / 255]
// // albedo: [0.4, 0.25, 0.25]
// // albedo: [0.5, 0.5, 0.5]
// albedo: [0.5, 0.5, 0.5]
// // emittance: [0.1, 0.1, 0.1]
// }
// }
// }
// }
]
export default {
maxDepth: 20,
camera: {
position: [0, 0, -4],
basis: {
tangent: [1, 0, 0],
bitangent: [0, -1, 0],
normal: [0, 0, 1]
},
aperture: 0,
fieldOfView: 1 / 3,
// fieldOfView: 0.35,
focalLength: 10
// tMin: 0.00001,
// tMax: Infinity
},
geometry: {
group: [
// ...skyAndGround,
...cheapCornellBox,
// TWISTED BOX
{
implicit: {
distancefunction: [
{ dfBox: [0.3, 0.3, 0.3] },
// { dfTwist: Math.PI / 2 }
{ dfRotate: Math.PI / 10 }
// { dfTwist: Math.PI }
// { dfTranslate: [0.35, -0.75, -0.35] }
],
// material: whiteMaterial
material: glassMaterial
// material: redMaterial
}
}
// // TORUS
// {
// implicit: {
// distancefunction: [
// { dfTorus: { major: 0.25, minor: 0.15 } }
// // { dfTwist: Math.PI },
// // { dfTranslate: [0.35, -0.5, -0.35] }
// ],
// // material: whiteMaterial
// // material: glassMaterial
// material: redMaterial
// }
// }
// // SPHERE
// {
// sphere: {
// center: [0, 0, 0],
// // radius: 0,
// radius: 0.4,
// // material: whiteMaterial
// // material: mirrorMaterial
// material: glassMaterial
// }
// }
]
}
}
|
const should = require('should');
const sinon = require('sinon');
const Promise = require('bluebird');
const errors = require('@tryghost/errors');
const models = require('../../../core/server/models');
const permissions = require('../../../core/server/services/permissions');
const validation = require('../../../core/server/data/validation');
const {errors: commonErrors} = require('../../../core/server/lib/common');
const security = require('../../../core/server/lib/security');
const testUtils = require('../../utils');
describe('Unit: models/user', function () {
before(function () {
models.init();
});
afterEach(function () {
sinon.restore();
});
describe('updateLastSeen method', function () {
it('exists', function () {
should.equal(typeof models.User.prototype.updateLastSeen, 'function');
});
it('sets the last_seen property to new Date and returns a call to save', function () {
const instance = {
set: sinon.spy(),
save: sinon.stub().resolves()
};
const now = new Date();
const clock = sinon.useFakeTimers(now.getTime());
const returnVal = models.User.prototype.updateLastSeen.call(instance);
should.deepEqual(instance.set.args[0][0], {
last_seen: now
});
should.equal(returnVal, instance.save.returnValues[0]);
clock.restore();
});
});
describe('validation', function () {
beforeEach(function () {
sinon.stub(security.password, 'hash').resolves('$2a$10$we16f8rpbrFZ34xWj0/ZC.LTPUux8ler7bcdTs5qIleN6srRHhilG');
});
describe('blank', function () {
it('name cannot be blank', function () {
return models.User.add({email: 'test@ghost.org'})
.then(function () {
throw new Error('expected ValidationError');
})
.catch(function (err) {
(err instanceof errors.ValidationError).should.eql(true);
err.message.should.match(/users\.name/);
});
});
it('email cannot be blank', function () {
let data = {name: 'name'};
sinon.stub(models.User, 'findOne').resolves(null);
return models.User.add(data)
.then(function () {
throw new Error('expected ValidationError');
})
.catch(function (err) {
err.should.be.an.Array();
(err[0] instanceof errors.ValidationError).should.eql(true);
err[0].message.should.match(/users\.email/);
});
});
});
});
describe('fn: check', function () {
beforeEach(function () {
sinon.stub(security.password, 'hash').resolves('$2a$10$we16f8rpbrFZ34xWj0/ZC.LTPUux8ler7bcdTs5qIleN6srRHhilG');
});
it('user status is warn', function () {
sinon.stub(security.password, 'compare').resolves(true);
// NOTE: Add a user with a broken field to ensure we only validate changed fields on login
sinon.stub(validation, 'validateSchema').resolves();
const user = models.User.forge(testUtils.DataGenerator.forKnex.createUser({
status: 'warn-1',
email: 'test-9@example.de',
website: '!!!!!this-is-not-a-website!!!!'
}));
sinon.stub(models.User, 'getByEmail').resolves(user);
sinon.stub(models.User, 'isPasswordCorrect').resolves();
sinon.stub(user, 'updateLastSeen').resolves();
sinon.stub(user, 'save').resolves();
return models.User.check({email: user.get('email'), password: 'test'});
});
it('user status is active', function () {
const user = models.User.forge(testUtils.DataGenerator.forKnex.createUser({
status: 'active',
email: 'test@ghost.de'
}));
sinon.stub(models.User, 'getByEmail').resolves(user);
sinon.stub(models.User, 'isPasswordCorrect').resolves();
sinon.stub(user, 'updateLastSeen').resolves();
sinon.stub(user, 'save').resolves();
return models.User.check({email: user.get('email'), password: 'test'});
});
it('password is incorrect', function () {
const user = models.User.forge(testUtils.DataGenerator.forKnex.createUser({
status: 'active',
email: 'test@ghost.de'
}));
sinon.stub(models.User, 'getByEmail').resolves(user);
sinon.stub(models.User, 'isPasswordCorrect').rejects(new errors.ValidationError());
return models.User.check({email: user.get('email'), password: 'test'})
.catch(function (err) {
(err instanceof errors.ValidationError).should.eql(true);
});
});
it('status is locked', function () {
const user = models.User.forge(testUtils.DataGenerator.forKnex.createUser({
status: 'locked',
email: 'test@ghost.de'
}));
sinon.stub(models.User, 'getByEmail').resolves(user);
return models.User.check({email: user.get('email'), password: 'test'})
.catch(function (err) {
(err instanceof commonErrors.PasswordResetRequiredError).should.eql(true);
});
});
});
describe('permissible', function () {
function getUserModel(id, role, roleId) {
const hasRole = sinon.stub();
hasRole.withArgs(role).returns(true);
return {
id: id,
hasRole: hasRole,
related: sinon.stub().returns([{name: role, id: roleId}]),
get: sinon.stub().returns(id)
};
}
it('cannot delete owner', function (done) {
const mockUser = getUserModel(1, 'Owner');
const context = {user: 1};
models.User.permissible(mockUser, 'destroy', context, {}, testUtils.permissions.owner, true, true, true).then(() => {
done(new Error('Permissible function should have errored'));
}).catch((error) => {
error.should.be.an.instanceof(errors.NoPermissionError);
should(mockUser.hasRole.calledOnce).be.true();
done();
});
});
it('can always edit self', function () {
const mockUser = getUserModel(3, 'Contributor');
const context = {user: 3};
return models.User.permissible(mockUser, 'edit', context, {}, testUtils.permissions.contributor, false, true, true).then(() => {
should(mockUser.get.calledOnce).be.true();
});
});
it('cannot edit my status to inactive', function () {
const mockUser = getUserModel(3, 'Editor');
const context = {user: 3};
return models.User.permissible(mockUser, 'edit', context, {status: 'inactive'}, testUtils.permissions.editor, false, true, true)
.then(Promise.reject)
.catch((err) => {
err.should.be.an.instanceof(errors.NoPermissionError);
});
});
it('without related roles', function () {
sinon.stub(models.User, 'findOne').withArgs({
id: 3,
status: 'all'
}, {withRelated: ['roles']}).resolves(getUserModel(3, 'Contributor'));
const mockUser = {id: 3, related: sinon.stub().returns()};
const context = {user: 3};
return models.User.permissible(mockUser, 'edit', context, {}, testUtils.permissions.contributor, false, true, true)
.then(() => {
models.User.findOne.calledOnce.should.be.true();
});
});
describe('change role', function () {
function getUserToEdit(id, role) {
const hasRole = sinon.stub();
hasRole.withArgs(role).returns(true);
return {
id: id,
hasRole: hasRole,
related: sinon.stub().returns([role]),
get: sinon.stub().returns(id)
};
}
beforeEach(function () {
sinon.stub(models.User, 'getOwnerUser');
sinon.stub(permissions, 'canThis');
models.User.getOwnerUser.resolves({
id: testUtils.context.owner.context.user,
related: () => {
return {
at: () => {
return testUtils.permissions.owner.user.roles[0].id;
}
};
}
});
});
it('cannot change own role', function () {
const mockUser = getUserToEdit(testUtils.context.admin.context.user, testUtils.permissions.editor.user.roles[0]);
const context = testUtils.context.admin.context;
const unsafeAttrs = testUtils.permissions.editor.user;
return models.User.permissible(mockUser, 'edit', context, unsafeAttrs, testUtils.permissions.admin, false, true, true)
.then(Promise.reject)
.catch((err) => {
err.should.be.an.instanceof(errors.NoPermissionError);
});
});
it('is owner and does not change the role', function () {
const mockUser = getUserToEdit(testUtils.context.owner.context.user, testUtils.permissions.owner.user.roles[0]);
const context = testUtils.context.owner.context;
const unsafeAttrs = testUtils.permissions.owner.user;
return models.User.permissible(mockUser, 'edit', context, unsafeAttrs, testUtils.permissions.owner, false, true, true)
.then(() => {
models.User.getOwnerUser.calledOnce.should.be.true();
});
});
it('cannot change owner\'s role', function () {
const mockUser = getUserToEdit(testUtils.context.owner.context.user, testUtils.permissions.owner.user.roles[0]);
const context = testUtils.context.admin.context;
const unsafeAttrs = testUtils.permissions.editor.user;
return models.User.permissible(mockUser, 'edit', context, unsafeAttrs, testUtils.permissions.admin, false, true, true)
.then(Promise.reject)
.catch((err) => {
err.should.be.an.instanceof(errors.NoPermissionError);
});
});
it('admin can change author role', function () {
const mockUser = getUserToEdit(testUtils.context.author.context.user, testUtils.permissions.author.user.roles[0]);
const context = testUtils.context.admin.context;
const unsafeAttrs = testUtils.permissions.editor.user;
permissions.canThis.returns({
assign: {
role: sinon.stub().resolves()
}
});
return models.User.permissible(mockUser, 'edit', context, unsafeAttrs, testUtils.permissions.admin, true, true, true)
.then(() => {
models.User.getOwnerUser.calledOnce.should.be.true();
permissions.canThis.calledOnce.should.be.true();
});
});
it('author can\'t change admin role', function () {
const mockUser = getUserToEdit(testUtils.context.admin.context.user, testUtils.permissions.admin.user.roles[0]);
const context = testUtils.context.author.context;
const unsafeAttrs = testUtils.permissions.editor.user;
permissions.canThis.returns({
assign: {
role: sinon.stub().resolves()
}
});
return models.User.permissible(mockUser, 'edit', context, unsafeAttrs, testUtils.permissions.author, false, true, true)
.then(Promise.reject)
.catch((err) => {
err.should.be.an.instanceof(errors.NoPermissionError);
});
});
});
describe('as editor', function () {
it('can\'t edit another editor', function (done) {
const mockUser = getUserModel(3, 'Editor');
const context = {user: 2};
models.User.permissible(mockUser, 'edit', context, {}, testUtils.permissions.editor, true, true, true).then(() => {
done(new Error('Permissible function should have errored'));
}).catch((error) => {
error.should.be.an.instanceof(errors.NoPermissionError);
should(mockUser.hasRole.called).be.true();
should(mockUser.get.calledOnce).be.true();
done();
});
});
it('can\'t edit owner', function (done) {
const mockUser = getUserModel(3, 'Owner');
const context = {user: 2};
models.User.permissible(mockUser, 'edit', context, {}, testUtils.permissions.editor, true, true, true).then(() => {
done(new Error('Permissible function should have errored'));
}).catch((error) => {
error.should.be.an.instanceof(errors.NoPermissionError);
should(mockUser.hasRole.called).be.true();
should(mockUser.get.calledOnce).be.true();
done();
});
});
it('can\'t edit an admin', function (done) {
const mockUser = getUserModel(3, 'Administrator');
const context = {user: 2};
models.User.permissible(mockUser, 'edit', context, {}, testUtils.permissions.editor, true, true, true).then(() => {
done(new Error('Permissible function should have errored'));
}).catch((error) => {
error.should.be.an.instanceof(errors.NoPermissionError);
should(mockUser.hasRole.called).be.true();
should(mockUser.get.calledOnce).be.true();
done();
});
});
it('can edit author', function () {
const mockUser = getUserModel(3, 'Author');
const context = {user: 2};
return models.User.permissible(mockUser, 'edit', context, {}, testUtils.permissions.editor, true, true, true).then(() => {
should(mockUser.hasRole.called).be.true();
should(mockUser.get.calledOnce).be.true();
});
});
it('can edit contributor', function () {
const mockUser = getUserModel(3, 'Contributor');
const context = {user: 2};
return models.User.permissible(mockUser, 'edit', context, {}, testUtils.permissions.editor, true, true, true).then(() => {
should(mockUser.hasRole.called).be.true();
should(mockUser.get.calledOnce).be.true();
});
});
it('can destroy self', function () {
const mockUser = getUserModel(3, 'Editor');
const context = {user: 3};
return models.User.permissible(mockUser, 'destroy', context, {}, testUtils.permissions.editor, true, true, true).then(() => {
should(mockUser.hasRole.called).be.true();
should(mockUser.get.calledOnce).be.true();
});
});
it('can\'t destroy another editor', function (done) {
const mockUser = getUserModel(3, 'Editor');
const context = {user: 2};
models.User.permissible(mockUser, 'destroy', context, {}, testUtils.permissions.editor, true, true, true).then(() => {
done(new Error('Permissible function should have errored'));
}).catch((error) => {
error.should.be.an.instanceof(errors.NoPermissionError);
should(mockUser.hasRole.called).be.true();
should(mockUser.get.calledOnce).be.true();
done();
});
});
it('can\'t destroy an admin', function (done) {
const mockUser = getUserModel(3, 'Administrator');
const context = {user: 2};
models.User.permissible(mockUser, 'destroy', context, {}, testUtils.permissions.editor, true, true, true).then(() => {
done(new Error('Permissible function should have errored'));
}).catch((error) => {
error.should.be.an.instanceof(errors.NoPermissionError);
should(mockUser.hasRole.called).be.true();
should(mockUser.get.calledOnce).be.true();
done();
});
});
it('can destroy an author', function () {
const mockUser = getUserModel(3, 'Author');
const context = {user: 2};
return models.User.permissible(mockUser, 'destroy', context, {}, testUtils.permissions.editor, true, true, true).then(() => {
should(mockUser.hasRole.called).be.true();
should(mockUser.get.calledOnce).be.true();
});
});
it('can destroy a contributor', function () {
const mockUser = getUserModel(3, 'Contributor');
const context = {user: 2};
return models.User.permissible(mockUser, 'destroy', context, {}, testUtils.permissions.editor, true, true, true).then(() => {
should(mockUser.hasRole.called).be.true();
should(mockUser.get.calledOnce).be.true();
});
});
});
});
describe('transferOwnership', function () {
beforeEach(function () {
sinon.stub(models.Role, 'findOne');
models.Role.findOne
.withArgs({name: 'Owner'})
.resolves(testUtils.permissions.owner.user.roles[0]);
models.Role.findOne
.withArgs({name: 'Administrator'})
.resolves(testUtils.permissions.admin.user.roles[0]);
sinon.stub(models.User, 'findOne');
});
it('Cannot transfer ownership if not owner', function () {
const loggedInUser = testUtils.context.admin;
const userToChange = loggedInUser;
const contextUser = sinon.stub();
contextUser.toJSON = sinon.stub().returns(testUtils.permissions.admin.user);
models.User
.findOne
.withArgs({id: loggedInUser.context.user}, {withRelated: ['roles']})
.resolves(contextUser);
return models.User.transferOwnership({id: loggedInUser.context.user}, loggedInUser)
.then(Promise.reject)
.catch((err) => {
err.should.be.an.instanceof(errors.NoPermissionError);
});
});
it('Owner tries to transfer ownership to editor', function () {
const loggedInUser = testUtils.context.owner;
const userToChange = testUtils.context.editor;
const loggedInContext = {
toJSON: sinon.stub().returns(testUtils.permissions.owner.user)
};
const userToChangeContext = {
toJSON: sinon.stub().returns(
// Test utils don't contain `status` which is required
Object.assign({status: 'active'}, testUtils.permissions.editor.user)
)
};
models.User
.findOne
.withArgs({id: loggedInUser.context.user}, {withRelated: ['roles']})
.resolves(loggedInContext);
models.User
.findOne
.withArgs({id: userToChange.context.user}, {withRelated: ['roles']})
.resolves(userToChangeContext);
return models.User.transferOwnership({id: userToChange.context.user}, loggedInUser)
.then(Promise.reject)
.catch((err) => {
err.should.be.an.instanceof(errors.ValidationError);
err.message.indexOf('Only administrators can')
.should.be.aboveOrEqual(0, 'contains correct error message');
});
});
it('Owner tries to transfer ownership to suspended user', function () {
const loggedInUser = testUtils.context.owner;
const userToChange = testUtils.context.admin;
const userToChangeJSON = Object.assign({status: 'inactive'}, testUtils.permissions.admin.user);
const loggedInContext = {
toJSON: sinon.stub().returns(testUtils.permissions.owner.user)
};
const userToChangeContext = {
toJSON: sinon.stub().returns(userToChangeJSON)
};
models.User
.findOne
.withArgs({id: loggedInUser.context.user}, {withRelated: ['roles']})
.resolves(loggedInContext);
models.User
.findOne
.withArgs({id: userToChange.context.user}, {withRelated: ['roles']})
.resolves(userToChangeContext);
return models.User.transferOwnership({id: userToChange.context.user}, loggedInUser)
.then(Promise.reject)
.catch((err) => {
err.should.be.an.instanceof(errors.ValidationError);
err.message.indexOf('Only active administrators can')
.should.be.aboveOrEqual(0, 'contains correct error message');
});
});
});
describe('isSetup', function () {
it('active', function () {
sinon.stub(models.User, 'getOwnerUser').resolves({get: sinon.stub().returns('active')});
return models.User.isSetup()
.then((result) => {
result.should.be.true();
});
});
it('inactive', function () {
sinon.stub(models.User, 'getOwnerUser').resolves({get: sinon.stub().returns('inactive')});
return models.User.isSetup()
.then((result) => {
result.should.be.false();
});
});
});
});
|
(function(){
var who = window.who || (window.who = {});
who.wikitoc = function(){
var height = 600,
maxRectWidth = 30,
oneDayPixel = 0.5,
x2,
allDates,
allDatesString,
morePixel,
dispatch = d3.dispatch("clicked");
function wikitoc(selection){
selection.each(function(data){
var chart;
var data = d3.entries(data)
var maxChapter = d3.max(data, function(d){return d.value.clusters.length})
allDatesString = data.map(function(d){return d.key});
allDates = data.map(function(d){return d3.time.day.floor(new Date(d.key))});
var allDatesInterval = d3.time.day.range(allDates[0], d3.time.day.offset(allDates[allDates.length-1],1))
var maxRectWPadding = maxRectWidth-(maxRectWidth*0.2);
var width = ((allDatesInterval.length - allDates.length)*oneDayPixel) + (allDates.length*maxRectWidth)
if (selection.select('svg').empty()){
chart = selection.append('svg')
.attr('width', Math.round(morePixel - maxRectWidth + width + (allDates.length*maxRectWidth)))
.attr('height', height)
}
else
{
chart = selection.select('svg')
.attr('width', Math.round(morePixel - maxRectWidth + width + (allDates.length*maxRectWidth)))
.attr('height', height)
}
var x = d3.scale.ordinal().rangeRoundBands([0, width-((allDatesInterval.length - allDates.length)*oneDayPixel)],0.1,0);
var xDomain = allDates
x.domain(xDomain)
x2 = d3.time.scale().rangeRound([0, width]);
var x2Domain = [allDates[0], allDates[allDates.length-1] ]
x2.domain(x2Domain)
var y = d3.scale.ordinal().rangeRoundBands([50, height], 0.3, 0);
var yDomain = d3.range(maxChapter)
y.domain(yDomain)
data.forEach(function(d,i){
d.value.clusters.forEach(function(e,f){
e.key = d.key
e.y = y(f);
e.x = x2(d3.time.day.floor(new Date(d.key))) + (i*maxRectWidth);
})
})
var allValues = d3.merge(data.map(function(d){return d.value.clusters}))
var nestValues = d3.nest()
.key(function(d) { return d.name; })
.entries(allValues);
var line = d3.svg.line()
.interpolate(function(points){
var path = "";
for (var i = 0; i < points.length; i++) {
if(i != points.length-1){
path += points[i][0] + "," + points[i][1] + " L" + (points[i][0]+maxRectWPadding) + "," + (points[i][1]) + " C";
var xControl = (points[i+1][0] - (points[i][0]+maxRectWPadding))/2;
path += ((points[i][0]+maxRectWPadding) + xControl) + "," + points[i][1] + " " + ((points[i][0]+maxRectWPadding) + xControl) + "," + points[i+1][1] + " ";
}else{
path+= points[i][0] + "," + points[i][1] + " L" + (points[i][0]+(maxRectWidth/2)) + "," + (points[i][1])
}
}
return path;
})
.x(function(d) { return d.x })
.y(function(d) { return d.y + y.rangeBand()/2})
var linesGroup = chart.selectAll('.lineGroup').data(nestValues)
linesGroup.enter().append("path")
.attr("class",function(d){return d.key.replace(/\s+/g, '') + " lineGroup"})
.attr("d", function(d) { return line(d.values)})
.attr("fill", "none")
.attr("stroke", "grey")
.attr("stroke-width",1)
.attr("stroke-opacity", 1)
var editGroup = chart.selectAll('.editGroup').data(data)
editGroup
.enter()
.append("g")
.attr("class", "editGroup")
.attr("transform", function(d,i){return "translate(" + (x2(d3.time.day.floor(new Date(d.key))) + (i*maxRectWidth) )+ ",0)"})
var editToc = editGroup.selectAll('rect').data(function(d){return d.value.clusters})
editToc
.enter()
.append('rect')
.attr("y", function(d,i){
if(d.group == 1){return y(i)}
else{return y(i) + (y.rangeBand()*0.6)/2}
})
.attr("x", 0)
.attr("width", function(d){
return x.rangeBand()
})
.attr("height", function(d){
if(d.group == 1){return y.rangeBand()}
else{return (y.rangeBand()*0.6)}
})
.attr("fill", function(d,i){ //here starts very bad parctice
if(d.type == "dead"){return "none"}
else{
if(d.group == 1){return colors[d.name]}
else {
var counter = 1
var data = d3.select(this.parentNode).data()[0].value.clusters[i - counter]
if(data.type == "dead"){
counter++
data = d3.select(this.parentNode).data()[0].value.clusters[i - counter]
}
if(data && data.group == 1 ){
var pn = data.name;
var pnl = colors[pn]
return pnl
}
else if (data){
var counter = 1
var pnl = d3.select(this.parentNode.childNodes[i-counter]).attr("fill")
if(pnl == "black" || pnl == "none"){
counter++
pnl = d3.select(this.parentNode.childNodes[i-counter]).attr("fill")
}
return pnl
}else{
return colors[d.name]
}
}
}
}) //here ends very bad parctice
.attr("fill-opacity", 1)
.attr("stroke-opacity", 1)
.attr("stroke", function(d){
if(d.type == "new"){
return 'black'
}else{return 'none'}
})
.attr("class", function(d){return d.name})
.on("click", function(d){
if (!d.click){
d.click = true;
chart.selectAll('rect')
.transition()
.attr("fill-opacity", function(e){
if(e.name != d.name){return 0.2}
else{return 1}
})
.attr("stroke-opacity", function(e){
if(e.name != d.name){return 0.2}
else{return 1}
})
chart.selectAll('path.lineGroup')
.attr("stroke-opacity", function(e){
if(e.key != d.name){return 0}
else{return 1}
})
}else{
chart.selectAll('rect')
.transition()
.attr("fill-opacity", function(e){e.click = false; return 1})
.attr("stroke-opacity", 1)
.attr("stroke", function(e){
if(e.type == 'new'){return 'black'}
else{return "none"}
})
chart.selectAll('path.lineGroup')
.transition()
.attr("stroke-opacity", 1)
}
})
var editDate = editGroup.selectAll('text').data(function(d){return [d]})
editDate
.enter()
.append('text')
.attr("y", 15)
.attr('font-family','Montserrat')
.attr('font-size',11)
.attr('font-weight',400)
.attr('dy', '0.71em')
.attr('text-anchor','middle')
.text(function(d){
var date = new Date(d.key)
return date.getFullYear() + " " + months[date.getMonth()] + " " + date.getDate();
})
.call(wrap, maxRectWidth, maxRectWidth/2)
var editTocX = editGroup.selectAll('.crossGroup').data(function(d){return d.value.clusters})
editTocX
.enter()
.append('path')
.attr("class", "crossGroup")
.attr("transform", function(d,i){
return "translate(" + maxRectWidth/2 + "," + (y(i)+y.rangeBand()/2) + ") rotate(45)"
})
.filter(function(d){return d.type == "dead"})
.attr("d", d3.svg.symbol().type("cross").size(40))
.attr("fill", "black")
}); //end selection
} // end wikitoc
wikitoc.height = function(x){
if (!arguments.length) return height;
height = x;
return wikitoc;
}
wikitoc.maxRectWidth = function(x){
if (!arguments.length) return maxRectWidth;
maxRectWidth = x;
return wikitoc;
}
wikitoc.oneDayPixel = function(x){
if (!arguments.length) return oneDayPixel;
oneDayPixel = x;
return wikitoc;
}
wikitoc.getPixel = function(x){
if (!arguments.length) return;
var pos = allDatesString.indexOf(x)
var pixel = x2(d3.time.day.floor(new Date(x))) + (pos*maxRectWidth);
return pixel;
}
wikitoc.morePixel = function(x){
if (!arguments.length) return morePixel;
morePixel = x;
return wikitoc;
}
var colors = {
'Adverse_effects': '#993333',
'Birth_control_methods': '#449093',
'Effectiveness': '#998250',
'Effects': '#998250',
'Etymology_and_movement': '#094A65',
'Definition': '#094A65',
'External_Links': '#819A90',
'External_links': '#819A90',
'Further_reading': '#B8DBCD',
'History': '#4F8D3C',
'History_of_Birth_Control': '#4F8D3C',
'History_of_birth_control': '#4F8D3C',
'History_of_birth_control_2': '#4F8D3C',
'History_of_birth_control_techniques_and_methods': '#4F8D3C',
'In_other_animals': '#346280',
'Legality': '#662B84',
'Mechanisms_of_action': '#A0BCA4',
'Methods': '#449093',
'Misconceptions': '#CC6632',
'Modern_Birth_Control_Methods:': '#662B84',
'Modern_Folklore': '#CC6632',
'Modern_birth_control_methods': '#662B84',
'Modern_birth_control_methods:': '#662B84',
'Modern_birth_control_methods_2': '#662B84',
'Myths': '#CC6632',
'Other_animals': '#346280',
'Prevalence': '#94616D',
'Quotes': '#A0BCA4',
'Quote': '#A0BCA4',
'References': '#78AEAA',
'Religious_and_Cultural_Attitudes_to_Birth_Control': '#E9AB45',
'Religious_and_cultural_attitudes': '#E9AB45',
'Religious_and_cultural_attitudes_to_birth_control': '#E9AB45',
'Religious_and_cultural_attitudes_toward_birth_control': '#E9AB45',
'Religious_and_cultural_attitudes_to_birth_control_2': '#E9AB45',
'Research': '#845597',
'Research_directions': '#845597',
'See_also': '#B8DBCD',
'Side_effects': '#74A460',
'Society_and_culture': '#E9AB45',
'Traditional_Birth_Control_Methods:': '#449093',
'Traditional_birth_control_methods': '#449093',
'Traditional_birth_control_methods:': '#449093',
'Traditional_birth_control_methods_2': '#449093',
//for family planning
'Components_of_Family_Planning': '#CC6632',
'Definitions': '#449093',
'Purposes': '#449093',
'Policy': '#662B84',
'Regional_variations': '#662B84',
'Family_Planning_Policy_in_the_United_States':'#662B84',
'Modern_methods': '#E9AB45',
'Planning_Children': '#EA9651',
'World_Contraception_Day': '#B83935',
'Birth_control': '#4F8D3C',
'Natural_family_planning': '#998250',
'See_Also': '#B8DBCD',
'International_oversight': '#998250'
}
function wrap(text, width, x) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", x).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
var months = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
d3.rebind(wikitoc, dispatch, 'on');
return wikitoc;
}
})();
|
//code from carlos' grammar tests need to modify
import assert from "assert"
import ast from "../src/ast.js"
// Programs expected to be syntactically correct
const syntaxChecks = [
["print statements", 'reveal "Place your bets"'],
["integer declaration", "chip x: 5"],
["string declaration", 'stringBet y: "hello!"'],
["float declaration", "change z: 100.52"],
["boolean declaration for true", "playingOnTilt t: hit"],
["boolean declaration for false", "playingOnTilt f: miss"],
[
"const declaration for strings",
'constantPressure stringBet name: "I should be winning more"',
],
["arithmetic sum", "chip sum: 9 + 10"],
["arithmetic difference", "chip difference : 9 - 10"],
["arithmetic multiplication", "chip multiplication : 9 * 10"],
["arithmetic division", "change division : 9 / 10"],
["arithmetic exponents", "chip exponents : 9 ** 10"],
["arithmetic modulus", "chip modulus : 9 % 10"],
[
"if else function",
`excuses x == 0 $. cashout hit .$ followingExcuses hit $. cashout miss.$ noMoreExcuses $. reveal "what".$`,
],
["ternary function", `total == 21 ? reveal "Stand" : hitOrBust(total)`],
["function call", "add(9, 10)"],
["reassignment", "x: pog"],
["for loop", "playingLoose (chip y: 0, y < 20, y+$) $.y incrementBy 5.$"],
[
"function declaration",
"straddle playingOnTilt nice(chip: num) $.cashout num == 69.$",
],
[
"while loop",
`contemplating patience != 0 $.
reveal "What is taking so long!?"
patience -$
.$`,
],
["unary negation", `excuses !negative $.reveal "Is this positive?".$`],
["binary and/or", "reveal burger && fries || tendies"],
["parentheses on expressions", "(-2)**2"],
["+= operator", "x incrementBy 8"],
["-= operator", "unlucky decrementBy allIn"],
["array instantiation", "flop chip hand: [2, 7, 10, 7, 10]"],
["subscripts", "stringBet lost: curseWords[2]"],
["array expression", '[1, 3, "5", odd]'],
["optinal type instantiation", 'stringBet? isItThere: "It is this time"'],
// ["complex var assignment", "c(5)[2] = 100;c.p.r=1;c.q(8)[2](1,1).z=1;"],
// ["complex var bumps", "c(5)[2]++;c.p.r++;c.q(8)[2](1,1).z--;"],
// ["call in statement", "let x = 1;\nf(100);\nprint(1);"],
// ["call in exp", "print(5 * f(x, y, 2 * y));"],
// ["short if", "if true { print(1); }"],
// ["longer if", "if true { print(1); } else { print(1); }"],
// ["even longer if", "if true { print(1); } else if false { print(1);}"],
// ["while with empty block", "while true {}"],
// ["while with one statement block", "while true { let x = 1; }"],
// ["repeat with long block", "repeat 2 { print(1);\nprint(2);print(3); }"],
// ["if inside loop", "repeat 3 { if true { print(1); } }"],
// ["for closed range", "for i in 2...9*1 {}"],
// ["for half-open range", "for i in 2..<9*1 {}"],
// ["for collection-as-id", "for i in things {}"],
// ["for collection-as-lit", "for i in [3,5,8] {}"],
// ["conditional", "return x?y:z?y:p;"],
// ["??", "return a ?? b ?? c ?? d;"],
// ["ors can be chained", "print(1 || 2 || 3 || 4 || 5);"],
// ["ands can be chained", "print(1 && 2 && 3 && 4 && 5);"],
// ["bitwise ops", "return (1|2|3) + (4^5^6) + (7&8&9);"],
// ["relational operators", "print(1<2||1<=2||1==2||1!=2||1>=2||1>2);"],
// ["shifts", "return 3 << 5 >> 8 << 13 >> 21;"],
// ["arithmetic", "return 2 * x + 3 / 5 - -1 % 7 ** 3 ** 3;"],
// ["length", "return #c; return #[1,2,3];"],
// ["boolean literals", "let x = false || true;"],
// ["all numeric literal forms", "print(8 * 89.123 * 1.3E5 * 1.3E+5 * 1.3E-5);"],
// ["empty array literal", "print(emptyArrayOf(int));"],
// ["nonempty array literal", "print([1, 2, 3]);"],
// ["some operator", "return some dog;"],
// ["no operator", "return no dog;"],
// ["parentheses", "print(83 * ((((((((-(13 / 21))))))))) + 1 - 0);"],
// ["variables in expression", "return r.p(3,1)[9]?.x?.y.z.p()(5)[1];"],
// ["more variables", "return c(3).p?.oh(9)[2][2].nope(1)[3](2);"],
// ["indexing array literals", "print([1,2,3][1]);"],
// ["member expression on string literal", `print("hello".append("there"));`],
// ["non-Latin letters in identifiers", "let コンパイラ = 100;"],
// ["a simple string literal", 'print("hello😉😬💀🙅🏽♀️—`");'],
// ["string literal with escapes", 'return "a\\n\\tbc\\\\de\\"fg";'],
// ["u-escape", 'print("\\u{a}\\u{2c}\\u{1e5}\\u{ae89}\\u{1f4a9}\\u{10ffe8}");'],
// ["end of program inside comment", "print(0); // yay"],
// ["comments with no text", "print(1);//\nprint(0);//"],
]
// Programs with syntax errors that the parser will detect
const syntaxErrors = [
["non-letter in an identifier", "chip ab😭c: 2;", /Line 1, col 8:/],
["illegal expression", "chip x = reveal -2", /Line 1, col 8:/],
// ["malformed number", "let x= 2.;", /Line 1, col 10:/],
// ["a float with an E but no exponent", "let x = 5E * 11;", /Line 1, col 10:/],
// ["a missing right operand", "print(5 -);", /Line 1, col 10:/],
// ["a non-operator", "print(7 * ((2 _ 3));", /Line 1, col 15:/],
// ["an expression starting with a )", "return );", /Line 1, col 8:/],
// ["a statement starting with expression", "x * 5;", /Line 1, col 3:/],
// ["an illegal statement on line 2", "print(5);\nx * 5;", /Line 2, col 3:/],
// ["a statement starting with a )", "print(5);\n)", /Line 2, col 1:/],
// ["an expression starting with a *", "let x = * 71;", /Line 1, col 9:/],
// ["negation before exponentiation", "print(-2**2);", /Line 1, col 10:/],
// ["mixing ands and ors", "print(1 && 2 || 3);", /Line 1, col 15:/],
// ["mixing ors and ands", "print(1 || 2 && 3);", /Line 1, col 15:/],
// ["associating relational operators", "print(1 < 2 < 3);", /Line 1, col 13:/],
// ["while without braces", "while true\nprint(1);", /Line 2, col 1/],
// ["if without braces", "if x < 3\nprint(1);", /Line 2, col 1/],
// ["while as identifier", "let for = 3;", /Line 1, col 5/],
// ["if as identifier", "let if = 8;", /Line 1, col 5/],
// ["unbalanced brackets", "function f(): int[;", /Line 1, col 18/],
// ["empty array without type", "print([]);", /Line 1, col 9/],
// ["bad array literal", "print([1,2,]);", /Line 1, col 12/],
// ["empty subscript", "print(a[]);", /Line 1, col 9/],
// ["true is not assignable", "true = 1;", /Line 1, col 5/],
// ["false is not assignable", "false = 1;", /Line 1, col 6/],
// ["no-paren function type", "function f(g:int->int) {}", /Line 1, col 17/],
// ["string lit with unknown escape", 'print("ab\\zcdef");', /col 11/],
// ["string lit with newline", 'print("ab\\zcdef");', /col 11/],
// ["string lit with quote", 'print("ab\\zcdef");', /col 11/],
// ["string lit with code point too long", 'print("\\u{1111111}");', /col 17/],
]
describe("The parser", () => {
for (const [scenario, source] of syntaxChecks) {
it(`recognizes ${scenario}`, () => {
assert(ast(source))
})
}
for (const [scenario, source, errorMessagePattern] of syntaxErrors) {
it(`throws on ${scenario}`, () => {
assert.throws(() => ast(source), errorMessagePattern)
})
}
})
|
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = function (config, options) {
config = config || {};
if (!options.isDev) {
config.minify = {
minimize: true,
removeComments: true,
collapseWhitespace: true,
minifyCSS: false,
minifyJS: true,
removeScriptTypeAttributes: true,
removeStyleTypeAttributes: true
};
}
config.links = [
// {
// rel: 'preconnect',
// href: 'https://api.hostmon.ru'
// },
{
rel: 'preconnect',
href: 'https://fonts.googleapis.com'
},
{
rel: 'stylesheet',
href: 'https://fonts.googleapis.com/css?family=Roboto:300,400,500',
},
{
rel: 'stylesheet',
href: 'https://fonts.googleapis.com/icon?family=Material+Icons',
},
];
config.meta = [
{
'http-equiv': 'Content-Security-Policy',
content: options.isDev ? "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *" :
"default-src 'self';" +
"connect-src 'self';" +
"script-src 'self' 'unsafe-inline';" +
"img-src 'self' data:;" +
"style-src 'self' 'unsafe-inline';" +
// "font-src 'self' data:;" +
"object-src 'none';" +
"child-src 'none';" + // deprecated
"frame-src 'none';" +
"form-action 'self';" +
"upgrade-insecure-requests;" +
"block-all-mixed-content;" +
"base-uri " + config.baseHref || '/'
},
{
'http-equiv': 'X-XSS-Protection',
content: '1;mode=block'
},
{
'http-equiv': 'Strict-Transport-Security',
content: 'max-age=31536000; includeSubDomains; preload'
},
{
'http-equiv': 'X-Content-Type-Options',
content: 'nosniff'
},
{
name: 'viewport',
content: 'minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no'
},
{
name: 'description',
content: 'Chat'
},
{
name: 'google',
content: 'notranslate'
},
{
name: 'theme-color',
content: '#9cf1fa'
},
{
name: 'mobile-web-app-capable',
content: 'yes'
}
];
return new HtmlWebpackPlugin(config);
};
|
/**
* @param {any} props
*/
const FreeIcon = (props) => (
<svg {...props} width="125" height="135" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M67.871 135c-5.86 0-10.742-4.891-10.742-10.761V61.386 44.022c0-4.647-3.662-8.316-8.3-8.316-4.64 0-8.302 3.669-8.302 8.316v55.76c0 5.87-4.883 10.761-10.742 10.761-5.86 0-10.742-4.891-10.742-10.76v-39.62c0-4.647-3.662-8.315-8.3-8.315-4.64 0-8.302 3.668-8.302 8.315v59.674H0V60.163c0-5.87 4.883-10.76 10.742-10.76 5.86 0 10.742 4.89 10.742 10.76v39.62c0 4.646 3.662 8.315 8.301 8.315s8.3-3.669 8.3-8.315V44.022c0-5.87 4.884-10.761 10.743-10.761 5.86 0 10.742 4.891 10.742 10.76v80.218c0 4.647 3.662 8.315 8.301 8.315s8.3-3.668 8.3-8.315v-70.19c0-5.87 4.884-10.76 10.743-10.76 5.86 0 10.742 4.89 10.742 10.76v54.782c0 4.647 3.662 8.316 8.301 8.316s8.301-3.669 8.301-8.316v-98.07C114.258 4.89 119.141 0 125 0v2.446c-4.639 0-8.301 3.668-8.301 8.315v98.07c0 5.87-4.883 10.761-10.742 10.761-5.859 0-10.742-4.891-10.742-10.761V54.049c0-4.647-3.662-8.315-8.301-8.315s-8.3 3.668-8.3 8.315v70.19c0 6.114-4.883 10.761-10.743 10.761z" fill="#FC6553" />
</svg>
)
export default FreeIcon
|
import socketio from "socket.io-client";
const socket = socketio("http://192.168.0.36:3333", {
autoConnect: false
});
function connect(latitude, longitude, techs) {
socket.io.opts.query = {
latitude,
longitude,
techs
};
socket.connect();
socket.on("message", text => {
console.log(text);
});
}
function disconnect() {
if (socket.connected) {
socket.disconnect();
}
}
export { connect, disconnect };
|
import Color from '../Core/Color.js';
import defined from '../Core/defined.js';
import defineProperties from '../Core/defineProperties.js';
/**
* A feature of a {@link Cesium3DTileset}.
* <p>
* Provides access to a feature's properties stored in the tile's batch table, as well
* as the ability to show/hide a feature and change its highlight color via
* {@link Cesium3DTileFeature#show} and {@link Cesium3DTileFeature#color}, respectively.
* </p>
* <p>
* Modifications to a <code>Cesium3DTileFeature</code> object have the lifetime of the tile's
* content. If the tile's content is unloaded, e.g., due to it going out of view and needing
* to free space in the cache for visible tiles, listen to the {@link Cesium3DTileset#tileUnload} event to save any
* modifications. Also listen to the {@link Cesium3DTileset#tileVisible} event to reapply any modifications.
* </p>
* <p>
* Do not construct this directly. Access it through {@link Cesium3DTileContent#getFeature}
* or picking using {@link Scene#pick} and {@link Scene#pickPosition}.
* </p>
*
* @alias Cesium3DTileFeature
* @constructor
*
* @example
* // On mouse over, display all the properties for a feature in the console log.
* handler.setInputAction(function(movement) {
* var feature = scene.pick(movement.endPosition);
* if (feature instanceof Cesium.Cesium3DTileFeature) {
* var propertyNames = feature.getPropertyNames();
* var length = propertyNames.length;
* for (var i = 0; i < length; ++i) {
* var propertyName = propertyNames[i];
* console.log(propertyName + ': ' + feature.getProperty(propertyName));
* }
* }
* }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
*/
function Cesium3DTileFeature(content, batchId) {
this._content = content;
this._batchId = batchId;
this._color = undefined; // for calling getColor
}
defineProperties(Cesium3DTileFeature.prototype, {
/**
* Gets or sets if the feature will be shown. This is set for all features
* when a style's show is evaluated.
*
* @memberof Cesium3DTileFeature.prototype
*
* @type {Boolean}
*
* @default true
*/
show : {
get : function() {
return this._content.batchTable.getShow(this._batchId);
},
set : function(value) {
this._content.batchTable.setShow(this._batchId, value);
}
},
/**
* Gets or sets the highlight color multiplied with the feature's color. When
* this is white, the feature's color is not changed. This is set for all features
* when a style's color is evaluated.
*
* @memberof Cesium3DTileFeature.prototype
*
* @type {Color}
*
* @default {@link Color.WHITE}
*/
color : {
get : function() {
if (!defined(this._color)) {
this._color = new Color();
}
return this._content.batchTable.getColor(this._batchId, this._color);
},
set : function(value) {
this._content.batchTable.setColor(this._batchId, value);
}
},
/**
* Gets the content of the tile containing the feature.
*
* @memberof Cesium3DTileFeature.prototype
*
* @type {Cesium3DTileContent}
*
* @readonly
* @private
*/
content : {
get : function() {
return this._content;
}
},
/**
* Gets the tileset containing the feature.
*
* @memberof Cesium3DTileFeature.prototype
*
* @type {Cesium3DTileset}
*
* @readonly
*/
tileset : {
get : function() {
return this._content.tileset;
}
},
/**
* All objects returned by {@link Scene#pick} have a <code>primitive</code> property. This returns
* the tileset containing the feature.
*
* @memberof Cesium3DTileFeature.prototype
*
* @type {Cesium3DTileset}
*
* @readonly
*/
primitive : {
get : function() {
return this._content.tileset;
}
},
/**
* @private
*/
pickId : {
get : function() {
return this._content.batchTable.getPickColor(this._batchId);
}
}
});
/**
* Returns whether the feature contains this property. This includes properties from this feature's
* class and inherited classes when using a batch table hierarchy.
*
* @see {@link https://github.com/CesiumGS/3d-tiles/tree/master/extensions/3DTILES_batch_table_hierarchy}
*
* @param {String} name The case-sensitive name of the property.
* @returns {Boolean} Whether the feature contains this property.
*/
Cesium3DTileFeature.prototype.hasProperty = function(name) {
return this._content.batchTable.hasProperty(this._batchId, name);
};
/**
* Returns an array of property names for the feature. This includes properties from this feature's
* class and inherited classes when using a batch table hierarchy.
*
* @see {@link https://github.com/CesiumGS/3d-tiles/tree/master/extensions/3DTILES_batch_table_hierarchy}
*
* @param {String[]} results An array into which to store the results.
* @returns {String[]} The names of the feature's properties.
*/
Cesium3DTileFeature.prototype.getPropertyNames = function(results) {
return this._content.batchTable.getPropertyNames(this._batchId, results);
};
/**
* Returns a copy of the value of the feature's property with the given name. This includes properties from this feature's
* class and inherited classes when using a batch table hierarchy.
*
* @see {@link https://github.com/CesiumGS/3d-tiles/tree/master/extensions/3DTILES_batch_table_hierarchy}
*
* @param {String} name The case-sensitive name of the property.
* @returns {*} The value of the property or <code>undefined</code> if the property does not exist.
*
* @example
* // Display all the properties for a feature in the console log.
* var propertyNames = feature.getPropertyNames();
* var length = propertyNames.length;
* for (var i = 0; i < length; ++i) {
* var propertyName = propertyNames[i];
* console.log(propertyName + ': ' + feature.getProperty(propertyName));
* }
*/
Cesium3DTileFeature.prototype.getProperty = function(name) {
return this._content.batchTable.getProperty(this._batchId, name);
};
/**
* Sets the value of the feature's property with the given name.
* <p>
* If a property with the given name doesn't exist, it is created.
* </p>
*
* @param {String} name The case-sensitive name of the property.
* @param {*} value The value of the property that will be copied.
*
* @exception {DeveloperError} Inherited batch table hierarchy property is read only.
*
* @example
* var height = feature.getProperty('Height'); // e.g., the height of a building
*
* @example
* var name = 'clicked';
* if (feature.getProperty(name)) {
* console.log('already clicked');
* } else {
* feature.setProperty(name, true);
* console.log('first click');
* }
*/
Cesium3DTileFeature.prototype.setProperty = function(name, value) {
this._content.batchTable.setProperty(this._batchId, name, value);
// PERFORMANCE_IDEA: Probably overkill, but maybe only mark the tile dirty if the
// property is in one of the style's expressions or - if it can be done quickly -
// if the new property value changed the result of an expression.
this._content.featurePropertiesDirty = true;
};
/**
* Returns whether the feature's class name equals <code>className</code>. Unlike {@link Cesium3DTileFeature#isClass}
* this function only checks the feature's exact class and not inherited classes.
* <p>
* This function returns <code>false</code> if no batch table hierarchy is present.
* </p>
*
* @param {String} className The name to check against.
* @returns {Boolean} Whether the feature's class name equals <code>className</code>
*
* @private
*/
Cesium3DTileFeature.prototype.isExactClass = function(className) {
return this._content.batchTable.isExactClass(this._batchId, className);
};
/**
* Returns whether the feature's class or any inherited classes are named <code>className</code>.
* <p>
* This function returns <code>false</code> if no batch table hierarchy is present.
* </p>
*
* @param {String} className The name to check against.
* @returns {Boolean} Whether the feature's class or inherited classes are named <code>className</code>
*
* @private
*/
Cesium3DTileFeature.prototype.isClass = function(className) {
return this._content.batchTable.isClass(this._batchId, className);
};
/**
* Returns the feature's class name.
* <p>
* This function returns <code>undefined</code> if no batch table hierarchy is present.
* </p>
*
* @returns {String} The feature's class name.
*
* @private
*/
Cesium3DTileFeature.prototype.getExactClassName = function() {
return this._content.batchTable.getExactClassName(this._batchId);
};
export default Cesium3DTileFeature;
|
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
*
* Initializes the HTML-CSS OutputJax to use the STIX-Web fonts
* Copyright (c) 2013-2019 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function (HTMLCSS,MML,AJAX) {
var VERSION = "2.7.6";
var ALPHABETSBOLDITALIC = "STIXMathJax_Alphabets-bold-italic",
ALPHABETSBOLD = "STIXMathJax_Alphabets-bold",
ALPHABETSITALIC = "STIXMathJax_Alphabets-italic",
ALPHABETS = "STIXMathJax_Alphabets",
ARROWSBOLD = "STIXMathJax_Arrows-bold",
ARROWS = "STIXMathJax_Arrows",
DOUBLESTRUCKBOLDITALIC = "STIXMathJax_DoubleStruck-bold-italic",
DOUBLESTRUCKBOLD = "STIXMathJax_DoubleStruck-bold",
DOUBLESTRUCKITALIC = "STIXMathJax_DoubleStruck-italic",
DOUBLESTRUCK = "STIXMathJax_DoubleStruck",
FRAKTURBOLD = "STIXMathJax_Fraktur-bold",
FRAKTUR = "STIXMathJax_Fraktur",
LATINBOLDITALIC = "STIXMathJax_Latin-bold-italic",
LATINBOLD = "STIXMathJax_Latin-bold",
LATINITALIC = "STIXMathJax_Latin-italic",
LATIN = "STIXMathJax_Latin",
MAINBOLDITALIC = "STIXMathJax_Main-bold-italic",
MAINBOLD = "STIXMathJax_Main-bold",
MAINITALIC = "STIXMathJax_Main-italic",
MAIN = "STIXMathJax_Main",
MARKSBOLDITALIC = "STIXMathJax_Marks-bold-italic",
MARKSBOLD = "STIXMathJax_Marks-bold",
MARKSITALIC = "STIXMathJax_Marks-italic",
MARKS = "STIXMathJax_Marks",
MISCBOLDITALIC = "STIXMathJax_Misc-bold-italic",
MISCBOLD = "STIXMathJax_Misc-bold",
MISCITALIC = "STIXMathJax_Misc-italic",
MISC = "STIXMathJax_Misc",
MONOSPACE = "STIXMathJax_Monospace",
NORMALBOLDITALIC = "STIXMathJax_Normal-bold-italic",
NORMALBOLD = "STIXMathJax_Normal-bold",
NORMALITALIC = "STIXMathJax_Normal-italic",
OPERATORSBOLD = "STIXMathJax_Operators-bold",
OPERATORS = "STIXMathJax_Operators",
SANSSERIFBOLDITALIC = "STIXMathJax_SansSerif-bold-italic",
SANSSERIFBOLD = "STIXMathJax_SansSerif-bold",
SANSSERIFITALIC = "STIXMathJax_SansSerif-italic",
SANSSERIF = "STIXMathJax_SansSerif",
SCRIPTBOLDITALIC = "STIXMathJax_Script-bold-italic",
SCRIPTITALIC = "STIXMathJax_Script-italic",
SCRIPT = "STIXMathJax_Script",
SHAPESBOLDITALIC = "STIXMathJax_Shapes-bold-italic",
SHAPESBOLD = "STIXMathJax_Shapes-bold",
SHAPES = "STIXMathJax_Shapes",
SIZE1 = "STIXMathJax_Size1",
SIZE2 = "STIXMathJax_Size2",
SIZE3 = "STIXMathJax_Size3",
SIZE4 = "STIXMathJax_Size4",
SIZE5 = "STIXMathJax_Size5",
SYMBOLSBOLD = "STIXMathJax_Symbols-bold",
SYMBOLS = "STIXMathJax_Symbols",
VARIANTSBOLDITALIC = "STIXMathJax_Variants-bold-italic",
VARIANTSBOLD = "STIXMathJax_Variants-bold",
VARIANTSITALIC = "STIXMathJax_Variants-italic",
VARIANTS = "STIXMathJax_Variants";
var H = "H", V = "V", EXTRAH = {load:"extra", dir:H}, EXTRAV = {load:"extra", dir:V};
var ARROWREP = [0x2212,MAIN,0,0,0,-.26,-.26];
HTMLCSS.Augment({
FONTDATA: {
version: VERSION,
TeX_factor: 1.125,
baselineskip: 1.200,
lineH: 0.800, lineD: 0.200,
hasStyleChar: true, // char 0xEFFD encodes font style
FONTS: {
"STIXMathJax_Alphabets-bold-italic": "Alphabets/BoldItalic/Main.js",
"STIXMathJax_Alphabets-bold": "Alphabets/Bold/Main.js",
"STIXMathJax_Alphabets-italic": "Alphabets/Italic/Main.js",
"STIXMathJax_Alphabets": "Alphabets/Regular/Main.js",
"STIXMathJax_Arrows-bold": "Arrows/Bold/Main.js",
"STIXMathJax_Arrows": "Arrows/Regular/Main.js",
"STIXMathJax_DoubleStruck-bold-italic": "DoubleStruck/BoldItalic/Main.js",
"STIXMathJax_DoubleStruck-bold": "DoubleStruck/Bold/Main.js",
"STIXMathJax_DoubleStruck-italic": "DoubleStruck/Italic/Main.js",
"STIXMathJax_DoubleStruck": "DoubleStruck/Regular/Main.js",
"STIXMathJax_Fraktur-bold": "Fraktur/Bold/Main.js",
"STIXMathJax_Fraktur": "Fraktur/Regular/Main.js",
"STIXMathJax_Latin-bold-italic": "Latin/BoldItalic/Main.js",
"STIXMathJax_Latin-bold": "Latin/Bold/Main.js",
"STIXMathJax_Latin-italic": "Latin/Italic/Main.js",
"STIXMathJax_Latin": "Latin/Regular/Main.js",
"STIXMathJax_Main-bold-italic": "Main/BoldItalic/Main.js",
"STIXMathJax_Main-bold": "Main/Bold/Main.js",
"STIXMathJax_Main-italic": "Main/Italic/Main.js",
"STIXMathJax_Main": "Main/Regular/Main.js",
"STIXMathJax_Marks-bold-italic": "Marks/BoldItalic/Main.js",
"STIXMathJax_Marks-bold": "Marks/Bold/Main.js",
"STIXMathJax_Marks-italic": "Marks/Italic/Main.js",
"STIXMathJax_Marks": "Marks/Regular/Main.js",
"STIXMathJax_Misc-bold-italic": "Misc/BoldItalic/Main.js",
"STIXMathJax_Misc-bold": "Misc/Bold/Main.js",
"STIXMathJax_Misc-italic": "Misc/Italic/Main.js",
"STIXMathJax_Misc": "Misc/Regular/Main.js",
"STIXMathJax_Monospace": "Monospace/Regular/Main.js",
"STIXMathJax_Normal-bold-italic": "Normal/BoldItalic/Main.js",
"STIXMathJax_Normal-bold": "Normal/Bold/Main.js",
"STIXMathJax_Normal-italic": "Normal/Italic/Main.js",
"STIXMathJax_Operators-bold": "Operators/Bold/Main.js",
"STIXMathJax_Operators": "Operators/Regular/Main.js",
"STIXMathJax_SansSerif-bold-italic": "SansSerif/BoldItalic/Main.js",
"STIXMathJax_SansSerif-bold": "SansSerif/Bold/Main.js",
"STIXMathJax_SansSerif-italic": "SansSerif/Italic/Main.js",
"STIXMathJax_SansSerif": "SansSerif/Regular/Main.js",
"STIXMathJax_Script-bold-italic": "Script/BoldItalic/Main.js",
"STIXMathJax_Script-italic": "Script/Italic/Main.js",
"STIXMathJax_Script": "Script/Regular/Main.js",
"STIXMathJax_Shapes-bold-italic": "Shapes/BoldItalic/Main.js",
"STIXMathJax_Shapes-bold": "Shapes/Bold/Main.js",
"STIXMathJax_Shapes": "Shapes/Regular/Main.js",
"STIXMathJax_Size1": "Size1/Regular/Main.js",
"STIXMathJax_Size2": "Size2/Regular/Main.js",
"STIXMathJax_Size3": "Size3/Regular/Main.js",
"STIXMathJax_Size4": "Size4/Regular/Main.js",
"STIXMathJax_Size5": "Size5/Regular/Main.js",
"STIXMathJax_Symbols-bold": "Symbols/Bold/Main.js",
"STIXMathJax_Symbols": "Symbols/Regular/Main.js",
"STIXMathJax_Variants-bold-italic": "Variants/BoldItalic/Main.js",
"STIXMathJax_Variants-bold": "Variants/Bold/Main.js",
"STIXMathJax_Variants-italic": "Variants/Italic/Main.js",
"STIXMathJax_Variants": "Variants/Regular/Main.js"
},
VARIANT: {
"normal": {
fonts: [MAIN,MONOSPACE,LATIN,ALPHABETS,MARKS,ARROWS,OPERATORS,SYMBOLS,SHAPES,MISC,VARIANTS,SIZE1],
remap: {0x007C: [0x007C, "-STIX-Web-variant"]}
},
"bold": {
fonts: [MAINBOLD,NORMALBOLD,FRAKTURBOLD,DOUBLESTRUCKBOLD,SANSSERIFBOLD,LATINBOLD,ALPHABETSBOLD,MARKSBOLD,ARROWSBOLD,OPERATORSBOLD,SYMBOLSBOLD,SHAPESBOLD,MISCBOLD,VARIANTSBOLD,SIZE1],
offsetA: 0x1D400,
offsetG: 0x1D6A8,
bold: true,
remap: {0x2202: 0x1D6DB, 0x2207: 0x1D6C1}
},
"italic": {
fonts: [MAINITALIC,NORMALITALIC,SCRIPTITALIC,DOUBLESTRUCKITALIC,SANSSERIFITALIC,LATINITALIC,ALPHABETSITALIC,MARKSITALIC,MISCITALIC,VARIANTSITALIC,SIZE1],
offsetA: 0x1D434, offsetG: 0x1D6E2,
remap: {0x1D455: 0x210E, 0x2202: 0x1D715, 0x2207: 0x1D6FB},
italic: true
},
"bold-italic": {
fonts: [MAINBOLDITALIC,NORMALBOLDITALIC,SCRIPTBOLDITALIC,DOUBLESTRUCKBOLDITALIC,SANSSERIFBOLDITALIC,LATINBOLDITALIC,ALPHABETSBOLDITALIC,MARKSBOLDITALIC,SHAPESBOLDITALIC,MISCBOLDITALIC,VARIANTSBOLDITALIC,SIZE1],
offsetA: 0x1D434, offsetG: 0x1D71C,
remap: {0x1D455: 0x210E, 0x2202: 0x1D74F, 0x2207: 0x1D735},
bold: true, italic: true
},
"double-struck": {
fonts: [DOUBLESTRUCK],
offsetA: 0x1D538,
offsetN: 0x1D7D8,
remap: {0x1D53A: 0x2102, 0x1D53F: 0x210D, 0x1D545: 0x2115, 0x1D547: 0x2119, 0x1D548: 0x211A, 0x1D549: 0x211D, 0x1D551: 0x2124}
},
"fraktur": {
fonts: [FRAKTUR],
offsetA: 0x1D504,
remap: {0x1D506: 0x212D, 0x1D50B: 0x210C, 0x1D50C: 0x2111, 0x1D515: 0x211C, 0x1D51D: 0x2128}
},
"bold-fraktur": {
fonts: [FRAKTURBOLD],
offsetA: 0x1D56C,
bold: true
},
"script": {
fonts: [SCRIPTITALIC],
offsetA: 0x1D49C,
italic: true,
remap: {0x1D49D: 0x212C, 0x1D4A0: 0x2130, 0x1D4A1: 0x2131, 0x1D4A3: 0x210B, 0x1D4A4: 0x2110, 0x1D4A7: 0x2112, 0x1D4A8: 0x2133, 0x1D4AD: 0x211B, 0x1D4BA: 0x212F, 0x1D4BC: 0x210A, 0x1D4C4: 0x2134}
},
"bold-script": {
fonts: [SCRIPTBOLDITALIC],
offsetA: 0x1D4D0,
bold:true, italic: true
},
"sans-serif": {
fonts: [SANSSERIF],
offsetA: 0x1D5A0,
offsetN: 0x1D7E2,
offsetP: 0xE17D,
remap: {0x2202: 0xE17C}
},
"bold-sans-serif": {
fonts: [SANSSERIFBOLD],
offsetA: 0x1D5D4,
offsetN: 0x1D7EC,
offsetG: 0x1D756,
remap: {0x2202: 0x1D789, 0x2207: 0x1D76F}
},
"sans-serif-italic": {
fonts: [SANSSERIFITALIC], italic: true,
offsetA: 0x1D608,
offsetN: 0xE1B4,
offsetP: 0xE1BF,
remap: {0x2202: 0xE1BE},
bold: true
},
"sans-serif-bold-italic": {
fonts: [SANSSERIFBOLDITALIC],
offsetA: 0x1D63C,
offsetN: 0xE1F6,
offsetG: 0x1D790,
remap: {0x2202: 0x1D7C3, 0x2207: 0x1D7A9},
bold: true, italic: true
},
"monospace": {
fonts: [MONOSPACE],
offsetA: 0x1D670,
offsetN: 0x1D7F6
},
"-STIX-Web-variant": {remap: {0x2A87: 0xE010, 0x2A88: 0xE00F, 0x25B3: 0x25B5, 0x25BD: 0x25BF, 0x007C: [0x007C, MML.VARIANT.NORMAL]}, fonts: [VARIANTS,SHAPES,OPERATORS,MAIN,MONOSPACE,LATIN,ALPHABETS,MARKS,ARROWS,SYMBOLS,MISC,SIZE1]},
"-tex-caligraphic": {offsetA: 0xE22D, noLowerCase: 1, fonts: [VARIANTSITALIC,MAINITALIC,NORMALITALIC,SCRIPTITALIC,DOUBLESTRUCKITALIC,SANSSERIFITALIC,LATINITALIC,ALPHABETSITALIC,MARKSITALIC,MISCITALIC,SIZE1], italic: true},
"-tex-oldstyle": {offsetN: 0xE261, remap: {0xE262: 0xE265, 0xE263: 0xE269, 0xE264: 0xE26D, 0xE265: 0xE271, 0xE266: 0xE275, 0xE267: 0xE279, 0xE268: 0xE27D, 0xE269: 0xE281, 0xE26A: 0xE285}, fonts: [VARIANTS,MAIN,MONOSPACE,LATIN,ALPHABETS,MARKS,ARROWS,OPERATORS,SYMBOLS,SHAPES,MISC,SIZE1]},
"-tex-caligraphic-bold": {offsetA: 0xE247, noLowerCase: 1, fonts: [VARIANTSBOLDITALIC,MAINBOLDITALIC,NORMALBOLDITALIC,SCRIPTBOLDITALIC,DOUBLESTRUCKBOLDITALIC,SANSSERIFBOLDITALIC,LATINBOLDITALIC,ALPHABETSBOLDITALIC,MARKSBOLDITALIC,SHAPESBOLDITALIC,MISCBOLDITALIC,SIZE1], italic: true, bold: true},
"-tex-oldstyle-bold": {offsetN: 0xE261, remap: {0xE264: 0xE267, 0xE265: 0xE26B, 0xE266: 0xE26F, 0xE267: 0xE273, 0xE268: 0xE277, 0xE269: 0xE27B, 0xE26A: 0xE27F, 0xE26B: 0xE283, 0xE26C: 0xE287}, fonts: [VARIANTSBOLD,MAINBOLD,NORMALBOLD,FRAKTURBOLD,DOUBLESTRUCKBOLD,SANSSERIFBOLD,LATINBOLD,ALPHABETSBOLD,MARKSBOLD,ARROWSBOLD,OPERATORSBOLD,SYMBOLSBOLD,SHAPESBOLD,MISCBOLD,SIZE1], bold: true},
"-tex-mathit": {fonts: [MAINITALIC,NORMALITALIC,SCRIPTITALIC,DOUBLESTRUCKITALIC,SANSSERIFITALIC,LATINITALIC,ALPHABETSITALIC,MARKSITALIC,MISCITALIC,VARIANTSITALIC,SIZE1], italic:true, noIC:true},
"-largeOp": {fonts:[SIZE1,MAIN]},
"-smallOp": {}
},
RANGES: [
{name: "alpha", low: 0x61, high: 0x7A, offset: "A", add: 26},
{name: "Alpha", low: 0x41, high: 0x5A, offset: "A"},
{name: "number", low: 0x30, high: 0x39, offset: "N"},
{name: "greek", low: 0x03B1, high: 0x03C9, offset: "G", add: 26},
{name: "Greek", low: 0x0391, high: 0x03A9, offset: "G"},
{name: "vargreek", low: 0x03D1, high: 0x03F6, offset: "G", remapOnly: true,
remap: {0x03F5: 52, 0x03D1: 53, 0x03F0: 54, 0x03D5: 55, 0x03F1: 56, 0x03D6: 57, 0x03F4: 17}},
{name: "PUAgreek", low: 0x03B1, high: 0x03C9, offset: "P", add: 25},
{name: "PUAGreek", low: 0x0391, high: 0x03A9, offset: "P"},
{name: "varPUAgreek", low: 0x03D1, high: 0x03F6, offset: "P", remapOnly: true,
remap: {0x03F5: 50, 0x03D1: 51, 0x03D5: 52, 0x03F1: 53, 0x03D6: 54, 0x03F4: 17}}
],
RULECHAR: 0x23AF,
REMAP: {
0xA: 0x20,
0x3008: 0x27E8,
0x3009: 0x27E9,
0x2758: 0x2223,
0x02F3: 0x02DA,
0x02F4: 0x02CA,
0xFE37: 0x23DE,
0xFE38: 0x23DF
},
REMAPACCENT: {
"\u007E": "\u0303",
"\u2192": "\u20D7",
"\u2190": "\u20D6",
"\u0060": "\u0300",
"\u005E": "\u0302",
"\u00B4": "\u0301",
"\u2032": "\u0301",
"\u2035": "\u0300"
},
REMAPACCENTUNDER: {
},
DELIMITERS: {
0x28:
{
dir: V,
HW: [[0.853,MAIN], [1.230,SIZE1], [1.350,SIZE1,1.098], [1.845,SIZE2], [2.460,SIZE3], [3.075,SIZE4]],
stretch: {bot:[0xE000,SIZE5], ext:[0xE001,SIZE5], top:[0xE002,SIZE5]}
},
0x29:
{
dir: V,
HW: [[0.853,MAIN], [1.230,SIZE1], [1.350,SIZE1,1.098], [1.845,SIZE2], [2.460,SIZE3], [3.075,SIZE4]],
stretch: {bot:[0xE003,SIZE5], ext:[0xE004,SIZE5], top:[0xE005,SIZE5]}
},
0x2D: {alias: 0x23AF, dir: H},
0x2F:
{
dir: V,
HW: [[0.690,MAIN], [1.230,SIZE1], [1.350,SIZE1,1.098], [1.845,SIZE2], [2.460,SIZE3], [3.075,SIZE4]]
},
0x3D: EXTRAH,
0x5B:
{
dir: V,
HW: [[0.818,MAIN], [1.230,SIZE1], [1.350,SIZE1,1.098], [1.845,SIZE2], [2.460,SIZE3], [3.075,SIZE4]],
stretch: {bot:[0xE006,SIZE5], ext:[0xE007,SIZE5], top:[0xE008,SIZE5]}
},
0x5C:
{
dir: V,
HW: [[0.690,MAIN], [1.230,SIZE1], [1.350,SIZE1,1.098], [1.845,SIZE2], [2.460,SIZE3], [3.075,SIZE4]]
},
0x5D:
{
dir: V,
HW: [[0.818,MAIN], [1.230,SIZE1], [1.350,SIZE1,1.098], [1.845,SIZE2], [2.460,SIZE3], [3.075,SIZE4]],
stretch: {bot:[0xE009,SIZE5], ext:[0xE00A,SIZE5], top:[0xE00B,SIZE5]}
},
0x5E: {alias: 0x2C6, dir: H},
0x5F: {alias: 0x23AF, dir: H},
0x7B:
{
dir: V,
HW: [[0.861,MAIN], [1.230,SIZE1], [1.350,SIZE1,1.098], [1.845,SIZE2], [2.460,SIZE3], [3.075,SIZE4]],
stretch: {bot:[0xE00C,SIZE5], ext:[0xE00D,SIZE5], mid:[0xE00E,SIZE5], top:[0xE00F,SIZE5]}
},
0x7C:
{
dir: V,
HW: [[0.690,MAIN]],
stretch: {bot:[0x7C,MAIN], ext:[0x7C,MAIN]}
},
0x7D:
{
dir: V,
HW: [[0.861,MAIN], [1.230,SIZE1], [1.350,SIZE1,1.098], [1.845,SIZE2], [2.460,SIZE3], [3.075,SIZE4]],
stretch: {bot:[0xE010,SIZE5], ext:[0xE00D,SIZE5], mid:[0xE011,SIZE5], top:[0xE012,SIZE5]}
},
0x7E: {alias: 0x2DC, dir: H},
0xAF: {alias: 0x23AF, dir: H},
0x2C6:
{
dir: H,
HW: [[0.311,MAIN], [0.560,SIZE1], [0.979,SIZE2], [1.460,SIZE3], [1.886,SIZE4], [2.328,SIZE5]]
},
0x2C7: EXTRAH,
0x2C9: {alias: 0x23AF, dir: H},
0x2CD: EXTRAH,
0x2DC:
{
dir: H,
HW: [[0.330,MAIN], [0.560,SIZE1], [0.979,SIZE2], [1.460,SIZE3], [1.886,SIZE4], [2.328,SIZE5]]
},
0x2F7: EXTRAH,
0x302:
{
dir: H,
HW: [[0.311,MAIN], [0.560,SIZE1], [0.979,SIZE2], [1.460,SIZE3], [1.886,SIZE4], [2.328,SIZE5]]
},
0x303:
{
dir: H,
HW: [[0.330,MAIN], [0.560,SIZE1], [0.979,SIZE2], [1.460,SIZE3], [1.886,SIZE4], [2.328,SIZE5]]
},
0x305:
{
dir: H,
HW: [[0.500,MARKS], [1.000,SIZE1], [1.500,SIZE2], [2.000,SIZE3], [2.500,SIZE4], [3.000,SIZE5]],
stretch: {left:[0xE013,SIZE5], rep:[0xE013,SIZE5]}
},
0x30C:
{
dir: H,
HW: [[0.311,MAIN], [0.560,SIZE1], [0.979,SIZE2], [1.460,SIZE3], [1.886,SIZE4], [2.328,SIZE5]]
},
0x330:
{
dir: H,
HW: [[0.330,MARKS], [0.560,SIZE1], [0.979,SIZE2], [1.460,SIZE3], [1.886,SIZE4], [2.328,SIZE5]]
},
0x332:
{
dir: H,
HW: [[0.500,MARKS], [1.000,SIZE1], [1.500,SIZE2], [2.000,SIZE3], [2.500,SIZE4], [3.000,SIZE5]],
stretch: {left:[0xE014,SIZE5], rep:[0xE014,SIZE5]}
},
0x338:
{
dir: V,
HW: [[0.818,MAIN], [0.553,SIZE1], [0.662,SIZE2], [0.818,SIZE3], [0.959,SIZE4], [1.414,SIZE5]]
},
0x2015: {alias: 0x23AF, dir: H},
0x2016:
{
dir: V,
HW: [[0.879,MAIN]],
stretch: {bot:[0x2016,MAIN], ext:[0x2016,MAIN]}
},
0x2017: {alias: 0x23AF, dir: H},
0x203E:
{
dir: H,
HW: [[0.500,MAIN], [1.000,SIZE1], [1.500,SIZE2], [2.000,SIZE3], [2.500,SIZE4], [3.000,SIZE5]],
stretch: {left:[0x203E,MAIN], rep:[0x203E,MAIN]}
},
0x20D0: EXTRAH,
0x20D1: EXTRAH,
0x20D6: EXTRAH,
0x20D7:
{
dir: H,
HW: [[0.436,MAIN], [0.872,SIZE1], [1.308,SIZE2], [1.744,SIZE3], [2.180,SIZE4], [3.000,SIZE5]],
stretch: {rep:[0xE016,SIZE5], right:[0xE019,SIZE5]}
},
0x20E1: EXTRAH,
0x20EC: EXTRAH,
0x20ED: EXTRAH,
0x20EE: EXTRAH,
0x20EF: EXTRAH,
0x2140: EXTRAV,
0x2190:
{
dir: H,
HW: [[0.786,MAIN]],
stretch: {left:[0x2190,MAIN], rep:ARROWREP}
},
0x2191:
{
dir: V,
HW: [[0.818,MAIN]],
stretch: {ext:[0x23D0,MAIN], top:[0x2191,MAIN]}
},
0x2192:
{
dir: H,
HW: [[0.786,MAIN]],
stretch: {rep:ARROWREP, right:[0x2192,MAIN]}
},
0x2193:
{
dir: V,
HW: [[0.818,MAIN]],
stretch: {bot:[0x2193,MAIN], ext:[0x23D0,MAIN]}
},
0x2194:
{
dir: H,
HW: [[0.850,MAIN]],
stretch: {left:[0x2190,MAIN], rep:ARROWREP, right:[0x2192,MAIN]}
},
0x2195:
{
dir: V,
HW: [[0.954,MAIN]],
stretch: {bot:[0x2193,MAIN], ext:[0x23D0,MAIN], top:[0x2191,MAIN]}
},
0x219E: EXTRAH,
0x219F: EXTRAV,
0x21A0: EXTRAH,
0x21A1: EXTRAV,
0x21A4: EXTRAH,
0x21A5: EXTRAV,
0x21A6: EXTRAH,
0x21A7: EXTRAV,
0x21A8: EXTRAV,
0x21A9: EXTRAH,
0x21AA: EXTRAH,
0x21B0: EXTRAV,
0x21B1: EXTRAV,
0x21B2: EXTRAV,
0x21B3: EXTRAV,
0x21B4: EXTRAH,
0x21B5: EXTRAV,
0x21BC: EXTRAH,
0x21BD: EXTRAH,
0x21BE: EXTRAV,
0x21BF: EXTRAV,
0x21C0: EXTRAH,
0x21C1: EXTRAH,
0x21C2: EXTRAV,
0x21C3: EXTRAV,
0x21CB: EXTRAH,
0x21CC: EXTRAH,
0x21D0:
{
dir: H,
HW: [[0.806,MAIN]],
stretch: {left:[0x21D0,MAIN], rep:[0xE01F,SIZE5]}
},
0x21D1:
{
dir: V,
HW: [[0.818,MAIN]],
stretch: {ext:[0xE020,SIZE5], top:[0x21D1,MAIN]}
},
0x21D2:
{
dir: H,
HW: [[0.806,MAIN]],
stretch: {rep:[0xE01F,SIZE5], right:[0x21D2,MAIN]}
},
0x21D3:
{
dir: V,
HW: [[0.818,MAIN]],
stretch: {bot:[0x21D3,MAIN], ext:[0xE020,SIZE5]}
},
0x21D4:
{
dir: H,
HW: [[0.886,MAIN]],
stretch: {left:[0x21D0,MAIN], rep:[0xE01F,SIZE5], right:[0x21D2,MAIN]}
},
0x21D5:
{
dir: V,
HW: [[0.954,MAIN]],
stretch: {bot:[0x21D3,MAIN], ext:[0xE020,SIZE5], top:[0x21D1,MAIN]}
},
0x21DA: EXTRAH,
0x21DB: EXTRAH,
0x21E0: EXTRAH,
0x21E1: EXTRAV,
0x21E2: EXTRAH,
0x21E3: EXTRAV,
0x21E4: EXTRAH,
0x21E5: EXTRAH,
0x21FD: EXTRAH,
0x21FE: EXTRAH,
0x21FF: EXTRAH,
0x220F: EXTRAV,
0x2210: EXTRAV,
0x2211: EXTRAV,
0x2212: {alias: 0x23AF, dir: H},
0x2215: {alias: 0x2F, dir: V},
0x221A:
{
dir: V,
HW: [[1.232,MAIN], [1.847,SIZE1], [2.460,SIZE2], [3.075,SIZE3]],
stretch: {bot:[0xE022,SIZE5], ext:[0xE023,SIZE5], top:[0xE024,SIZE5]}
},
0x221B: EXTRAV,
0x221C: EXTRAV,
0x2223:
{
dir: V,
HW: [[0.879,MAIN]],
stretch: {ext:[0x2223,MAIN]}
},
0x2225:
{
dir: V,
HW: [[0.879,MAIN]],
stretch: {ext:[0x2225,MAIN]}
},
0x222B: EXTRAV,
0x222C: EXTRAV,
0x222D: EXTRAV,
0x222E: EXTRAV,
0x222F: EXTRAV,
0x2230: EXTRAV,
0x2231: EXTRAV,
0x2232: EXTRAV,
0x2233: EXTRAV,
0x22C0: EXTRAV,
0x22C1: EXTRAV,
0x22C2: EXTRAV,
0x22C3: EXTRAV,
0x2308:
{
dir: V,
HW: [[0.926,MAIN], [1.230,SIZE1], [1.350,SIZE1,1.098], [1.845,SIZE2], [2.460,SIZE3], [3.075,SIZE4]],
stretch: {ext:[0xE007,SIZE5], top:[0xE008,SIZE5]}
},
0x2309:
{
dir: V,
HW: [[0.926,MAIN], [1.230,SIZE1], [1.350,SIZE1,1.098], [1.845,SIZE2], [2.460,SIZE3], [3.075,SIZE4]],
stretch: {ext:[0xE00A,SIZE5], top:[0xE00B,SIZE5]}
},
0x230A:
{
dir: V,
HW: [[0.926,MAIN], [1.230,SIZE1], [1.350,SIZE1,1.098], [1.845,SIZE2], [2.460,SIZE3], [3.075,SIZE4]],
stretch: {bot:[0xE006,SIZE5], ext:[0xE007,SIZE5]}
},
0x230B:
{
dir: V,
HW: [[0.926,MAIN], [1.230,SIZE1], [1.350,SIZE1,1.098], [1.845,SIZE2], [2.460,SIZE3], [3.075,SIZE4]],
stretch: {bot:[0xE009,SIZE5], ext:[0xE00A,SIZE5]}
},
0x2312: {alias: 0x23DC, dir:H},
0x2322: {alias: 0x23DC, dir:H},
0x2323: {alias: 0x23DD, dir:H},
0x2329: {alias: 0x27E8, dir: V},
0x232A: {alias: 0x27E9, dir: V},
0x23AA: EXTRAV,
0x23AF:
{
dir: H,
HW: [[0.315,SYMBOLS]],
stretch: {rep:[0x23AF,SYMBOLS]}
},
0x23B0:
{
dir: V,
HW: [[1.001,SIZE5,null,0xE03A]],
stretch: {top:[0xE00F,SIZE5], ext:[0xE00D,SIZE5], bot:[0xE010,SIZE5]}
},
0x23B1:
{
dir: V,
HW: [[1.001,SIZE5,null,0xE03B]],
stretch: {top:[0xE012,SIZE5], ext:[0xE00D,SIZE5], bot:[0xE00C,SIZE5]}
},
0x23B4: EXTRAH,
0x23B5: EXTRAH,
0x23D0: EXTRAV,
0x23DC: EXTRAH,
0x23DD: EXTRAH,
0x23DE:
{
dir: H,
HW: [[1.000,MAIN], [0.925,SIZE1], [1.460,SIZE2], [1.886,SIZE3], [2.328,SIZE4], [3.238,SIZE5]],
stretch: {left:[0xE031,SIZE5], rep:[0xE028,SIZE5], mid:[0xE032,SIZE5], right:[0xE033,SIZE5]}
},
0x23DF:
{
dir: H,
HW: [[1.000,MAIN], [0.925,SIZE1], [1.460,SIZE2], [1.886,SIZE3], [2.328,SIZE4], [3.238,SIZE5]],
stretch: {left:[0xE034,SIZE5], rep:[0xE02B,SIZE5], mid:[0xE035,SIZE5], right:[0xE036,SIZE5]}
},
0x23E0: EXTRAH,
0x23E1: EXTRAH,
0x2500: {alias: 0x2212, dir: H},
0x2758: {alias: 0x2223, dir: V},
0x2772: EXTRAV,
0x2773: EXTRAV,
0x27E6: EXTRAV,
0x27E7: EXTRAV,
0x27E8:
{
dir: V,
HW: [[0.926,MAIN], [1.230,SIZE1], [1.350,SIZE1,1.098], [1.845,SIZE2], [2.460,SIZE3], [3.075,SIZE4]]
},
0x27E9:
{
dir: V,
HW: [[0.926,MAIN], [1.230,SIZE1], [1.350,SIZE1,1.098], [1.845,SIZE2], [2.460,SIZE3], [3.075,SIZE4]]
},
0x27EA: EXTRAV,
0x27EB: EXTRAV,
0x27EE:
{
dir: V,
HW: [[0.853,MAIN]],
stretch: {bot:[0xE000,SIZE5], ext:[0xE001,SIZE5], top:[0xE002,SIZE5]}
},
0x27EF:
{
dir: V,
HW: [[0.853,MAIN]],
stretch: {bot:[0xE003,SIZE5], ext:[0xE004,SIZE5], top:[0xE005,SIZE5]}
},
0x27F0: EXTRAV,
0x27F1: EXTRAV,
0x27F5: {alias: 0x2190, dir: H},
0x27F6: {alias: 0x2192, dir: H},
0x27F7: {alias: 0x2194, dir: H},
0x27F8: {alias: 0x21D0, dir: H},
0x27F9: {alias: 0x21D2, dir: H},
0x27FA: {alias: 0x21D4, dir: H},
0x27FB: {alias: 0x21A4, dir: H},
0x27FC: {alias: 0x21A6, dir: H},
0x27FD: {alias: 0x2906, dir: H},
0x27FE: {alias: 0x2907, dir: H},
0x2906: EXTRAH,
0x2907: EXTRAH,
0x290A: EXTRAV,
0x290B: EXTRAV,
0x2912: EXTRAV,
0x2913: EXTRAV,
0x294E: EXTRAH,
0x294F: EXTRAV,
0x2950: EXTRAH,
0x2951: EXTRAV,
0x2952: EXTRAH,
0x2953: EXTRAH,
0x2954: EXTRAV,
0x2955: EXTRAV,
0x2956: EXTRAH,
0x2957: EXTRAH,
0x2958: EXTRAV,
0x2959: EXTRAV,
0x295A: EXTRAH,
0x295B: EXTRAH,
0x295C: EXTRAV,
0x295D: EXTRAV,
0x295E: EXTRAH,
0x295F: EXTRAH,
0x2960: EXTRAV,
0x2961: EXTRAV,
0x2980: EXTRAV,
0x2983: EXTRAV,
0x2984: EXTRAV,
0x2985: EXTRAV,
0x2986: EXTRAV,
0x2997: EXTRAV,
0x2998: EXTRAV,
0x29F8:
{
dir: V,
HW: [[1.020,MAIN], [1.845,SIZE1]]
},
0x29F9:
{
dir: V,
HW: [[1.020,MAIN], [1.845,SIZE1]]
},
0x2A00: EXTRAV,
0x2A01: EXTRAV,
0x2A02: EXTRAV,
0x2A03: EXTRAV,
0x2A04: EXTRAV,
0x2A05: EXTRAV,
0x2A06: EXTRAV,
0x2A07: EXTRAV,
0x2A08: EXTRAV,
0x2A09: EXTRAV,
0x2A0A: EXTRAV,
0x2A0B: EXTRAV,
0x2A0C: EXTRAV,
0x2A0D: EXTRAV,
0x2A0E: EXTRAV,
0x2A0F: EXTRAV,
0x2A10: EXTRAV,
0x2A11: EXTRAV,
0x2A12: EXTRAV,
0x2A13: EXTRAV,
0x2A14: EXTRAV,
0x2A15: EXTRAV,
0x2A16: EXTRAV,
0x2A17: EXTRAV,
0x2A18: EXTRAV,
0x2A19: EXTRAV,
0x2A1A: EXTRAV,
0x2A1B: EXTRAV,
0x2A1C: EXTRAV,
0x2AFC: EXTRAV,
0x2AFF: EXTRAV,
0x2B45: EXTRAH,
0x2B46:
{
dir: H,
HW: [[0.818,SHAPES]],
stretch: {rep:[0xE039,SIZE5], right:[0x2B46,SHAPES]}
},
0x3008: {alias: 0x27E8, dir: V},
0x3009: {alias: 0x27E9, dir: V},
0xFE37: {alias: 0x23DE, dir: H},
0xFE38: {alias: 0x23DF, dir: H}
}
}
});
MathJax.Hub.Register.LoadHook(HTMLCSS.fontDir+"/Main/Regular/Main.js",function () {
HTMLCSS.FONTDATA.FONTS[MAIN][0x22EE][0] += 400; // adjust height for \vdots
HTMLCSS.FONTDATA.FONTS[MAIN][0x22F1][0] += 500; // adjust height for \ddots
HTMLCSS.FONTDATA.FONTS[MAIN][0x2212][0] = HTMLCSS.FONTDATA.FONTS[MAIN][0x002B][0]; // - needs height and depth of +
HTMLCSS.FONTDATA.FONTS[MAIN][0x2212][1] = HTMLCSS.FONTDATA.FONTS[MAIN][0x002B][1]; // - needs height and depth of +
HTMLCSS.FONTDATA.FONTS[MAIN][0x003D][1] += 100; // adjust depth for = (double arrow extender)
});
MathJax.Hub.Register.LoadHook(HTMLCSS.fontDir+"/Size5/Regular/Main.js",function () {
var u;
u = HTMLCSS.FONTDATA.DELIMITERS[0x23DE].stretch.rep[0];
HTMLCSS.FONTDATA.FONTS[SIZE5][u][0] += 200; // adjust height for brace extender
HTMLCSS.FONTDATA.FONTS[SIZE5][u][1] += 200; // adjust depth for brace extender
u = HTMLCSS.FONTDATA.DELIMITERS[0x23DF].stretch.rep[0];
HTMLCSS.FONTDATA.FONTS[SIZE5][u][0] += 200; // adjust height for brace extender
HTMLCSS.FONTDATA.FONTS[SIZE5][u][1] += 200; // adjust depth for brace extender
});
AJAX.loadComplete(HTMLCSS.fontDir + "/fontdata.js");
})(MathJax.OutputJax["HTML-CSS"],MathJax.ElementJax.mml,MathJax.Ajax);
|
'use strict';
// MODULES //
var isArrayLike = require( 'validate.io-array-like' ),
ctors = require( 'compute-array-constructors' );
// APPLY //
/**
* FUNCTION: apply( fcn, ...array[, opts] )
* Applies a function to each array element.
*
* @param {Function} fcn - function to apply
* @param {Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} array - input arrays
* @param {Object} [opts] - function options
* @param {String} [opts.dtype="generic"] - output data type
* @param {Boolean} [opts.out=false] - boolean indicating whether an output array has been provided
* @returns {Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} output array
*/
function apply() {
/* jshint newcap:false */
var nargs = arguments.length,
args = new Array( nargs ),
opts,
ctor,
fcn,
out,
arr,
len,
dt,
idx, end, // start/end indices
i, j, k;
for ( i = 0; i < nargs; i++ ) {
args[ i ] = arguments[ i ];
}
nargs -= 1;
if ( !isArrayLike( args[ nargs ] ) ) {
opts = args[ nargs ];
nargs -= 1;
} else {
opts = {};
}
end = nargs;
fcn = args[ 0 ];
len = args[ 1 ].length;
if ( opts.out ) {
out = args[ 1 ];
idx = 2;
nargs -= 1;
} else {
dt = opts.dtype || 'generic';
ctor = ctors( dt );
if ( ctor === null ) {
throw new Error( 'invalid option. Data type option does not have a corresponding array constructor. Option: `' + dt + '`.' );
}
out = new ctor( len );
idx = 1;
}
arr = new Array( nargs );
for ( i = 0; i < len; i++ ) {
for ( k = 0, j = idx; j <= end; k++, j++ ) {
arr[ k ] = args[ j ][ i ];
}
out[ i ] = fcn.apply( null, arr );
}
return out;
} // end FUNCTION apply()
// EXPORTS //
module.exports = apply;
|
import {
SET_FINGERPRINT,
SET_USER,
SET_AUTHENTICATED,
SET_UNAUTHENTICATED,
LOADING_USER,
LIKE_SNIPPET,
PLAY_SNIPPET,
UNLIKE_SNIPPET,
MARK_NOTIFICATIONS_READ
} from "../types";
const initialState = {
fingerprint: null,
authenticated: false,
loading: false,
credentials: {},
likes: [],
plays: [],
notifications: [],
};
export default function (state = initialState, action) {
switch (action.type) {
case SET_AUTHENTICATED:
return {
...state,
authenticated: true,
};
case SET_UNAUTHENTICATED:
return initialState;
case SET_USER:
return {
authenticated: true,
loading: false,
...action.payload,
};
case LOADING_USER:
return {
...state,
loading: true
};
case LIKE_SNIPPET:
return {
...state,
likes: [
...state.likes,
{
userHandle: state.credentials.handle,
snippetId: action.payload.snippetId
}
]
};
case PLAY_SNIPPET:
return {
...state,
plays: [
...state.plays,
{
userHandle: state.credentials.handle,
snippetId: action.payload.snippetId
}
]
};
case UNLIKE_SNIPPET:
return {
...state,
likes: state.likes.filter(like => like.snippetId !== action.payload.snippetId)
};
case MARK_NOTIFICATIONS_READ:
state.notifications.forEach(notification => notification.read = true);
return {
...state
};
case SET_FINGERPRINT:
return {
...state,
fingerprint: action.payload,
}
default:
return state;
}
}
|
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
module.exports = mongoose.model(
"OAuthAuthorizationCode",
new Schema({
authorizationCode: String,
expiresAt: Date,
scope: String,
redirectUri: String,
user: { type: Schema.Types.ObjectId, ref: "User" },
client: { type: Schema.Types.ObjectId, ref: "OAuthClient" }
})
);
|
const array = [10, 4, 40, 32 , 67, 12, 43, 31, 65, 1]
function bubbleSort(array){
// Recorrer el arreglo basado en su tamaño total
for (let i = 0; i < array.length; i++) {
for(let j = 0; j < array.length; j++) {
//Comprobar el valor actual con el valor siguiente
if(array[j] > array[j+1]){
let currentNumber = array[j] // variable auxiliar para almacenar el estado y evitar que se pierda
//Ahora la posicion actual obtiene el valor de la siguiente posición
array[j] = array[j+1]
//Ahora la siguiente posición obtiene el valor de la posición actual
array[j+1] = currentNumber;
}
}
}
return array;
}
const result = bubbleSort(array)
console.log(result)
|
'use strict';
var loadTemplate = require('../utils/loadTemplate'),
baseModal = require('./baseModal');
module.exports = baseModal.extend({
className: 'guid-still-creating-modal',
events: {
},
render: function() {
var self = this;
loadTemplate('./js/templates/guidStillCreatingModal.html', function(t) {
self.$el.html(t());
baseModal.prototype.render.apply(self, arguments);
});
return this;
}
});
|
//How do you find the duplicate number on a given integer array?
//[1,2,7,4,6,3,6,3,7,8,9]
function findDuplicate(inputList) {
for (let i = 0; i < inputList.length; i++) {
for (let j = 0; j < inputList.length - 1; j++) {
if (inputList[j] > inputList[j + 1]) {
let c = inputList[j];
inputList[j] = inputList[j + 1];
inputList[j + 1] = c;
}
}
}
//return inputList;
console.log(inputList);
let duplicate = 1;
for (let i = 0; i < inputList.length; i++) {
if (inputList[i] === inputList[i + 1]) {
duplicate++;
}
if (inputList[i] !== inputList[i + 1] && duplicate !== 1) {
console.log(inputList[i] + " apare de " + duplicate);
duplicate = 1;
}
}
}
const inputList = [1, 2, 3, 4, 2, 3, 4, 5, 1, 7, 3, 6, 9, 9, 9, 9];
findDuplicate(inputList);
|
const User = require('./User');
const Meal = require('./Meal');
const SelectMeal = require('./SelectMeal');
const Diet = require('./Diet');
const MealDiet = require('./MealDiet');
const UserProfile = require('./UserProfile');
//USER AND USER PROFILE ASSOCIATIONS
UserProfile.belongsTo(User, {
foreignKey: 'user_id'
});
User.hasOne(UserProfile, {
foreignKey: 'user_id'
});
//MEALSELECTION AND MEAL ASSOCIATIONS
// Meal belongsToMany Users (through SelectMeal)
Meal.belongsToMany(User, {
through: SelectMeal,
foreignKey: 'meal_id'
});
// User belongsToMany Meals (through SelectMeal)
User.belongsToMany(Meal, {
through: SelectMeal,
foreignKey: 'user_id'
});
Meal.hasMany(SelectMeal, {
foreignKey: 'meal_id'
});
User.hasMany(SelectMeal, {
foreignKey: 'user_id'
});
// MEAL AND DIET ASSOCIATIONS
// Meal belongToMany Diets (through MealDiet)
Meal.belongsToMany(Diet, {
through: MealDiet,
foreignKey: 'meal_id'
});
// Diet belongsToMany Meals (through MealDiet)
Diet.belongsToMany(Meal, {
through: MealDiet,
foreignKey: 'diet_id'
});
// ProductTag.belongsTo(Product, {
// foreignKey: 'product_id'
// });
// ProductTag.belongsTo(Tag, {
// foreignKey: 'tag_id'
// });
Meal.hasMany(MealDiet, {
foreignKey: 'meal_id'
});
Diet.hasMany(MealDiet, {
foreignKey: 'diet_id'
});
module.exports = { User, Meal, SelectMeal, Diet, MealDiet, UserProfile };
|
'use strict';
var expect = require('chai').expect;
var sinon = require('sinon');
var createAnnounceParams = require('./helpers/create-announce-params');
describe('TrackerService', function () {
var TrackerService = require('../release/tracker-service').default,
MemoryTorrentStore = require('../release/memory-torrent-store').default,
Torrent = require('../release/torrent').default,
AnnounceParamsValidator = require('../release/announce-params-validator').default,
Address = require('../release/address').default,
bufferpack = require('bufferpack'),
trackerService,
torrentStub,
memoryTorrentStoreStub,
params,
output,
ip1 = [244, 200, 100, 44],
ip2 = [192, 168, 0, 12],
ip3 = [11, 22, 33, 66],
port1 = 51413,
port2 = 50000,
port3 = 1,
peer1 = {peerId: 'peer1', ip: new Address(ip1.join('.')), port: port1},
peer2 = {peerId: 'peer2', ip: new Address(ip2.join('.')), port: port2},
peer3 = {peerId: 'peer3', ip: new Address(ip3.join('.')), port: port3},
peers = [peer1, peer2, peer3];
beforeEach(function () {
torrentStub = sinon.createStubInstance(Torrent);
torrentStub.getPeers = function () {
return peers;
};
torrentStub.getComplete = function () {
return 'complete';
};
torrentStub.getIncomplete = function () {
return 'incomplete';
};
memoryTorrentStoreStub = sinon.createStubInstance(MemoryTorrentStore);
memoryTorrentStoreStub.getTorrent = function () {
return torrentStub;
};
params = createAnnounceParams();
trackerService = new TrackerService();
trackerService.torrentStore = memoryTorrentStoreStub;
});
describe('#announce', function () {
function returnsObject() {
it('returns object', function () {
expect(output).to.be.an('object');
});
}
function returnsResponse(isCompact, noPeers) {
returnsObject();
describe('[peers]', function () {
if (isCompact) {
if (noPeers) {
it("return an empty buffer", function() {
expect(output.peers).to.be.an.instanceof(Buffer);
expect(output.peers.length).to.equal(0);
});
} else {
it('returns a buffer containing byte representations of IP address and port for each peer', function () {
var addr1num = Buffer.from(ip1).readInt32BE(0),
addr2num = Buffer.from(ip2).readInt32BE(0),
addr3num = Buffer.from(ip3).readInt32BE(0),
expected = bufferpack.pack('lHlHlH', [addr1num, port1, addr2num, port2, addr3num, port3]);
expect(output.peers).to.eql(expected);
});
}
} else {
if (noPeers) {
it('return an empty array', function () {
expect(output.peers).to.eql([]);
});
} else {
it('returns an array with peer data', function () {
expect(output.peers).to.eql([
{
'peer id': 'peer1',
ip: '244.200.100.44',
port: port1
},
{
'peer id': 'peer2',
ip: '192.168.0.12',
port: port2
},
{
'peer id': 'peer3',
ip: '11.22.33.66',
port: port3
}
]);
});
}
}
});
describe('[complete]', function () {
it('contains a list of seeders', function () {
expect(output.complete).to.equal('complete');
});
});
describe('[incomplete]', function () {
it('contains a list of leechers', function () {
expect(output.incomplete).to.equal('incomplete');
});
});
describe('[interval]', function () {
it('contains an interval in seconds that the client should wait between sending regular requests to the tracker', function () {
expect(output.interval).to.equal(300);
});
});
}
function returnsError(message) {
returnsObject();
describe('[failure reason]', function () {
it('contains an error message', function () {
expect(output['failure reason']).to.equal(message);
});
});
}
function behavesLikeEventNotSpecified() {
it('sets peer\'s data only once', function () {
expect(torrentStub.setPeer.callCount).to.equal(1);
});
['peerId', 'ip', 'port', 'left'].forEach(function (testParam) {
it('updates the peer\'s ' + testParam, function () {
var expObj = {};
expObj[testParam] = params[testParam];
expect(torrentStub.setPeer.getCall(0).args[0]).to.include(expObj);
});
});
it('saves updated torrent', function () {
expect(memoryTorrentStoreStub.saveTorrent.callCount).to.equal(1);
expect(memoryTorrentStoreStub.saveTorrent.calledAfter(torrentStub.setPeer)).to.be.true;
expect(memoryTorrentStoreStub.saveTorrent.calledWith(torrentStub)).to.be.true;
});
}
function whenEventStopped(isCompact, noPeers) {
describe("when `event` === stopped", function() {
if (noPeers) {
beforeEach(function () {
torrentStub.getPeers = function () {
return [];
};
});
}
beforeEach(function () {
params
.withCompact(isCompact)
.withEvent('stopped');
output = trackerService.announce(params);
});
returnsResponse(isCompact, noPeers);
it('unregisters the peer from the torrent', function () {
expect(torrentStub.removePeer.callCount).to.equal(1);
expect(torrentStub.removePeer.calledWith('myPeerId')).to.be.true;
});
it('saves updated torrent', function () {
expect(memoryTorrentStoreStub.saveTorrent.callCount).to.equal(1);
expect(memoryTorrentStoreStub.saveTorrent.calledAfter(torrentStub.removePeer)).to.be.true;
expect(memoryTorrentStoreStub.saveTorrent.calledWith(torrentStub)).to.be.true;
});
});
}
function whenEventNotSpecified(isCompact, noPeers) {
describe("when `event` is not specified", function () {
if (noPeers) {
beforeEach(function () {
torrentStub.getPeers = function () {
return [];
};
});
}
beforeEach(function () {
params
.withCompact(isCompact)
.withEvent(undefined);
output = trackerService.announce(params);
});
returnsResponse(isCompact, noPeers);
behavesLikeEventNotSpecified();
});
}
function whenEventStarted(isCompact, noPeers) {
describe("when `event` === started", function () {
if (noPeers) {
beforeEach(function () {
torrentStub.getPeers = function () {
return [];
};
});
}
beforeEach(function () {
params
.withCompact(isCompact)
.withEvent('started');
output = trackerService.announce(params);
});
returnsResponse(isCompact, noPeers);
behavesLikeEventNotSpecified();
});
}
function whenEventCompleted(isCompact, noPeers) {
describe("when `event` === completed", function () {
if (noPeers) {
beforeEach(function () {
torrentStub.getPeers = function () {
return [];
};
});
}
beforeEach(function () {
params
.withCompact(isCompact)
.withEvent('completed');
output = trackerService.announce(params);
});
returnsResponse(isCompact, noPeers);
behavesLikeEventNotSpecified();
});
}
beforeEach(function () {
params
.withPeerId('myPeerId')
.withIp('11.22.33.44')
.withPort(6666)
.withLeft(27);
});
describe("when parameters are valid", function() {
beforeEach(function () {
sinon.stub(AnnounceParamsValidator.prototype, 'validate');
});
afterEach(function () {
AnnounceParamsValidator.prototype.validate.restore();
});
describe('when a compact response is needed', function () {
var isCompact = true;
describe("when there is no peers", function() {
var noPeers = true;
whenEventStopped(isCompact, noPeers);
whenEventNotSpecified(isCompact, noPeers);
whenEventStarted(isCompact, noPeers);
whenEventCompleted(isCompact, noPeers);
});
describe("when there are some peers", function() {
var noPeers = false;
whenEventStopped(isCompact, noPeers);
whenEventNotSpecified(isCompact, noPeers);
whenEventStarted(isCompact, noPeers);
whenEventCompleted(isCompact, noPeers);
});
});
describe('when a compact response is not needed', function () {
var isCompact = false;
describe("when there is no peers", function() {
var noPeers = true;
whenEventStopped(isCompact, noPeers);
whenEventNotSpecified(isCompact, noPeers);
whenEventStarted(isCompact, noPeers);
whenEventCompleted(isCompact, noPeers);
});
describe("when there are some peers", function() {
var noPeers = false;
whenEventStopped(isCompact, noPeers);
whenEventNotSpecified(isCompact, noPeers);
whenEventStarted(isCompact, noPeers);
whenEventCompleted(isCompact, noPeers);
});
});
});
describe("when parameters are not valid", function() {
var message = 'my error message';
beforeEach(function() {
sinon.stub(AnnounceParamsValidator.prototype, 'validate', function() {
throw new Error(message);
});
output = trackerService.announce(params);
});
afterEach(function () {
AnnounceParamsValidator.prototype.validate.restore();
});
returnsError(message);
});
});
});
|
var stream_edit = (function () {
var exports = {};
function setup_subscriptions_stream_hash(sub) {
var id = sub.stream_id;
subs.change_state.prevent_once();
window.location.hash = "#streams" + "/" + id + "/" + hash_util.encodeHashComponent(sub.name);
}
function settings_for_sub(sub) {
var id = parseInt(sub.stream_id, 10);
return $("#subscription_overlay .subscription_settings[data-stream-id='" + id + "']");
}
exports.is_sub_settings_active = function (sub) {
// This function return whether the provided given sub object is
// currently being viewed/edited in the stream edit UI. This is
// used to determine whether we need to rerender the stream edit
// UI when a sub object is modified by an event.
var active_stream = subs.active_stream();
if (active_stream !== undefined && active_stream.id === sub.stream_id) {
return true;
}
return false;
};
function get_email_of_subscribers(subscribers) {
var emails = [];
subscribers.each(function (o, i) {
var email = people.get_person_from_user_id(i).email;
emails.push(email);
});
return emails;
}
exports.rerender_subscribers_list = function (sub) {
if (!sub.can_access_subscribers) {
$(".subscriber_list_settings_container").hide();
} else {
var emails = get_email_of_subscribers(sub.subscribers);
var subscribers_list = list_render.get("stream_subscribers/" + sub.stream_id);
// Changing the data clears the rendered list and the list needs to be re-rendered.
// Perform re-rendering only when the stream settings form of the corresponding
// stream is open.
if (subscribers_list) {
exports.sort_but_pin_current_user_on_top(emails);
subscribers_list.data(emails);
subscribers_list.render();
ui.update_scrollbar($(".subscriber_list_container"));
}
$(".subscriber_list_settings_container").show();
}
};
exports.hide_sub_settings = function (sub) {
var $settings = $(".subscription_settings[data-stream-id='" + sub.stream_id + "']");
$settings.find(".regular_subscription_settings").removeClass('in');
// Clear email address widget
$settings.find(".email-address").html("");
if (!sub.can_change_stream_permissions) {
$settings.find(".change-stream-privacy").hide();
}
};
exports.show_sub_settings = function (sub) {
if (!exports.is_sub_settings_active(sub)) {
return;
}
var $settings = $(".subscription_settings[data-stream-id='" + sub.stream_id + "']");
if ($settings.find(".email-address").val().length === 0) {
// Rerender stream email address, if not.
$settings.find(".email-address").text(sub.email_address);
$settings.find(".stream-email-box").show();
}
$settings.find(".regular_subscription_settings").addClass('in');
};
exports.show_stream_row = function (node, show_settings) {
$(".display-type #add_new_stream_title").hide();
$(".display-type #stream_settings_title, .right .settings").show();
$(".stream-row.active").removeClass("active");
if (show_settings) {
subs.show_subs_pane.settings();
$(node).addClass("active");
stream_edit.show_settings_for(node);
} else {
subs.show_subs_pane.nothing_selected();
}
};
function format_member_list_elem(email) {
var person = people.get_by_email(email);
return templates.render('stream_member_list_entry',
{name: person.full_name, email: email,
displaying_for_admin: page_params.is_admin});
}
function get_subscriber_list(sub_row) {
var id = sub_row.data("stream-id");
return $('.subscription_settings[data-stream-id="' + id + '"] .subscriber-list');
}
exports.update_stream_name = function (sub, new_name) {
var sub_settings = settings_for_sub(sub);
sub_settings.find(".email-address").text(sub.email_address);
sub_settings.find(".stream-name-editable").text(new_name);
};
exports.update_stream_description = function (sub) {
var stream_settings = settings_for_sub(sub);
stream_settings.find('input.description').val(sub.description);
stream_settings.find('.stream-description-editable').html(sub.rendered_description);
};
exports.invite_user_to_stream = function (user_email, sub, success, failure) {
// TODO: use stream_id when backend supports it
var stream_name = sub.name;
return channel.post({
url: "/json/users/me/subscriptions",
data: {subscriptions: JSON.stringify([{name: stream_name}]),
principals: JSON.stringify([user_email])},
success: success,
error: failure,
});
};
exports.remove_user_from_stream = function (user_email, sub, success, failure) {
// TODO: use stream_id when backend supports it
var stream_name = sub.name;
return channel.del({
url: "/json/users/me/subscriptions",
data: {subscriptions: JSON.stringify([stream_name]),
principals: JSON.stringify([user_email])},
success: success,
error: failure,
});
};
function get_stream_id(target) {
if (target.constructor !== jQuery) {
target = $(target);
}
return target.closest(".stream-row, .subscription_settings").attr("data-stream-id");
}
function get_sub_for_target(target) {
var stream_id = get_stream_id(target);
if (!stream_id) {
blueslip.error('Cannot find stream id for target');
return;
}
var sub = stream_data.get_sub_by_id(stream_id);
if (!sub) {
blueslip.error('get_sub_for_target() failed id lookup: ' + stream_id);
return;
}
return sub;
}
exports.sort_but_pin_current_user_on_top = function (emails) {
if (emails === undefined) {
blueslip.error("Undefined emails are passed to function sort_but_pin_current_user_on_top");
return;
}
// Set current user top of subscription list, if subscribed.
if (emails.indexOf(people.my_current_email()) > -1) {
emails.splice(emails.indexOf(people.my_current_email()), 1);
emails.sort();
emails.unshift(people.my_current_email());
} else {
emails.sort();
}
};
function show_subscription_settings(sub_row) {
var stream_id = sub_row.data("stream-id");
var sub = stream_data.get_sub_by_id(stream_id);
var sub_settings = settings_for_sub(sub);
var colorpicker = sub_settings.find('.colorpicker');
var color = stream_data.get_color(sub.name);
stream_color.set_colorpicker_color(colorpicker, color);
if (!sub.render_subscribers) {
return;
}
// fetch subscriber list from memory.
var list = get_subscriber_list(sub_settings);
list.empty();
var emails = get_email_of_subscribers(sub.subscribers);
exports.sort_but_pin_current_user_on_top(emails);
list_render.create(list, emails, {
name: "stream_subscribers/" + stream_id,
modifier: function (item) {
return format_member_list_elem(item);
},
filter: {
element: $("[data-stream-id='" + stream_id + "'] .search"),
callback: function (item, value) {
var person = people.get_by_email(item);
if (person) {
var email = person.email.toLocaleLowerCase();
var full_name = person.full_name.toLowerCase();
return email.indexOf(value) > -1 || full_name.indexOf(value) > -1;
}
},
},
}).init();
ui.set_up_scrollbar($(".subscriber_list_container"));
sub_settings.find('input[name="principal"]').typeahead({
source: people.get_realm_persons, // This is a function.
items: 5,
highlighter: function (item) {
return typeahead_helper.render_person(item);
},
matcher: function (item) {
var query = $.trim(this.query.toLowerCase());
if (query === '' || query === item.email) {
return false;
}
// Case-insensitive.
var item_matches = item.email.toLowerCase().indexOf(query) !== -1 ||
item.full_name.toLowerCase().indexOf(query) !== -1;
var is_subscribed = stream_data.is_user_subscribed(sub.name, item.user_id);
return item_matches && !is_subscribed;
},
sorter: function (matches) {
var current_stream = compose_state.stream_name();
return typeahead_helper.sort_recipientbox_typeahead(
this.query, matches, current_stream);
},
updater: function (item) {
return item.email;
},
});
}
exports.show_settings_for = function (node) {
var stream_id = get_stream_id(node);
var sub = stream_data.get_sub_by_id(stream_id);
stream_data.update_calculated_fields(sub);
var html = templates.render('subscription_settings', sub);
$('.subscriptions .right .settings').html(html);
var sub_settings = settings_for_sub(sub);
$(".nothing-selected").hide();
ui.update_scrollbar($("#subscription_overlay .settings"));
sub_settings.addClass("show");
show_subscription_settings(sub_settings);
};
function stream_home_view_clicked(e) {
var sub = get_sub_for_target(e.target);
if (!sub) {
blueslip.error('stream_home_view_clicked() fails');
return;
}
var sub_settings = settings_for_sub(sub);
var notification_checkboxes = sub_settings.find(".sub_notification_setting");
subs.toggle_home(sub);
if (sub.in_home_view) {
sub_settings.find(".mute-note").addClass("hide-mute-note");
notification_checkboxes.removeClass("muted-sub");
notification_checkboxes.find("input[type='checkbox']").prop("disabled", false);
} else {
sub_settings.find(".mute-note").removeClass("hide-mute-note");
notification_checkboxes.addClass("muted-sub");
notification_checkboxes.find("input[type='checkbox']").attr("disabled", true);
}
}
exports.bulk_set_stream_property = function (sub_data) {
return channel.post({
url: '/json/users/me/subscriptions/properties',
data: {subscription_data: JSON.stringify(sub_data)},
timeout: 10 * 1000,
});
};
exports.set_stream_property = function (sub, property, value) {
var sub_data = {stream_id: sub.stream_id, property: property, value: value};
exports.bulk_set_stream_property([sub_data]);
};
exports.set_notification_setting_for_all_streams = function (notification_type, new_setting) {
var sub_data = [];
_.each(stream_data.subscribed_subs(), function (sub) {
if (sub[notification_type] !== new_setting) {
sub_data.push({
stream_id: sub.stream_id,
property: notification_type,
value: new_setting,
});
}
});
exports.bulk_set_stream_property(sub_data);
};
function redraw_privacy_related_stuff(sub_row, sub) {
var stream_settings = settings_for_sub(sub);
var html;
stream_data.update_calculated_fields(sub);
html = templates.render('subscription_setting_icon', sub);
sub_row.find('.icon').expectOne().replaceWith($(html));
html = templates.render('subscription_type', sub);
stream_settings.find('.subscription-type-text').expectOne().html(html);
if (sub.invite_only) {
stream_settings.find(".large-icon")
.removeClass("hash").addClass("lock")
.html("<i class='fa fa-lock' aria-hidden='true'></i>");
} else {
stream_settings.find(".large-icon")
.addClass("hash").removeClass("lock")
.html("");
}
stream_list.redraw_stream_privacy(sub);
}
function change_stream_privacy(e) {
e.stopPropagation();
var stream_id = $(e.target).data("stream-id");
var sub = stream_data.get_sub_by_id(stream_id);
var privacy_setting = $('#stream_privacy_modal input[name=privacy]:checked').val();
var is_announcement_only = $('#stream_privacy_modal input[name=is-announcement-only]').prop('checked');
var invite_only;
var history_public_to_subscribers;
if (privacy_setting === 'invite-only') {
invite_only = true;
history_public_to_subscribers = false;
} else if (privacy_setting === 'invite-only-public-history') {
invite_only = true;
history_public_to_subscribers = true;
} else {
invite_only = false;
history_public_to_subscribers = true;
}
$(".stream_change_property_info").hide();
var data = {
stream_name: sub.name,
// toggle the privacy setting
is_private: JSON.stringify(invite_only),
is_announcement_only: JSON.stringify(is_announcement_only),
history_public_to_subscribers: JSON.stringify(history_public_to_subscribers),
};
channel.patch({
url: "/json/streams/" + stream_id,
data: data,
success: function () {
sub = stream_data.get_sub_by_id(stream_id);
var sub_row = $(".stream-row[data-stream-id='" + stream_id + "']");
// save new privacy settings.
sub.invite_only = invite_only;
sub.is_announcement_only = is_announcement_only;
sub.history_public_to_subscribers = history_public_to_subscribers;
redraw_privacy_related_stuff(sub_row, sub);
$("#stream_privacy_modal").remove();
// For auto update, without rendering whole template
stream_data.update_calculated_fields(sub);
if (!sub.can_change_stream_permissions) {
$(".change-stream-privacy").hide();
}
},
error: function () {
$("#change-stream-privacy-button").text(i18n.t("Try again"));
},
});
}
function stream_desktop_notifications_clicked(e) {
var sub = get_sub_for_target(e.target);
sub.desktop_notifications = !sub.desktop_notifications;
exports.set_stream_property(sub, 'desktop_notifications', sub.desktop_notifications);
}
function stream_audible_notifications_clicked(e) {
var sub = get_sub_for_target(e.target);
sub.audible_notifications = !sub.audible_notifications;
exports.set_stream_property(sub, 'audible_notifications', sub.audible_notifications);
}
function stream_push_notifications_clicked(e) {
var sub = get_sub_for_target(e.target);
sub.push_notifications = !sub.push_notifications;
exports.set_stream_property(sub, 'push_notifications', sub.push_notifications);
}
function stream_email_notifications_clicked(e) {
var sub = get_sub_for_target(e.target);
sub.email_notifications = !sub.email_notifications;
exports.set_stream_property(sub, 'email_notifications', sub.email_notifications);
}
function stream_pin_clicked(e) {
var sub = get_sub_for_target(e.target);
if (!sub) {
blueslip.error('stream_pin_clicked() fails');
return;
}
subs.toggle_pin_to_top_stream(sub);
}
exports.change_stream_name = function (e) {
e.preventDefault();
var sub_settings = $(e.target).closest('.subscription_settings');
var stream_id = $(e.target).closest(".subscription_settings").attr("data-stream-id");
var new_name_box = sub_settings.find('.stream-name-editable');
var new_name = $.trim(new_name_box.text());
$(".stream_change_property_info").hide();
channel.patch({
// Stream names might contain unsafe characters so we must encode it first.
url: "/json/streams/" + stream_id,
data: {new_name: JSON.stringify(new_name)},
success: function () {
new_name_box.val('');
ui_report.success(i18n.t("The stream has been renamed!"), $(".stream_change_property_info"));
},
error: function (xhr) {
new_name_box.text(stream_data.maybe_get_stream_name(stream_id));
ui_report.error(i18n.t("Error"), xhr, $(".stream_change_property_info"));
ui.update_scrollbar($("#subscription_overlay .settings"));
},
});
};
exports.change_stream_description = function (e) {
e.preventDefault();
var sub_settings = $(e.target).closest('.subscription_settings');
var sub = get_sub_for_target(sub_settings);
if (!sub) {
blueslip.error('change_stream_description() fails');
return;
}
var stream_id = sub.stream_id;
var description = sub_settings.find('.stream-description-editable').text().trim();
$(".stream_change_property_info").hide();
channel.patch({
// Description might contain unsafe characters so we must encode it first.
url: '/json/streams/' + stream_id,
data: {
description: JSON.stringify(description),
},
success: function () {
// The event from the server will update the rest of the UI
ui_report.success(i18n.t("The stream description has been updated!"),
$(".stream_change_property_info"));
},
error: function (xhr) {
sub_settings.find('.stream-description-editable').html(sub.rendered_description);
ui_report.error(i18n.t("Error"), xhr, $(".stream_change_property_info"));
ui.update_scrollbar($("#subscription_overlay .settings"));
},
});
};
exports.delete_stream = function (stream_id, alert_element, stream_row) {
channel.del({
url: '/json/streams/' + stream_id,
error: function (xhr) {
ui_report.error(i18n.t("Failed"), xhr, alert_element);
},
success: function () {
stream_row.remove();
},
});
};
exports.initialize = function () {
$("#zfilt").on("click", ".stream_sub_unsub_button", function (e) {
e.preventDefault();
e.stopPropagation();
var stream_name = narrow_state.stream();
if (stream_name === undefined) {
return;
}
var sub = stream_data.get_sub(stream_name);
subs.sub_or_unsub(sub);
});
$("#subscriptions_table").on("click", ".change-stream-privacy", function (e) {
var stream_id = get_stream_id(e.target);
var stream = stream_data.get_sub_by_id(stream_id);
var template_data = {
stream_id: stream_id,
stream_name: stream.name,
is_announcement_only: stream.is_announcement_only,
is_public: !stream.invite_only,
is_private: stream.invite_only && !stream.history_public_to_subscribers,
is_private_with_public_history: stream.invite_only &&
stream.history_public_to_subscribers,
};
var change_privacy_modal = templates.render("subscription_stream_privacy_modal", template_data);
$("#stream_privacy_modal").remove();
$("#subscriptions_table").append(change_privacy_modal);
overlays.open_modal('stream_privacy_modal');
});
$("#subscriptions_table").on('click', '#change-stream-privacy-button',
change_stream_privacy);
$("#subscriptions_table").on('click', '.close-privacy-modal', function (e) {
// This fixes a weird bug in which, subscription_settings hides
// unexpectedly by clicking the cancel button.
e.stopPropagation();
});
$("#subscriptions_table").on("click", "#sub_setting_not_in_home_view",
stream_home_view_clicked);
$("#subscriptions_table").on("click", "#sub_desktop_notifications_setting",
stream_desktop_notifications_clicked);
$("#subscriptions_table").on("click", "#sub_audible_notifications_setting",
stream_audible_notifications_clicked);
$("#subscriptions_table").on("click", "#sub_push_notifications_setting",
stream_push_notifications_clicked);
$("#subscriptions_table").on("click", "#sub_email_notifications_setting",
stream_email_notifications_clicked);
$("#subscriptions_table").on("click", "#sub_pin_setting",
stream_pin_clicked);
$("#subscriptions_table").on("submit", ".subscriber_list_add form", function (e) {
e.preventDefault();
var settings_row = $(e.target).closest('.subscription_settings');
var sub = get_sub_for_target(settings_row);
if (!sub) {
blueslip.error('.subscriber_list_add form submit fails');
return;
}
var text_box = settings_row.find('input[name="principal"]');
var principal = $.trim(text_box.val());
var stream_subscription_info_elem = $('.stream_subscription_info').expectOne();
function invite_success(data) {
text_box.val('');
if (data.subscribed.hasOwnProperty(principal)) {
stream_subscription_info_elem.text(i18n.t("Subscribed successfully!"));
// The rest of the work is done via the subscription -> add event we will get
} else {
stream_subscription_info_elem.text(i18n.t("User already subscribed."));
}
stream_subscription_info_elem.addClass("text-success")
.removeClass("text-error");
}
function invite_failure(xhr) {
var error = JSON.parse(xhr.responseText);
stream_subscription_info_elem.text(error.msg)
.addClass("text-error").removeClass("text-success");
}
exports.invite_user_to_stream(principal, sub, invite_success, invite_failure);
});
$("#subscriptions_table").on("submit", ".subscriber_list_remove form", function (e) {
e.preventDefault();
var list_entry = $(e.target).closest("tr");
var principal = list_entry.children(".subscriber-email").text();
var settings_row = $(e.target).closest('.subscription_settings');
var sub = get_sub_for_target(settings_row);
if (!sub) {
blueslip.error('.subscriber_list_remove form submit fails');
return;
}
var stream_subscription_info_elem = $('.stream_subscription_info').expectOne();
function removal_success(data) {
if (data.removed.length > 0) {
// Remove the user from the subscriber list.
list_entry.remove();
stream_subscription_info_elem.text(i18n.t("Unsubscribed successfully!"));
// The rest of the work is done via the subscription -> remove event we will get
} else {
stream_subscription_info_elem.text(i18n.t("User is already not subscribed."));
}
stream_subscription_info_elem.addClass('text-success')
.removeClass('text-error');
ui.update_scrollbar($("#subscription_overlay .settings"));
}
function removal_failure() {
stream_subscription_info_elem.text(i18n.t("Error removing user from this stream."))
.addClass("text-error").removeClass("text-success");
}
exports.remove_user_from_stream(principal, sub, removal_success,
removal_failure);
});
// This handler isn't part of the normal edit interface; it's the convenient
// checkmark in the subscriber list.
$("#subscriptions_table").on("click", ".sub_unsub_button", function (e) {
var sub = get_sub_for_target(e.target);
var stream_row = $(this).parent();
subs.sub_or_unsub(sub);
var sub_settings = settings_for_sub(sub);
var regular_sub_settings = sub_settings.find(".regular_subscription_settings");
if (!sub.subscribed) {
regular_sub_settings.addClass("in");
exports.show_stream_row(stream_row, true);
} else {
regular_sub_settings.removeClass("in");
}
setup_subscriptions_stream_hash(sub);
e.preventDefault();
e.stopPropagation();
});
$("#subscriptions_table").on("click", ".deactivate", function (e) {
e.preventDefault();
e.stopPropagation();
var stream_id = get_stream_id(e.target);
if (!stream_id) {
ui_report.message(i18n.t("Invalid stream id"), $(".stream_change_property_info"), 'alert-error');
return;
}
var stream_name = stream_data.maybe_get_stream_name(stream_id);
var deactivate_stream_modal = templates.render("deactivation-stream-modal", {stream_name: stream_name});
$(".subscription_settings").append(deactivate_stream_modal);
overlays.open_modal('deactivation_stream_modal');
});
$("#subscriptions_table").on("click", "#do_deactivate_stream_button", function (e) {
var stream_id = get_stream_id(e.target);
overlays.close_modal('deactivation_stream_modal');
$("#deactivation_stream_modal").remove();
if (!stream_id) {
ui_report.message(i18n.t("Invalid stream id"), $(".stream_change_property_info"), 'alert-error');
return;
}
var row = $(".stream-row.active");
exports.delete_stream(stream_id, $(".stream_change_property_info"), row);
});
$("#subscriptions_table").on("hide.bs.modal", "#deactivation_stream_modal", function () {
$("#deactivation_stream_modal").remove();
});
$("#subscriptions_table").on("click", ".stream-row", function (e) {
if ($(e.target).closest(".check, .subscription_settings").length === 0) {
exports.show_stream_row(this, true);
var stream_id = $(this).attr("data-stream-id");
var sub = stream_data.get_sub_by_id(stream_id);
setup_subscriptions_stream_hash(sub);
}
});
$(document).on('peer_subscribe.zulip', function (e, data) {
var sub = stream_data.get_sub(data.stream_name);
subs.rerender_subscriptions_settings(sub);
});
$(document).on('peer_unsubscribe.zulip', function (e, data) {
var sub = stream_data.get_sub(data.stream_name);
subs.rerender_subscriptions_settings(sub);
});
};
return exports;
}());
if (typeof module !== 'undefined') {
module.exports = stream_edit;
}
window.stream_edit = stream_edit;
|
jQuery('.skillbar').each(function(){
jQuery(this).find('.skillbar-bar').animate({
width:jQuery(this).attr('data-percent')
},2000);
});
|
!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,n){"use strict";var r=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}();var o=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.version="0.0.1",this.cacheList={}}return r(e,[{key:"setCache",value:function(e,t){this.cacheList[e]=t}},{key:"getCache",value:function(e){return this.cacheList[e]}}]),e}();window.ForceTool=o}]);
|
"main";_21d.x([["formatNumber",()=>formatNumber],["formatCurrency",()=>formatCurrency],["getThumbnailUrl",()=>getThumbnailUrl],["getParentIds",()=>getParentIds]]);const formatNumber = (number = 0, settings) => {
const x = 3;
const re = '\\d(?=(\\d{' + x + '})+' + (settings.decimal_number > 0 ? '\\D' : '$') + ')';
let num = (number || 0).toFixed(Math.max(0, ~~settings.decimal_number));
return (settings.decimal_separator ? num.replace('.', settings.decimal_separator) : num).replace(new RegExp(re, 'g'), '$&' + settings.thousand_separator);
};
const amountPattern = '{amount}';
const formatCurrency = (number = 0, settings) => {
return settings.currency_format.replace(amountPattern, formatNumber(number, settings));
};
const getThumbnailUrl = (originalUrl, width) => {
if (originalUrl && originalUrl.length > 0) {
const pos = originalUrl.lastIndexOf('/');
const thumbnailUrl = originalUrl.substring(0, pos) + `/${width}/` + originalUrl.substring(pos + 1);
return thumbnailUrl;
} else {
return '';
}
};
const getParentIds = (categories, categoryId) => {
let parentIds = [];
let parentExists = false;
do {
const category = categories.find(item => item.id === categoryId);
parentExists = category && category.parent_id;
if (parentExists) {
parentIds.push(category.parent_id);
categoryId = category.parent_id;
}
} while (parentExists);
return parentIds;
};
|
console.log('utils.js')
const name = 'rajan';
const add = function(a, b) {
return a + b ;
}
//module.exports = name
module.exports = add
|
self.__precacheManifest = [
{
"revision": "ff66b25a0ebf00d45f6a72f7fc265f2c",
"url": "/img/brand/logo.png"
},
{
"revision": "1dd2fce4c79c5cd8fa2a06fc30baca5d",
"url": "/img/brand/plots screenshot.png"
},
{
"revision": "0fc390b64ce6957d01f9",
"url": "/js/chunk-vendors.15824258.js"
},
{
"revision": "8f23df122fc78432490934ac08e59061",
"url": "/img/theme/ManjotPahwa.png"
},
{
"revision": "be997d5226b992ffad34816870c6b7aa",
"url": "/img/theme/team-2-800x800.jpg"
},
{
"revision": "fd4a34d026fb9e0f4867188d47b11ba8",
"url": "/img/theme/img-1-1200x1000.jpg"
},
{
"revision": "a7435bbc0a1b62ea82777077cec85d50",
"url": "/img/header-img.png"
},
{
"revision": "0b8a30b10cbe7708d5f3a4b007c1d665",
"url": "/img/nucleo-icons.0b8a30b1.svg"
},
{
"revision": "7789b5bfa57722dd8916b1b9ff1b1d37",
"url": "/img/theme/img-2-1200x1000.jpg"
},
{
"revision": "54e3f3c414bd8e7234bae3ee3be950e5",
"url": "/img/theme/team-3-800x800.jpg"
},
{
"revision": "538acb7b7372c338e37ba9b5e1abb16a",
"url": "/img/women_preso_discussing.png"
},
{
"revision": "66618a418175ddf2ac8c47a241d327a8",
"url": "/img/theme/team-4-800x800.jpg"
},
{
"revision": "912ec66d7572ff821749319396470bde",
"url": "/img/fontawesome-webfont.912ec66d.svg"
},
{
"revision": "816ae368141c872173abadad685cadf0",
"url": "/index.html"
},
{
"revision": "edc7106b21ec12e57022b2ebd534cd2d",
"url": "/img/theme/team-1-800x800.jpg"
},
{
"revision": "594b1ee1d95ada356eaad078e9217932",
"url": "/img/ill/ill-2.svg"
},
{
"revision": "dc49ad52655e1d9d0552c026db3ef688",
"url": "/img/theme/landing.jpg"
},
{
"revision": "76f0657b89251f66c80452ca4efd8797",
"url": "/img/theme/ChandraPrakash.jpeg"
},
{
"revision": "71883344aa1fb0c1bac4a7d2cc6308ac",
"url": "/img/theme/HimanshuChaudhary.jpeg"
},
{
"revision": "6fafe4baca9d50d61a898c84ade7afa3",
"url": "/img/brand/white.png"
},
{
"revision": "981ef6e04a37bcd4e291",
"url": "/js/app.1a0517b0.js"
},
{
"revision": "a7eee6a9698ab66b0f93f931282bda6a",
"url": "/img/theme/ManishSachdev.jpeg"
},
{
"revision": "974088a1931e40895bac6db119c62448",
"url": "/img/theme/promo-1.png"
},
{
"revision": "39d48b47ddec702a2a0708e025a5507f",
"url": "/img/theme/ManjotPahwaSquare.jpg"
},
{
"revision": "20d702b83a06bdb2ea71c4c0cb9a7a56",
"url": "/img/theme/profile.jpg"
},
{
"revision": "15689451f4887312a8fec873746f82f2",
"url": "/img/2women_humaaans_discuss.png"
},
{
"revision": "c47104936cd781b936927cc1fc33543b",
"url": "/favicon.png"
},
{
"revision": "c85c75275c0a0a617f9e5accc2700908",
"url": "/img/brand/creativetim-white-slim.png"
},
{
"revision": "8e55eab46b5fcfc4a7a0b27cb07c8888",
"url": "/img/brand/github-white-slim.png"
},
{
"revision": "185288d13ed8e9d745bd279ea34667bf",
"url": "/img/brand/blue.png"
},
{
"revision": "b06871f281fee6b241d60582ae9369b9",
"url": "/fonts/fontawesome-webfont.b06871f2.ttf"
},
{
"revision": "674f50d287a8c48dc19ba404d20fe713",
"url": "/fonts/fontawesome-webfont.674f50d2.eot"
},
{
"revision": "c47104936cd781b936927cc1fc33543b",
"url": "/img/brand/favicon.png"
},
{
"revision": "fee66e712a8a08eef5805a46892932ad",
"url": "/fonts/fontawesome-webfont.fee66e71.woff"
},
{
"revision": "af7ae505a9eed503f8b8e6982036873e",
"url": "/fonts/fontawesome-webfont.af7ae505.woff2"
},
{
"revision": "f82ec6ba2dc4181db2af35c499462840",
"url": "/fonts/nucleo-icons.f82ec6ba.ttf"
},
{
"revision": "c1733565b32b585676302d4233c39da8",
"url": "/fonts/nucleo-icons.c1733565.eot"
},
{
"revision": "426439788ec5ba772cdf94057f6f4659",
"url": "/fonts/nucleo-icons.42643978.woff2"
},
{
"revision": "2569aaea6eaaf8cd210db7f2fa016743",
"url": "/fonts/nucleo-icons.2569aaea.woff"
},
{
"revision": "981ef6e04a37bcd4e291",
"url": "/css/app.9ef16e3c.css"
}
];
|
import {TYPE, URL} from "../../config"
import 'whatwg-fetch'
const _URL = URL.EVALUATION.EVALUATION_ALL
const _TYPE = TYPE.EVALUATION.EVALUATION_ALL
export function getUserEvaluation(calendar, semester) {
return function (dispatch) {
fetch(_URL.GET_USER_EVALUATION(calendar, semester), {
credentials: 'same-origin'
}).then(function (response) {
return response.json()
}).then(function (json) {
dispatch({
type: _TYPE.SET_USER_EVALUATION,
payload: json
})
})
}
}
export function UpdateUserEvaluation(user_evaluation) {
return function (dispatch) {
dispatch({
type: _TYPE.SET_USER_EVALUATION,
payload: user_evaluation
})
}
}
|
//
// debugSurfaceGeometryPass.js
//
// Created by Sam Gateau on 6/6/2016
// Copyright 2016 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or https://www.apache.org/licenses/LICENSE-2.0.html
//
// Set up the qml ui
var qml = Script.resolvePath('ambientOcclusionPass.qml');
var window = new OverlayWindow({
title: 'Ambient Occlusion Pass',
source: qml,
width: 400, height: 300,
});
window.setPosition(Window.innerWidth - 420, 50 + 550 + 50);
window.closed.connect(function() { Script.stop(); });
var moveDebugCursor = false;
Controller.mousePressEvent.connect(function (e) {
if (e.isMiddleButton) {
moveDebugCursor = true;
setDebugCursor(e.x, e.y);
}
});
Controller.mouseReleaseEvent.connect(function() { moveDebugCursor = false; });
Controller.mouseMoveEvent.connect(function (e) { if (moveDebugCursor) setDebugCursor(e.x, e.y); });
function setDebugCursor(x, y) {
nx = (x / Window.innerWidth);
ny = 1.0 - ((y) / (Window.innerHeight - 32));
Render.getConfig("RenderMainView").getConfig("DebugAmbientOcclusion").debugCursorTexcoord = { x: nx, y: ny };
}
|
module.exports={D:{"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0.028032,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0.004672,"19":0,"20":0.004672,"21":0,"22":0.032704,"23":0,"24":0.014016,"25":0.014016,"26":0.009344,"27":0,"28":0,"29":0.009344,"30":0,"31":0.009344,"32":0,"33":0.004672,"34":0.02336,"35":0.004672,"36":0.065408,"37":0.004672,"38":0.037376,"39":0.018688,"40":0.004672,"41":0.004672,"42":0.004672,"43":0.032704,"44":0.032704,"45":0.014016,"46":0.014016,"47":0.009344,"48":0.02336,"49":0.9344,"50":0.018688,"51":0.121472,"52":0.037376,"53":0.065408,"54":0.056064,"55":0.14016,"56":0.172864,"57":0.065408,"58":0.289664,"59":6.7744,"60":22.392896,"61":0.042048,"62":0.018688,"63":0,"64":0,"65":0},C:{"2":0,"3":0.004672,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0.004672,"16":0.032704,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0.009344,"30":0,"31":0,"32":0,"33":0.009344,"34":0.032704,"35":0,"36":0.004672,"37":0.004672,"38":0.004672,"39":0.004672,"40":0.014016,"41":0,"42":0,"43":0.018688,"44":0,"45":0.065408,"46":0.018688,"47":0.04672,"48":0.074752,"49":0.009344,"50":0.018688,"51":0.018688,"52":0.200896,"53":0.056064,"54":2.620992,"55":1.041856,"56":0.009344,"57":0.004672,"58":0,"59":0,"3.5":0,"3.6":0.004672},F:{"9":0,"11":0,"12":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0.004672,"27":0.004672,"28":0.004672,"29":0.004672,"30":0,"31":0,"32":0,"33":0.004672,"34":0,"35":0.004672,"36":0.018688,"37":0.014016,"38":0.004672,"39":0,"40":0,"41":0.014016,"42":0.004672,"43":0,"44":0,"45":0.009344,"46":0.401792,"47":0.3504,"48":0.009344,"49":0.004672,_:"50","9.5-9.6":0,"10.0-10.1":0.009344,"10.5":0,"10.6":0,"11.1":0,"11.5":0,"11.6":0,"12.1":0.009344},E:{"4":0.004672,"5":0.004672,"6":0,"7":0,"8":0.02336,"9":0.051392,"10":0.331712,"11":0,_:"0","3.1":0,"3.2":0,"5.1":0.004672,"6.1":0.009344,"7.1":0.004672,"9.1":0.219584,"10.1":1.44832},G:{"8":0,"11":2.64440386187,"3.2":0,"4.0-4.1":0,"4.2-4.3":0,"5.0-5.1":0,"6.0-6.1":0,"7.0-7.1":0.0302771223022,"8.1-8.4":0.0266438676259,"9.0-9.2":0,"9.3":0.190140328058,"10.0-10.2":0.36271992518,"10.3":1.79603889496},I:{"3":0,"4":0.0756533562232,_:"56","2.1":0,"2.2":0,"2.3":0,"4.1":0.266588017167,"4.2-4.3":0.720508154506,"4.4":1.97779488412,"4.4.3-4.4.4":1.15641558798},K:{_:"0 10 11 12 11.1 11.5 12.1"},A:{"6":0.00477536283186,"7":0.00477536283186,"8":0.105057982301,"9":0.0429782654867,"10":0.0955072566372,"11":0.826137769912,"5.5":0},B:{"12":0.088768,"13":0.1168,"14":0.345728,"15":0.42048,"16":0},J:{"7":0.0170496,"10":0.0681984},P:{"4":0,"5":0},N:{"10":0.10396,"11":0.2599},R:{_:"0"},M:{"0":0.010656},Q:{_:"1.2"},O:{"0":0.953712},H:{"0":1.83177345695},L:{"0":41.25616}};
|
module.exports={A:{A:{"1":"E A B","2":"K C G YB"},B:{"1":"D w Z I M H"},C:{"1":"0 1 3 5 6 7 8 P Q R S T U V W X Y y a b c d e f L h i j k l m n o p q r s t u v z x","2":"WB AB","260":"F J K C G E A B D w Z I M H N O UB OB"},D:{"1":"0 1 3 5 6 7 8 F J K C G E A B D w Z I M H N O P Q R S T U V W X Y y a b c d e f L h i j k l m n o p q r s t u v z x BB IB DB FB ZB GB"},E:{"1":"F J K C G E A JB KB LB MB NB","2":"HB CB","513":"B g PB"},F:{"1":"4 9 B D I M H N O P Q R S T U V W X Y y a b c d e f L h i j k l m n o p q r s t u v SB TB g VB","2":"E QB RB"},G:{"1":"2 G CB XB EB aB bB cB dB eB fB gB","513":"hB iB"},H:{"2":"jB"},I:{"1":"2 AB F BB mB nB oB pB","132":"kB lB"},J:{"1":"C A"},K:{"1":"4 9 B D L g","2":"A"},L:{"1":"DB"},M:{"1":"x"},N:{"1":"A B"},O:{"1":"qB"},P:{"1":"F J rB"},Q:{"1":"sB"},R:{"1":"tB"}},B:1,C:"Video element"};
|
<html>
<body>
<div class="container">
<div class="header">
<ul class="nav">
<li class="active"><a href="#"></a>Home</li>
<li><a href="#"></a>About</li>
<li><a href="#"></a>Contact</li>
</ul>
<h3 class="text-muted">CSS Inspections</h3>
</div>
<div class="row">
<div class="col-xs-3">
<div class="panel panel-default">
<div class="panel-heading"></div>
<div class="panel-body"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-3">
<div class="panel panel-default">
<div class="panel-heading-primary"></div>
<div class="panel-body"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-3">
<div class="panel panel-default">
<div class="panel-heading-primary"></div>
<div class="panel-body"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-3">
<div class="panel panel-default">
<div class="panel-heading-primary"></div>
<div class="panel-body"></div>
</div>
</div>
</div>
</div>
</body>
</html>
<script>
/*
//Create a button to prepend a table on generation that will be used for printing function execution.
$("button").click(function(){
$("tr.text-center").each(function(){
message = $(this).text();
console.log(message);
});
});
//END BUTTON snippet
*/
//BEGIN TABLE FUNCTION
/*
function mytablefunction(){
//Set global variables
//tableHeader variables
var headerVal="";
var headers = "";
var headersFull ="";
//tableBody variables
var lineHTML="";
var evalPartial="";
var tableData="";
var tblCounter = 0;
var rowHTML="";
//finalStich variables
var finalStringPiece = "";
*/
//Begin table Header Function
/*
var headersFunction = function(){
//If TESTING UNCOMMENT BELOW AND RUN AS COMMAND
//var headerVal ="";
//var headers="";
//var headersFull="";
//Define length of headers for the report by "col" count
var colCnt = $("col").length;
var $CustomDataVals = $("#CustomData > thead > tr > th > a");
//Create condition to valuate a good table
if(colCnt!=$CustomDataVals.length){
console.log("Sorry, this report cannot be printed! Due to column matching error.");
} else {
//Begin process if table lengths match
console.log("There are " + colCnt + " header columns for this report."+"\n"+"Building columns now...");
//iterate table head values and write to a variable "headers"
$($CustomDataVals).each(function(){
headerVal = "<td>" + $(this).text() +"</td>";
//Uncommenting below will show the process of building the table
console.log(headers);
headers += headerVal;
});
//Surround the built table data with a table row and head
console.log("The table Header has completed, see below:")
headersFull = '<thead><tr class="whatever">' + headers + "</tr></thead>";
//Below shows that the headers variable is being populated correctly
console.log(headersFull);
};
};
//End table Header Function (TableHeaders Now defined as "headersFull")
*/
//Comment out starred area comment below to test
/*
(function(){
tableDataFunction()
finalStringPiece = '<table class="table table-responsive">' + headersFull + '</table>';
console.log(finalStringPiece);
});
*/
//Comment out starred area comment below to test - END
/*
//Begin tableBody Function
var tableDataFunction = function(){
//If TESTING UNCOMMENT BELOW AND RUN AS COMMAND
var rowHTML, lineHTML, evalPartial, tableData="";
var tblCounter=0;
//cache the table rows
var cachedRows = $("#rdDataTableDiv-CustomData").find("tr").siblings();
//console.log(cachedRows);
rowHTML = "<tbody>";
$(cachedRows).each(function(){
//testing logger below, uncomment to test
tblCounter ++;
//log row being added
console.log("running row " + tblCounter );
//log the line to be added
console.log($(this).text());
//for each line, grab the text by span
$(this).find("span").each(function(){
//td values by row
console.log($(this).text());
})
//Set Local Variables
var $iterationCount = cachedRows.length;
var $cachedText = "";
$(this).find("td").each(function(){
$cachedText = $(this).find("span").text();
});
console.log("iterations to be performed: " + $iterationCount);
//while($iterationCount!=tblCounter)
console.log("cached text res: " +$cachedText);
evalPartial = $cachedText;
console.log(evalPartial);
if (evalPartial == "USD"){
};
});
};
*/
/*
//BEGIN CONSTRUCTOR SECTION
//uncomment below for testing variables
//var finalStringPiece = "";
var constructFinal = function(){
//Stitch pieces together
//set table header then add tableBody to it
finalStringPiece = "HTML FILE PASSED"; //headers + tableData;
console.log(finalStringPiece);
//Below opens a new page with the built string
var launcherWindow = function(){
//alert user going to new window
alert("Opening a new window to display print view.");
//Create the window, and set window options
var myPrintWindow = window.open("", "MsgWindow", "width=full, height=full");
//Send the constructed print view to the window for printing, and print it
(function(){
//Below the new window is launched, and the string piece constructed
//prior written into the new window. Then the print function is called
myPrintWindow.document.write(finalStringPiece);
myPrintWindow.print();
})();
};
//Launches new window that gets fed the composed "finalStringPiece" variable (HTML)
launcherWindow();
};
//END FINAL CONSTRUCTOR PIECE
*/
</script>
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const index = require('./index-71713531.js');
function generateClasses(classes) {
return classes.filter(Boolean).join(' ');
}
const proButtonCss = "*{margin:0;padding:0;box-sizing:border-box;font-smoothing:antialiased;font-family:Nunito, sans-serif}button{background:transparent;border:none;outline:none;cursor:pointer}:host{all:initial}.pro-button{border-radius:4px;font-family:Nunito;font-style:normal;font-weight:bold;font-size:16px;line-height:22px}.pro-button.small{height:32px;padding:0 16px}.pro-button.medium{height:40px;padding:0 24px}.pro-button.large{height:48px;padding:0 32px}.pro-button.primary{background:var(--pro-color-primary-500);color:var(--pro-color-white)}.pro-button.primary:hover{background:var(--pro-color-primary-700)}.pro-button.outline-primary{background:transparent;color:var(--pro-color-primary-500);border:1px solid var(--pro-color-primary-500)}.pro-button.outline-primary:hover{color:var(--pro-color-primary-600);background:var(--pro-color-primary-100);border:1px solid var(--pro-color-primary-600)}.pro-button.secondary{background:var(--pro-color-secondary-600);color:var(--pro-color-white)}.pro-button.secondary:hover{background:var(--pro-color-secondary-400)}.pro-button.outline-secondary{background:transparent;color:var(--pro-color-secondary-500);border:1px solid var(--pro-color-secondary-500)}.pro-button.outline-secondary:hover{color:var(--pro-color-secondary-600);background:var(--pro-color-secondary-100);border:1px solid var(--pro-color-secondary-600)}.pro-button.neutral{background:var(--pro-color-base-600);color:var(--pro-color-white)}.pro-button.neutral:hover{background:var(--pro-color-base-400)}.pro-button.outline-neutral{background:transparent;color:var(--pro-color-base-600);border:1px solid var(--pro-color-base-600)}.pro-button.outline-neutral:hover{background:var(--pro-color-base-100);color:var(--pro-color-base-500);border:1px solid var(--pro-color-base-500)}.pro-button.success{background:var(--pro-color-success-600);color:var(--pro-color-white)}.pro-button.success:hover{background:var(--pro-color-success-700)}.pro-button.outline-success{background:transparent;color:var(--pro-color-success-600);border:1px solid var(--pro-color-success-600)}.pro-button.outline-success:hover{background:var(--pro-color-success-100);color:var(--pro-color-success-700);border:1px solid var(--pro-color-success-700)}.pro-button.info{background:var(--pro-color-info-600);color:var(--pro-color-white)}.pro-button.info:hover{background:var(--pro-color-info-700)}.pro-button.outline-info{background:transparent;color:var(--pro-color-info-600);border:1px solid var(--pro-color-info-600)}.pro-button.outline-info:hover{background:var(--pro-color-info-100);color:var(--pro-color-info-700);border:1px solid var(--pro-color-info-700)}.pro-button.warning{background:var(--pro-color-warning-500);color:var(--pro-color-warning-900)}.pro-button.warning:hover{background:var(--pro-color-warning-600)}.pro-button.outline-warning{background:transparent;color:var(--pro-color-warning-800);border:1px solid var(--pro-color-warning-800)}.pro-button.outline-warning:hover{background:var(--pro-color-warning-100);color:var(--pro-color-warning-900);border:1px solid var(--pro-color-warning-900)}.pro-button.danger{background:var(--pro-color-danger-500);color:var(--pro-color-white)}.pro-button.danger:hover{background:var(--pro-color-danger-600)}.pro-button.outline-danger{background:transparent;color:var(--pro-color-danger-500);border:1px solid var(--pro-color-danger-500)}.pro-button.outline-danger:hover{background:var(--pro-color-danger-100);color:var(--pro-color-danger-600);border:1px solid var(--pro-color-danger-600)}.pro-button:disabled{background:var(--pro-color-base-200);color:var(--pro-color-base-400);cursor:not-allowed;border:0}.pro-button:disabled:hover{border:0;background:var(--pro-color-base-200);color:var(--pro-color-base-400)}";
const ProButton = class {
constructor(hostRef) {
index.registerInstance(this, hostRef);
this.variant = "primary";
this.size = "small";
this.disabled = false;
}
classes() {
return generateClasses(["pro-button", this.size, this.variant]);
}
render() {
return (index.h("button", { class: this.classes(), disabled: !!this.disabled }, index.h("slot", null)));
}
};
ProButton.style = proButtonCss;
exports.pro_button = ProButton;
|
var express = require('express');
var router = express.Router();
var databaseConfig = require('../../models/db');
var fs = require('fs');
// Danh sách nhân viên
router.get('/', function (req, res, next) {
const sql = 'SELECT * FROM quydinh '
databaseConfig.query(sql, function (err, rows) {
if (err) {
req.flash('error', err);
res.render('admin/rule/index',
{
data: '',
user: req.session.user,
layout: 'orther'
});
} else {
res.render('admin/rule/index',
{
data: rows,
user: req.session.user,
layout: 'orther'
});
}
})
})
router.get('/create', function (req, res, next) {
res.render('admin/rule/create',
{
user: req.session.user,
layout: 'orther'
});
})
router.post('/create', function (req, res, next) {
let id = req.body.id;
let Key = req.body.Key;
let Value = req.body.Value;
let errors = false;
if (!errors) {
var form_data = {
id: id,
Key: Key,
Value: Value,
}
databaseConfig.query('INSERT INTO quydinh SET ?', form_data, function (err, result) {
if (err) {
req.flash('error', err)
res.render('admin/rule/create', {
id: form_data.id,
Key: form_data.Key,
Value: form_data.Value,
user: req.session.user,
layout: 'orther',
})
} else {
req.flash('success', 'add rule successfully added');
res.redirect('/rule-info/');
}
})
}
})
router.get('/edit/(:id)/', function (req, res, next) {
let id = req.params.id;
databaseConfig.query(`SELECT * FROM quydinh where id =` + id, function (err, rows, fields) {
if (err) throw err
if (rows.length <= 0) {
req.flash('error', 'Phong not found with id = ' + id)
res.redirect('/rule-info')
} else {
res.render('admin/rule/edit', {
id: rows[0].id,
Key: rows[0].Key,
Value: rows[0].Value,
user: req.session.user,
layout: 'orther'
})
}
})
})
// Sửa Phòng
router.post('/edit/:id', function (req, res, next) {
let id = req.params.id
let Key = req.body.Key
let Value = req.body.Value
let errors = false
if (!errors) {
var form_data = {
id: id,
Key: Key,
Value: Value,
}
databaseConfig.query('UPDATE quydinh SET ? WHERE id = ' + id, form_data, function (err, result) {
if (err) {
console.log(form_data);
req.flash('error', err)
// render to add.ejs
res.render('admin/rule/edit', {
id: form_data.id,
Key: form_data.Key,
Value: form_data.Value,
user: req.session.user,
layout: 'orther',
})
} else {
req.flash('success', 'Update Product successfully added');
res.redirect('/rule-info/');
}
})
}
})
// //Xoa
// router.get('/delete/:id',function(req,res,next){
// let id = req.params.id;
// databaseConfig.query('DELETE FROM quydinh WHERE id = ' + id, function(err, result) {
// //if(err) throw err
// if (err) {
// // set flash message
// req.flash('error', err);
// // redirect to books page
// res.redirect('/rule-info/');
// } else {
// // set flash message
// req.flash('success', 'Rule successfully deleted! ID = ' + id);
// // redirect to books page
// res.redirect('/rule-info/');
// }
// })
// })
module.exports = router
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'link', 'ru', {
acccessKey: 'Клавиша доступа',
advanced: 'Дополнительно',
advisoryContentType: 'Тип содержимого',
advisoryTitle: 'Заголовок',
anchor: {
toolbar: 'Вставить / редактировать якорь',
menu: 'Изменить якорь',
title: 'Свойства якоря',
name: 'Имя якоря',
errorName: 'Пожалуйста, введите имя якоря',
remove: 'Удалить якорь'
},
anchorId: 'По идентификатору',
anchorName: 'По имени',
charset: 'Кодировка ресурса',
cssClasses: 'Классы CSS',
emailAddress: 'Email адрес',
emailBody: 'Текст сообщения',
emailSubject: 'Тема сообщения',
id: 'Идентификатор',
info: 'Информация о ссылке',
langCode: 'Код языка',
langDir: 'Направление текста',
langDirLTR: 'Слева направо (LTR)',
langDirRTL: 'Справа налево (RTL)',
menu: 'Редактировать ссылку',
name: 'Имя',
noAnchors: '(В документе нет ни одного якоря)',
noEmail: 'Пожалуйста, введите email адрес',
noUrl: 'Пожалуйста, введите ссылку',
other: '<другой>',
popupDependent: 'Зависимое (Netscape)',
popupFeatures: 'Параметры всплывающего окна',
popupFullScreen: 'Полноэкранное (IE)',
popupLeft: 'Отступ слева',
popupLocationBar: 'Панель адреса',
popupMenuBar: 'Панель меню',
popupResizable: 'Изменяемый размер',
popupScrollBars: 'Полосы прокрутки',
popupStatusBar: 'Строка состояния',
popupToolbar: 'Панель инструментов',
popupTop: 'Отступ сверху',
rel: 'Отношение',
selectAnchor: 'Выберите якорь',
styles: 'Стиль',
tabIndex: 'Последовательность перехода',
target: 'Цель',
targetFrame: '<фрейм>',
targetFrameName: 'Имя целевого фрейма',
targetPopup: '<всплывающее окно>',
targetPopupName: 'Имя всплывающего окна',
title: 'Ссылка',
toAnchor: 'Ссылка на якорь в тексте',
toEmail: 'Email',
toUrl: 'Ссылка',
toolbar: 'Вставить/Редактировать ссылку',
type: 'Тип ссылки',
unlink: 'Убрать ссылку',
upload: 'Загрузка'
} );
|
var moment = require("../../moment");
/**************************************************
Traditional Chinese
*************************************************/
exports["lang:zh-tw"] = {
setUp : function (cb) {
moment.lang('zh-tw');
cb();
},
tearDown : function (cb) {
moment.lang('en');
cb();
},
"parse" : function (test) {
test.expect(96);
var tests = '一月 1月_二月 2月_三月 3月_四月 4月_五月 5月_六月 6月_七月 7月_八月 8月_九月 9月_十月 10月_十一月 11月_十二月 12月'.split("_"), i;
function equalTest(input, mmm, i) {
test.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1));
}
for (i = 0; i < 12; i++) {
tests[i] = tests[i].split(' ');
equalTest(tests[i][0], 'MMM', i);
equalTest(tests[i][1], 'MMM', i);
equalTest(tests[i][0], 'MMMM', i);
equalTest(tests[i][1], 'MMMM', i);
equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i);
}
test.done();
},
"format" : function (test) {
test.expect(22);
var a = [
['dddd, MMMM Do YYYY, a h:mm:ss', '星期日, 二月 14日 2010, 下午 3:25:50'],
['ddd, Ah', '週日, 下午3'],
['M Mo MM MMMM MMM', '2 2月 02 二月 2月'],
['YYYY YY', '2010 10'],
['D Do DD', '14 14日 14'],
['d do dddd ddd dd', '0 0日 星期日 週日 日'],
['DDD DDDo DDDD', '45 45日 045'],
['w wo ww', '8 8週 08'],
['h hh', '3 03'],
['H HH', '15 15'],
['m mm', '25 25'],
['s ss', '50 50'],
['a A', '下午 下午'],
['[這年的第] DDDo', '這年的第 45日'],
['L', '2010年2月14日'],
['LL', '2010年2月14日'],
['LLL', '2010年2月14日下午3點25'],
['LLLL', '2010年2月14日星期日下午3點25'],
['l', '2010年2月14日'],
['ll', '2010年2月14日'],
['lll', '2010年2月14日下午3點25'],
['llll', '2010年2月14日星期日下午3點25']
],
b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)),
i;
for (i = 0; i < a.length; i++) {
test.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]);
}
test.done();
},
"format month" : function (test) {
test.expect(12);
var expected = '一月 1月_二月 2月_三月 3月_四月 4月_五月 5月_六月 6月_七月 7月_八月 8月_九月 9月_十月 10月_十一月 11月_十二月 12月'.split("_"), i;
for (i = 0; i < expected.length; i++) {
test.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]);
}
test.done();
},
"format week" : function (test) {
test.expect(7);
var expected = '星期日 週日 日_星期一 週一 一_星期二 週二 二_星期三 週三 三_星期四 週四 四_星期五 週五 五_星期六 週六 六'.split("_"), i;
for (i = 0; i < expected.length; i++) {
test.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]);
}
test.done();
},
"from" : function (test) {
test.expect(30);
var start = moment([2007, 1, 28]);
test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), "幾秒", "44 seconds = a few seconds");
test.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), "一分鐘", "45 seconds = a minute");
test.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), "一分鐘", "89 seconds = a minute");
test.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), "2分鐘", "90 seconds = 2 minutes");
test.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), "44分鐘", "44 minutes = 44 minutes");
test.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), "一小時", "45 minutes = an hour");
test.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), "一小時", "89 minutes = an hour");
test.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), "2小時", "90 minutes = 2 hours");
test.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), "5小時", "5 hours = 5 hours");
test.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), "21小時", "21 hours = 21 hours");
test.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), "一天", "22 hours = a day");
test.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), "一天", "35 hours = a day");
test.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), "2天", "36 hours = 2 days");
test.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), "一天", "1 day = a day");
test.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), "5天", "5 days = 5 days");
test.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), "25天", "25 days = 25 days");
test.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), "一個月", "26 days = a month");
test.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), "一個月", "30 days = a month");
test.equal(start.from(moment([2007, 1, 28]).add({d: 45}), true), "一個月", "45 days = a month");
test.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), "2個月", "46 days = 2 months");
test.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), "2個月", "75 days = 2 months");
test.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), "3個月", "76 days = 3 months");
test.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), "一個月", "1 month = a month");
test.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), "5個月", "5 months = 5 months");
test.equal(start.from(moment([2007, 1, 28]).add({d: 344}), true), "11個月", "344 days = 11 months");
test.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), "一年", "345 days = a year");
test.equal(start.from(moment([2007, 1, 28]).add({d: 547}), true), "一年", "547 days = a year");
test.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), "2年", "548 days = 2 years");
test.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), "一年", "1 year = a year");
test.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), "5年", "5 years = 5 years");
test.done();
},
"suffix" : function (test) {
test.expect(2);
test.equal(moment(30000).from(0), "幾秒內", "prefix");
test.equal(moment(0).from(30000), "幾秒前", "suffix");
test.done();
},
"now from now" : function (test) {
test.expect(1);
test.equal(moment().fromNow(), "幾秒前", "now from now should display as in the past");
test.done();
},
"fromNow" : function (test) {
test.expect(2);
test.equal(moment().add({s: 30}).fromNow(), "幾秒內", "in a few seconds");
test.equal(moment().add({d: 5}).fromNow(), "5天內", "in 5 days");
test.done();
},
"calendar day" : function (test) {
test.expect(6);
var a = moment().hours(2).minutes(0).seconds(0);
test.equal(moment(a).calendar(), "今天早上2點00", "today at the same time");
test.equal(moment(a).add({ m: 25 }).calendar(), "今天早上2點25", "Now plus 25 min");
test.equal(moment(a).add({ h: 1 }).calendar(), "今天早上3點00", "Now plus 1 hour");
test.equal(moment(a).add({ d: 1 }).calendar(), "明天早上2點00", "tomorrow at the same time");
test.equal(moment(a).subtract({ h: 1 }).calendar(), "今天早上1點00", "Now minus 1 hour");
test.equal(moment(a).subtract({ d: 1 }).calendar(), "昨天早上2點00", "yesterday at the same time");
test.done();
},
"calendar next week" : function (test) {
test.expect(15);
var i, m;
for (i = 2; i < 7; i++) {
m = moment().add({ d: i });
test.equal(m.calendar(), m.format('[下]ddddLT'), "Today + " + i + " days current time");
m.hours(0).minutes(0).seconds(0).milliseconds(0);
test.equal(m.calendar(), m.format('[下]ddddLT'), "Today + " + i + " days beginning of day");
m.hours(23).minutes(59).seconds(59).milliseconds(999);
test.equal(m.calendar(), m.format('[下]ddddLT'), "Today + " + i + " days end of day");
}
test.done();
},
"calendar last week" : function (test) {
test.expect(15);
var i, m;
for (i = 2; i < 7; i++) {
m = moment().subtract({ d: i });
test.equal(m.calendar(), m.format('[上]ddddLT'), "Today - " + i + " days current time");
m.hours(0).minutes(0).seconds(0).milliseconds(0);
test.equal(m.calendar(), m.format('[上]ddddLT'), "Today - " + i + " days beginning of day");
m.hours(23).minutes(59).seconds(59).milliseconds(999);
test.equal(m.calendar(), m.format('[上]ddddLT'), "Today - " + i + " days end of day");
}
test.done();
},
"calendar all else" : function (test) {
test.expect(4);
var weeksAgo = moment().subtract({ w: 1 }),
weeksFromNow = moment().add({ w: 1 });
test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "1 week ago");
test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 1 week");
weeksAgo = moment().subtract({ w: 2 });
weeksFromNow = moment().add({ w: 2 });
test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "2 weeks ago");
test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 2 weeks");
test.done();
},
"meridiem" : function (test) {
test.expect(10);
test.equal(moment([2011, 2, 23, 0, 0]).format('a'), "早上", "morning");
test.equal(moment([2011, 2, 23, 9, 0]).format('a'), "上午", "before noon");
test.equal(moment([2011, 2, 23, 12, 0]).format('a'), "中午", "noon");
test.equal(moment([2011, 2, 23, 13, 0]).format('a'), "下午", "after noon");
test.equal(moment([2011, 2, 23, 18, 0]).format('a'), "晚上", "night");
test.equal(moment([2011, 2, 23, 0, 0]).format('A'), "早上", "morning");
test.equal(moment([2011, 2, 23, 9, 0]).format('A'), "上午", "before noon");
test.equal(moment([2011, 2, 23, 12, 0]).format('A'), "中午", "noon");
test.equal(moment([2011, 2, 23, 13, 0]).format('A'), "下午", "afternoon");
test.equal(moment([2011, 2, 23, 18, 0]).format('A'), "晚上", "night");
test.done();
},
// Sunday is the first day of the week.
// The week that contains Jan 1st is the first week of the year.
"weeks year starting sunday" : function (test) {
test.expect(5);
test.equal(moment([2012, 0, 1]).week(), 1, "Jan 1 2012 should be week 1");
test.equal(moment([2012, 0, 7]).week(), 1, "Jan 7 2012 should be week 1");
test.equal(moment([2012, 0, 8]).week(), 2, "Jan 8 2012 should be week 2");
test.equal(moment([2012, 0, 14]).week(), 2, "Jan 14 2012 should be week 2");
test.equal(moment([2012, 0, 15]).week(), 3, "Jan 15 2012 should be week 3");
test.done();
},
"weeks year starting monday" : function (test) {
test.expect(6);
test.equal(moment([2006, 11, 31]).week(), 1, "Dec 31 2006 should be week 1");
test.equal(moment([2007, 0, 1]).week(), 1, "Jan 1 2007 should be week 1");
test.equal(moment([2007, 0, 6]).week(), 1, "Jan 6 2007 should be week 1");
test.equal(moment([2007, 0, 7]).week(), 2, "Jan 7 2007 should be week 2");
test.equal(moment([2007, 0, 13]).week(), 2, "Jan 13 2007 should be week 2");
test.equal(moment([2007, 0, 14]).week(), 3, "Jan 14 2007 should be week 3");
test.done();
},
"weeks year starting tuesday" : function (test) {
test.expect(6);
test.equal(moment([2007, 11, 29]).week(), 52, "Dec 29 2007 should be week 52");
test.equal(moment([2008, 0, 1]).week(), 1, "Jan 1 2008 should be week 1");
test.equal(moment([2008, 0, 5]).week(), 1, "Jan 5 2008 should be week 1");
test.equal(moment([2008, 0, 6]).week(), 2, "Jan 6 2008 should be week 2");
test.equal(moment([2008, 0, 12]).week(), 2, "Jan 12 2008 should be week 2");
test.equal(moment([2008, 0, 13]).week(), 3, "Jan 13 2008 should be week 3");
test.done();
},
"weeks year starting wednesday" : function (test) {
test.expect(6);
test.equal(moment([2002, 11, 29]).week(), 1, "Dec 29 2002 should be week 1");
test.equal(moment([2003, 0, 1]).week(), 1, "Jan 1 2003 should be week 1");
test.equal(moment([2003, 0, 4]).week(), 1, "Jan 4 2003 should be week 1");
test.equal(moment([2003, 0, 5]).week(), 2, "Jan 5 2003 should be week 2");
test.equal(moment([2003, 0, 11]).week(), 2, "Jan 11 2003 should be week 2");
test.equal(moment([2003, 0, 12]).week(), 3, "Jan 12 2003 should be week 3");
test.done();
},
"weeks year starting thursday" : function (test) {
test.expect(6);
test.equal(moment([2008, 11, 28]).week(), 1, "Dec 28 2008 should be week 1");
test.equal(moment([2009, 0, 1]).week(), 1, "Jan 1 2009 should be week 1");
test.equal(moment([2009, 0, 3]).week(), 1, "Jan 3 2009 should be week 1");
test.equal(moment([2009, 0, 4]).week(), 2, "Jan 4 2009 should be week 2");
test.equal(moment([2009, 0, 10]).week(), 2, "Jan 10 2009 should be week 2");
test.equal(moment([2009, 0, 11]).week(), 3, "Jan 11 2009 should be week 3");
test.done();
},
"weeks year starting friday" : function (test) {
test.expect(6);
test.equal(moment([2009, 11, 27]).week(), 1, "Dec 27 2009 should be week 1");
test.equal(moment([2010, 0, 1]).week(), 1, "Jan 1 2010 should be week 1");
test.equal(moment([2010, 0, 2]).week(), 1, "Jan 2 2010 should be week 1");
test.equal(moment([2010, 0, 3]).week(), 2, "Jan 3 2010 should be week 2");
test.equal(moment([2010, 0, 9]).week(), 2, "Jan 9 2010 should be week 2");
test.equal(moment([2010, 0, 10]).week(), 3, "Jan 10 2010 should be week 3");
test.done();
},
"weeks year starting saturday" : function (test) {
test.expect(5);
test.equal(moment([2010, 11, 26]).week(), 1, "Dec 26 2010 should be week 1");
test.equal(moment([2011, 0, 1]).week(), 1, "Jan 1 2011 should be week 1");
test.equal(moment([2011, 0, 2]).week(), 2, "Jan 2 2011 should be week 2");
test.equal(moment([2011, 0, 8]).week(), 2, "Jan 8 2011 should be week 2");
test.equal(moment([2011, 0, 9]).week(), 3, "Jan 9 2011 should be week 3");
test.done();
},
"weeks year starting sunday format" : function (test) {
test.expect(5);
test.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1週', "Jan 1 2012 應該是第 1週");
test.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1週', "Jan 7 2012 應該是第 1週");
test.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2週', "Jan 8 2012 應該是第 2週");
test.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2週', "Jan 14 2012 應該是第 2週");
test.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3週', "Jan 15 2012 應該是第 3週");
test.done();
},
"returns the name of the language" : function (test) {
if (typeof module !== 'undefined' && module.exports) {
test.equal(require('../../lang/zh-tw'), 'zh-tw', "module should export zh-tw");
}
test.done();
}
};
|
"use strict";
var assign = require('object-assign');
var projectHeader = 'X-Sanity-Project-ID';
module.exports = function (config) {
var overrides = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var headers = {};
var token = overrides.token || config.token;
if (token) {
headers.Authorization = "Bearer ".concat(token);
}
if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {
headers[projectHeader] = config.projectId;
}
var withCredentials = Boolean(typeof overrides.withCredentials === 'undefined' ? config.token || config.withCredentials : overrides.withCredentials);
var timeout = typeof overrides.timeout === 'undefined' ? config.timeout : overrides.timeout;
return assign({}, overrides, {
headers: assign({}, headers, overrides.headers || {}),
timeout: typeof timeout === 'undefined' ? 5 * 60 * 1000 : timeout,
json: true,
withCredentials: withCredentials
});
};
|
const path = require('path');
module.exports = {
stories: ['../getting-started/*.story.(js|mdx)', '../packages/**/*.story.(js|mdx)'],
addons: [
{
name: '@storybook/addon-storysource',
options: {
rule: {
test: [/\.story\.(js)?$/],
include: [path.resolve(__dirname, '../packages')],
},
loaderOptions: {
prettierConfig: { printWidth: 80, singleQuote: false },
},
},
},
'@storybook/addon-docs',
'@storybook/addon-viewport/register',
],
webpackFinal: async (config) => {
config.devtool = 'inline-source-map';
config.resolve = {
alias: {
'@rainbow-modules/app': path.join(__dirname, '../packages/app/src/index.js'),
'@rainbow-modules/auth': path.join(__dirname, '../packages/auth/src/index.js'),
'@rainbow-modules/dashboard': path.join(
__dirname,
'../packages/dashboard/src/index.js',
),
'@rainbow-modules/icons': path.join(__dirname, '../packages/icons/src/index.js'),
'@rainbow-modules/firebase-hooks': path.join(
__dirname,
'../packages/firebase-hooks/src/index.js',
),
'@rainbow-modules/forms': path.join(__dirname, '../packages/forms/src/index.js'),
'@rainbow-modules/hooks': path.join(__dirname, '../packages/hooks/src/index.js'),
'@rainbow-modules/listview': path.join(
__dirname,
'../packages/listview/src/index.js',
),
'@rainbow-modules/storage': path.join(
__dirname,
'../packages/storage/src/index.js',
),
'@rainbow-modules/validation': path.join(
__dirname,
'../packages/validation/src/index.js',
),
'@rainbow-modules/payment': path.join(
__dirname,
'../packages/payment/src/index.js',
),
'@rainbow-modules/record': path.join(__dirname, '../packages/record/src/index.js'),
},
};
return config;
},
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core = require("@actions/core");
const AWS = require("aws-sdk");
const format_1 = require("./format");
const fs_1 = require("fs");
async function run() {
const region = process.env.AWS_DEFAULT_REGION;
const ssm = new AWS.SSM({ region });
try {
const ssmPath = core.getInput('ssm-path', { required: true });
const format = core.getInput('format', { required: true });
const output = core.getInput('output', { required: true });
const append = core.getInput('append');
const prefix = core.getInput('prefix');
const allParameters = [];
const withDecryption = core.getInput('decryption') === 'true';
let nextToken;
try {
do {
const result = await ssm
.getParametersByPath({
WithDecryption: withDecryption,
Path: ssmPath,
Recursive: true,
NextToken: nextToken,
})
.promise();
core.debug(`parameters length: ${result.Parameters.length}`);
nextToken = result.NextToken;
allParameters.push(...result.Parameters);
} while (nextToken);
const envs = allParameters
.map(p => ({
Value: p.Value,
Name: p.Name.split('/').pop(),
}))
.map(format_1.formatter(format)(prefix));
if (envs.length > 0) {
envs.push('\n');
}
if (fs_1.existsSync(output) && append) {
console.log(`append to ${output} file`);
fs_1.appendFileSync(output, '\n' + envs.join('\n'));
}
else {
console.log(`create ${output} file`);
fs_1.writeFileSync(output, envs.join('\n'));
}
}
catch (e) {
core.error(e);
core.setFailed(e.message);
}
}
catch (e) {
core.setFailed(e.message);
}
}
run();
|
var util = require('util')
var errors = {
100: 'CommonInvalidParam1',
101: 'CommonInvalidParam2',
102: 'CommonInvalidParam3',
103: 'CommonInvalidParam4',
104: 'CommonInvalidParam5',
105: 'CommonInvalidParam6',
106: 'CommonInvalidParam7',
107: 'CommonInvalidParam8',
108: 'CommonInvalidParam9',
109: 'CommonInvalidParam10',
110: 'CommonInvalidParam11',
111: 'CommonInvalidParam12',
112: 'CommonInvalidState',
113: 'CommonInvalidStructure',
114: 'CommonIOError',
200: 'WalletInvalidHandle',
201: 'WalletUnknownTypeError',
202: 'WalletTypeAlreadyRegisteredError',
203: 'WalletAlreadyExistsError',
204: 'WalletNotFoundError',
205: 'WalletIncompatiblePoolError',
206: 'WalletAlreadyOpenedError',
207: 'WalletAccessFailed',
300: 'PoolLedgerNotCreatedError',
301: 'PoolLedgerInvalidPoolHandle',
302: 'PoolLedgerTerminated',
303: 'LedgerNoConsensusError',
304: 'LedgerInvalidTransaction',
305: 'LedgerSecurityError',
306: 'PoolLedgerConfigAlreadyExistsError',
307: 'PoolLedgerTimeout',
308: 'PoolIncompatibleProtocolVersion',
400: 'AnoncredsRevocationRegistryFullError',
401: 'AnoncredsInvalidUserRevocId',
404: 'AnoncredsMasterSecretDuplicateNameError',
405: 'AnoncredsProofRejected',
406: 'AnoncredsCredentialRevoked',
407: 'AnoncredsCredDefAlreadyExistsError',
500: 'UnknownCryptoTypeError',
600: 'DidAlreadyExistsError',
700: 'PaymentUnknownMethodError',
701: 'PaymentIncompatibleMethodsError',
702: 'PaymentInsufficientFundsError',
703: 'PaymentSourceDoesNotExistError',
704: 'PaymentOperationNotSupportedError'
}
function IndyError (err) {
Error.call(this)
Error.captureStackTrace(this, this.constructor)
this.name = this.constructor.name
if (errors.hasOwnProperty(err)) {
this.message = errors[err]
this.indyCode = err
this.indyName = errors[err]
} else {
this.message = (err + '')
}
}
util.inherits(IndyError, Error)
module.exports = IndyError
|
const jwt = require("jsonwebtoken");
const secret = "mysecretsshhhhh";
const expiration = "2h";
module.exports = {
authMiddleware: function ({ req }) {
// allows token to be sent via req.body, req.query, or headers
let token = req.body.token || req.query.token || req.headers.authorization;
// ["Bearer", "<tokenvalue>"]
if (req.headers.authorization) {
token = token.split(" ").pop().trim();
}
if (!token) {
return req;
}
try {
const { data } = jwt.verify(token, secret, { maxAge: expiration });
req.user = data;
} catch {
console.log("Invalid token");
}
return req;
},
signToken: function ({ username, email, _id }) {
const payload = { username, email, _id };
return jwt.sign({ data: payload }, secret, { expiresIn: expiration });
},
};
|
"use strict";
var tslib_1 = require("tslib");
var React = require("react");
var Chat_1 = require("./Chat");
var react_redux_1 = require("react-redux");
var ShellContainer = (function (_super) {
tslib_1.__extends(ShellContainer, _super);
function ShellContainer(props) {
return _super.call(this, props) || this;
}
ShellContainer.prototype.sendMessage = function () {
Chat_1.sendMessage(this.props.dispatch, this.props.inputText, this.props.user, this.props.format.locale);
};
ShellContainer.prototype.onChangeText = function () {
this.props.dispatch({ type: 'Update_Input', input: this.textInput.value });
};
ShellContainer.prototype.onKeyPress = function (e) {
if (e.key === 'Enter')
this.sendMessage();
};
ShellContainer.prototype.onClickSend = function () {
this.textInput.focus();
this.sendMessage();
};
ShellContainer.prototype.onChangeFile = function () {
this.textInput.focus();
Chat_1.sendFiles(this.props.dispatch, this.fileInput.files, this.props.user, this.props.format.locale);
this.fileInput.value = null;
};
ShellContainer.prototype.render = function () {
var _this = this;
var className = 'wc-console';
if (this.props.inputText.length > 0)
className += ' has-text';
return (React.createElement("div", { className: className },
React.createElement("input", { id: "wc-upload-input", type: "file", ref: function (input) { return _this.fileInput = input; }, multiple: true, onChange: function () { return _this.onChangeFile(); } }),
React.createElement("label", { className: "wc-upload", htmlFor: "wc-upload-input" },
React.createElement("svg", { width: "26", height: "18" },
React.createElement("path", { d: "M 19.9603965 4.789052 m -2 0 a 2 2 0 0 1 4 0 a 2 2 0 0 1 -4 0 z M 8.3168322 4.1917918 L 2.49505 15.5342575 L 22.455446 15.5342575 L 17.465347 8.5643945 L 14.4158421 11.1780931 L 8.3168322 4.1917918 Z M 1.04 1 L 1.04 17 L 24.96 17 L 24.96 1 L 1.04 1 Z M 1.0352753 0 L 24.9647247 0 C 25.5364915 0 26 0.444957 26 0.9934084 L 26 17.006613 C 26 17.5552514 25.5265266 18 24.9647247 18 L 1.0352753 18 C 0.4635085 18 0 17.5550644 0 17.006613 L 0 0.9934084 C 0 0.44477 0.4734734 0 1.0352753 0 Z" }))),
React.createElement("div", { className: "wc-textbox" },
React.createElement("input", { type: "text", ref: function (input) { return _this.textInput = input; }, autoFocus: true, value: this.props.inputText, onChange: function () { return _this.onChangeText(); }, onKeyPress: function (e) { return _this.onKeyPress(e); }, placeholder: this.props.format.strings.consolePlaceholder })),
React.createElement("label", { className: "wc-send", onClick: function () { return _this.onClickSend(); } },
React.createElement("svg", { width: "27", height: "18" },
React.createElement("path", { d: "M 26.7862876 9.3774996 A 0.3121028 0.3121028 0 0 0 26.7862876 8.785123 L 0.4081408 0.0226012 C 0.363153 0.0000109 0.3406591 0.0000109 0.3181652 0.0000109 C 0.1372585 0.0000109 0 0.1315165 0 0.2887646 C 0 0.3270384 0.0081316 0.3668374 0.0257445 0.4066363 L 3.4448168 9.0813113 L 0.0257445 17.7556097 A 0.288143 0.288143 0 0 0 0.0126457 17.7975417 A 0.279813 0.279813 0 0 0 0.0055133 17.8603089 C 0.0055133 18.0178895 0.138422 18.1590562 0.303205 18.1590562 A 0.3049569 0.3049569 0 0 0 0.4081408 18.1400213 L 26.7862876 9.3774996 Z M 0.8130309 0.7906714 L 24.8365128 8.7876374 L 3.9846704 8.7876374 L 0.8130309 0.7906714 Z M 3.9846704 9.3749852 L 24.8365128 9.3749852 L 0.8130309 17.3719511 L 3.9846704 9.3749852 Z" })))));
};
return ShellContainer;
}(React.Component));
exports.Shell = react_redux_1.connect(function (state) { return ({
inputText: state.shell.input,
format: state.format,
user: state.connection.user,
}); })(ShellContainer);
//# sourceMappingURL=Shell.js.map
|
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './public'),
publicPath: '/',
filename: 'js/build.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
},
{
test: /\.scss$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
],
},
{
test: /\.sass$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader?indentedSyntax'
],
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this necessary.
'scss': [
'vue-style-loader',
'css-loader',
'sass-loader'
],
'sass': [
'vue-style-loader',
'css-loader',
'sass-loader?indentedSyntax'
]
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}]
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
|
/* Copyright (c) 2012-2013 LevelUP contributors
* See list at <https://github.com/rvagg/node-levelup#contributing>
* MIT +no-false-attribs License <https://github.com/rvagg/node-levelup/blob/master/LICENSE>
*/
/*
* This test unpacks a tar file, pushes that data into a
* database then compares the database data with the files
* on the filesystem.
* The different types of data are useful for testing, particularly
* the binary files.
*/
var async = require('async')
, rimraf = require('rimraf')
, tarcommon = require('./tarcommon')
console.log('***************************************************')
console.log('RUNNING BINARY-DATA-TEST...')
async.series([
// pre-clean
rimraf.bind(null, tarcommon.dblocation)
, rimraf.bind(null, tarcommon.datadir)
// extract data for comparison
, tarcommon.extract.bind(null, tarcommon.datatar, tarcommon.datadir)
// open database
, tarcommon.opendb.bind(null, tarcommon.dblocation)
// push the data into a database
, tarcommon.fstreamWrite
// run a sync put & del to force an fs sync
, tarcommon.sync
// verify database entries are the same as the files
, tarcommon.verify
// clean up
, rimraf.bind(null, tarcommon.dblocation)
, rimraf.bind(null, tarcommon.datadir)
], function (err) {
if (err) console.error('Error', err)
else console.log('No errors? All good then!')
console.log('***************************************************')
process.exit(err ? -1 : 0)
})
|
import React from "react";
import { Provider } from "react-redux";
import "react-native-gesture-handler";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from '@react-navigation/stack';
import { configureStore, createReducer, combineReducers } from "@reduxjs/toolkit";
import { screens } from "@screens";
import { hooks, slices, navigators, initialRoute } from "@modules";
import { connectors } from "@store";
const Stack = createStackNavigator();
const getNavigation = (modules, screens, initialRoute) => {
const Navigation = () => {
const routes = modules.concat(screens).map(([name, navigator]) => {
return (
<Stack.Screen key={name} name={name} component={navigator} screenOptions={ { headerShown: false } } />
)
});
return (
<NavigationContainer>
<Stack.Navigator initialRouteName={initialRoute}>
{routes}
</Stack.Navigator>
</NavigationContainer>
)
}
return Navigation;
}
const getStore = slices => {
const reducers = Object.fromEntries(slices.map(([name, slice]) => [name, slice.reducer]));
const appState = {
name: "percy_28572Identifier",
url: "https://percy_28572Identifier.botics.co",
version: "1.0.0"
}
const appReducer = createReducer(appState, _ => {
return appState;
})
const reducer = combineReducers({
app: appReducer,
...reducers
});
return configureStore({
reducer: reducer,
middleware: (getDefaultMiddleware) => getDefaultMiddleware()
});
}
const App = () => {
const Navigation = getNavigation(navigators, screens, initialRoute);
const store = getStore([...slices, ...connectors]);
let effects = {};
hooks.map(([_, hook]) => {
effects[hook.name] = hook();
});
return (
<Provider store={store}>
<Navigation />
</Provider>
);
};
export default App;
|
window.jsb = window.jsb || {};
jsb.onWindowResize = function (callBack) {
console.warn('jsb.onWindowResize not supported');
};
// 屏蔽废弃的函数
window.resize = function () {};
|
/*
const useWindowSize = () => {
const getSize = () => {
return {
width: isClient ? window.innerWidth : undefined,
height: isClient ? window.innerHeight : undefined,
}
}
const [windowSize, setWindowSize] = useState(getSize)
useEffect(() => {
if (!isClient) {
return false
}
const handleResize = () => {
setWindowSize(getSize())
}
document.addEventListener('resize', handleResize)
return () => document.removeEventListener('resize', handleResize)
}, [])
return windowSize
}
*/
import { useEffect, useState } from 'react'
// Хук для отслеживания ширины экрана при ресайзе
const isClient = typeof window === 'object'
const useWindowSize = () => {
const [width, setWidth] = useState(isClient ? window.innerWidth : undefined)
useEffect(() => {
if (!isClient) {
return false
}
const handleResize = () => setTimeout(() => setWidth(window.innerWidth), 1000)
window.addEventListener('resize', handleResize)
return () => window.removeEventListener('resize', handleResize)
}, [])
return width
}
export default useWindowSize
|
// services/network/public/mojom/cors.mojom.js is auto generated by mojom_bindings_generator.py, do not edit
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
(function() {
var mojomId = 'services/network/public/mojom/cors.mojom';
if (mojo.internal.isMojomLoaded(mojomId)) {
console.warn('The following mojom is loaded multiple times: ' + mojomId);
return;
}
mojo.internal.markMojomLoaded(mojomId);
var bindings = mojo;
var associatedBindings = mojo;
var codec = mojo.internal;
var validator = mojo.internal;
var exports = mojo.internal.exposeNamespace('network.mojom');
var CorsPreflightPolicy = {};
CorsPreflightPolicy.kConsiderPreflight = 0;
CorsPreflightPolicy.kPreventPreflight = 1;
CorsPreflightPolicy.MIN_VALUE = 0;
CorsPreflightPolicy.MAX_VALUE = 1;
CorsPreflightPolicy.isKnownEnumValue = function(value) {
switch (value) {
case 0:
case 1:
return true;
}
return false;
};
CorsPreflightPolicy.toKnownEnumValue = function(value) {
return value;
};
CorsPreflightPolicy.validate = function(enumValue) {
const isExtensible = false;
if (isExtensible || this.isKnownEnumValue(enumValue))
return validator.validationError.NONE;
return validator.validationError.UNKNOWN_ENUM_VALUE;
};
var CorsError = {};
CorsError.kDisallowedByMode = 0;
CorsError.kInvalidResponse = 1;
CorsError.kWildcardOriginNotAllowed = 2;
CorsError.kMissingAllowOriginHeader = 3;
CorsError.kMultipleAllowOriginValues = 4;
CorsError.kInvalidAllowOriginValue = 5;
CorsError.kAllowOriginMismatch = 6;
CorsError.kInvalidAllowCredentials = 7;
CorsError.kCorsDisabledScheme = 8;
CorsError.kPreflightInvalidStatus = 9;
CorsError.kPreflightDisallowedRedirect = 10;
CorsError.kPreflightWildcardOriginNotAllowed = 11;
CorsError.kPreflightMissingAllowOriginHeader = 12;
CorsError.kPreflightMultipleAllowOriginValues = 13;
CorsError.kPreflightInvalidAllowOriginValue = 14;
CorsError.kPreflightAllowOriginMismatch = 15;
CorsError.kPreflightInvalidAllowCredentials = 16;
CorsError.kPreflightMissingAllowExternal = 17;
CorsError.kPreflightInvalidAllowExternal = 18;
CorsError.kInvalidAllowMethodsPreflightResponse = 19;
CorsError.kInvalidAllowHeadersPreflightResponse = 20;
CorsError.kMethodDisallowedByPreflightResponse = 21;
CorsError.kHeaderDisallowedByPreflightResponse = 22;
CorsError.kRedirectContainsCredentials = 23;
CorsError.kInsecurePrivateNetwork = 24;
CorsError.MIN_VALUE = 0;
CorsError.MAX_VALUE = 24;
CorsError.isKnownEnumValue = function(value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 20:
case 21:
case 22:
case 23:
case 24:
return true;
}
return false;
};
CorsError.toKnownEnumValue = function(value) {
return value;
};
CorsError.validate = function(enumValue) {
const isExtensible = false;
if (isExtensible || this.isKnownEnumValue(enumValue))
return validator.validationError.NONE;
return validator.validationError.UNKNOWN_ENUM_VALUE;
};
function CorsErrorStatus(values) {
this.initDefaults_();
this.initFields_(values);
}
CorsErrorStatus.prototype.initDefaults_ = function() {
};
CorsErrorStatus.prototype.initFields_ = function(fields) {
for(var field in fields) {
if (this.hasOwnProperty(field))
this[field] = fields[field];
}
};
CorsErrorStatus.validate = function(messageValidator, offset) {
var err;
err = messageValidator.validateStructHeader(offset, codec.kStructHeaderSize);
if (err !== validator.validationError.NONE)
return err;
var kVersionSizes = [
{version: 0, numBytes: 8}
];
err = messageValidator.validateStructVersion(offset, kVersionSizes);
if (err !== validator.validationError.NONE)
return err;
return validator.validationError.NONE;
};
CorsErrorStatus.encodedSize = codec.kStructHeaderSize + 0;
CorsErrorStatus.decode = function(decoder) {
var packed;
var val = new CorsErrorStatus();
var numberOfBytes = decoder.readUint32();
var version = decoder.readUint32();
return val;
};
CorsErrorStatus.encode = function(encoder, val) {
var packed;
encoder.writeUint32(CorsErrorStatus.encodedSize);
encoder.writeUint32(0);
};
exports.CorsPreflightPolicy = CorsPreflightPolicy;
exports.CorsError = CorsError;
exports.CorsErrorStatus = CorsErrorStatus;
})();
|
// Private property declaration in es6 class
class Sample {
#property;
constructor() {
this.#property = "Sample Property";
console.log(this.#property); // Output:: Sample Property
}
}
const instance = new Sample();
console.log(instance.property); // Output:: undefined
console.log(instance.#property) // Uncaught SyntaxError: Private field '#property' must be declared in an enclosing class
|
export default {"name":"--pf-c-wizard__description--Color","value":"#ededed","var":"var(--pf-c-wizard__description--Color)"}
|
/**
* 我们有两个长度相等且不为空的整型数组 A 和 B 。
我们可以交换 A[i] 和 B[i] 的元素。注意这两个元素在各自的序列中应该处于相同的位置。
在交换过一些元素之后,数组 A 和 B 都应该是严格递增的(数组严格递增的条件仅为A[0] < A[1] < A[2] < ... < A[A.length - 1])。
给定数组 A 和 B ,请返回使得两个数组均保持严格递增状态的最小交换次数。假设给定的输入总是有效的。
示例:
输入: A = [1,3,5,4], B = [1,2,3,7]
输出: 1
解释:
交换 A[3] 和 B[3] 后,两个数组如下:
A = [1, 3, 5, 7] , B = [1, 2, 3, 4]
两个数组均为严格递增的。
注意:
A, B 两个数组的长度总是相等的,且长度的范围为 [1, 1000]。
A[i], B[i] 均为 [0, 2000]区间内的整数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-swaps-to-make-sequences-increasing
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @param {number[]} A
* @param {number[]} B
* @return {number}
*/
var minSwap = function (A, B) {
const len = A.length;
const dp = new Array(len).fill().map(() => []);
dp[0][0] = 0;
dp[0][1] = 1;
for (let i = 1; i < len; i++) {
const a1 = A[i - 1];
const a2 = A[i];
const b1 = B[i - 1];
const b2 = B[i];
// 序列正常
if (a1 < a2 && b1 < b2) {
// 前后两位置都可以互换
if (a1 < b2 && b1 < a2) {
dp[i][0] = Math.min(dp[i - 1][0], dp[i - 1][1]);
dp[i][1] = Math.min(dp[i - 1][0], dp[i - 1][1]) + 1;
} else {
// 前后两位置需要一起换
dp[i][0] = dp[i - 1][0];
dp[i][1] = dp[i - 1][1] + 1;
}
} else {
// 前个位置交换 OR 当前位置交互
dp[i][0] = dp[i - 1][1];
dp[i][1] = dp[i - 1][0] + 1;
}
}
return Math.min(dp[len - 1][0], dp[len - 1][1]);
};
console.log(minSwap([0, 4, 4, 5, 9], [0, 1, 6, 8, 10]));
// console.log(minSwap([0, 4, 4], [0, 1, 6]));
|
class HtmlWebpackUltraPlugin {
constructor(options) {
this.options = Object.assign({}, options)
}
apply (compiler) {
const me = this
compiler.hooks.emit.tap('HtmlWebpackUltraPlugin', (compilation) => {
if (typeof this.options.modifier !== 'function') {
return
}
const files = Object.keys(compilation.assets)
const htmlReg = /\.html$/
files.map((name) => {
if (htmlReg.test(name)) {
let asset = compilation.assets[name]
let html = asset.source()
html = me.options.modifier(html, name)
asset.source = () => html
asset.size = () => html.length
}
})
})
}
}
module.exports = HtmlWebpackUltraPlugin
|
import React from "react";
import { documentToReactComponents } from "@contentful/rich-text-react-renderer";
import { INLINES } from "@contentful/rich-text-types";
const options = {
renderNode: {
[INLINES.HYPERLINK]: node => {
return (
<a href={node.data.uri} target="_blank" rel="noopener noreferrer">
{node.content[0].value}
</a>
);
}
}
};
export default function renderRichText(raw) {
return documentToReactComponents(JSON.parse(raw), options);
}
|
jest.mock('fs')
jest.mock('/vue.config.js', () => ({ lintOnSave: false }), { virtual: true })
jest.mock('vue-cli-plugin-foo', () => () => {}, { virtual: true })
const fs = require('fs')
const path = require('path')
const Service = require('../lib/Service')
const mockPkg = json => {
fs.writeFileSync('/package.json', JSON.stringify(json, null, 2))
}
const createMockService = (plugins = [], init = true, mode) => {
const service = new Service('/', {
plugins,
useBuiltIn: false
})
if (init) {
service.init(mode)
}
return service
}
beforeEach(() => {
mockPkg({})
delete process.env.NODE_ENV
delete process.env.BABEL_ENV
delete process.env.FOO
delete process.env.BAR
delete process.env.BAZ
})
test('env loading', () => {
process.env.FOO = 0
fs.writeFileSync('/.env.local', `FOO=1\nBAR=2`)
fs.writeFileSync('/.env', `BAR=3\nBAZ=4`)
createMockService()
expect(process.env.FOO).toBe('0')
expect(process.env.BAR).toBe('2')
expect(process.env.BAZ).toBe('4')
fs.unlinkSync('/.env.local')
fs.unlinkSync('/.env')
})
test('env loading for custom mode', () => {
process.env.VUE_CLI_TEST_TESTING_ENV = true
fs.writeFileSync('/.env', 'FOO=1')
fs.writeFileSync('/.env.staging', 'FOO=2\nNODE_ENV=production')
createMockService([], true, 'staging')
expect(process.env.FOO).toBe('2')
expect(process.env.NODE_ENV).toBe('production')
process.env.VUE_CLI_TEST_TESTING_ENV = false
fs.unlinkSync('/.env')
fs.unlinkSync('/.env.staging')
})
test('loading plugins from package.json', () => {
mockPkg({
devDependencies: {
'bar': '^1.0.0',
'@vue/cli-plugin-babel': '^4.0.0-rc.0',
'vue-cli-plugin-foo': '^1.0.0'
}
})
const service = new Service('/') // this one needs to read from package.json
expect(service.plugins.some(({ id }) => id === '@vue/cli-plugin-babel')).toBe(true)
expect(service.plugins.some(({ id }) => id === 'vue-cli-plugin-foo')).toBe(true)
expect(service.plugins.some(({ id }) => id === 'bar')).toBe(false)
})
test('load project options from package.json', () => {
mockPkg({
vue: {
lintOnSave: 'default'
}
})
const service = createMockService()
expect(service.projectOptions.lintOnSave).toBe('default')
})
test('handle option publicPath and outputDir correctly', () => {
mockPkg({
vue: {
publicPath: 'https://foo.com/bar',
outputDir: '/public/'
}
})
const service = createMockService()
expect(service.projectOptions.publicPath).toBe('https://foo.com/bar/')
expect(service.projectOptions.outputDir).toBe('/public')
})
test('normalize publicPath when relative', () => {
mockPkg({
vue: {
publicPath: './foo/bar'
}
})
const service = createMockService()
expect(service.projectOptions.publicPath).toBe('foo/bar/')
})
test('keep publicPath when empty', () => {
mockPkg({
vue: {
publicPath: ''
}
})
const service = createMockService()
expect(service.projectOptions.publicPath).toBe('')
})
test('load project options from vue.config.js', () => {
process.env.VUE_CLI_SERVICE_CONFIG_PATH = `/vue.config.js`
fs.writeFileSync('/vue.config.js', `module.exports = { lintOnSave: false }`)
mockPkg({
vue: {
lintOnSave: 'default'
}
})
const service = createMockService()
fs.unlinkSync('/vue.config.js')
delete process.env.VUE_CLI_SERVICE_CONFIG_PATH
// vue.config.js has higher priority
expect(service.projectOptions.lintOnSave).toBe(false)
})
test('load project options from vue.config.js', () => {
process.env.VUE_CLI_SERVICE_CONFIG_PATH = `/vue.config.js`
fs.writeFileSync('/vue.config.js', '') // only to ensure fs.existsSync returns true
jest.mock('/vue.config.js', () => function () { return { lintOnSave: false } }, { virtual: true })
mockPkg({
vue: {
lintOnSave: 'default'
}
})
const service = createMockService()
fs.unlinkSync('/vue.config.js')
delete process.env.VUE_CLI_SERVICE_CONFIG_PATH
// vue.config.js has higher priority
expect(service.projectOptions.lintOnSave).toBe(false)
})
test('api: assertVersion', () => {
const plugin = {
id: 'test-assertVersion',
apply: api => {
expect(() => api.assertVersion(4)).not.toThrow()
expect(() => api.assertVersion('^4.0.0-0')).not.toThrow()
// expect(() => api.assertVersion('>= 4')).not.toThrow()
expect(() => api.assertVersion(4.1)).toThrow('Expected string or integer value')
expect(() => api.assertVersion('^100')).toThrow('Require @vue/cli-service "^100"')
}
}
createMockService([plugin], true /* init */)
})
test('api: registerCommand', () => {
let args
const service = createMockService([{
id: 'test',
apply: api => {
api.registerCommand('foo', _args => {
args = _args
})
}
}])
service.run('foo', { n: 1 })
expect(args).toEqual({ _: [], n: 1 })
})
test('api: --skip-plugins', () => {
let untouched = true
const service = createMockService([{
id: 'test-command',
apply: api => {
api.registerCommand('foo', _args => {
return
})
}
},
{
id: 'vue-cli-plugin-test-plugin',
apply: api => {
untouched = false
}
}], false)
service.run('foo', { 'skip-plugins': 'test-plugin' })
expect(untouched).toEqual(true)
})
test('api: defaultModes', () => {
fs.writeFileSync('/.env.foo', `FOO=5\nBAR=6`)
fs.writeFileSync('/.env.foo.local', `FOO=7\nBAZ=8`)
const plugin1 = {
id: 'test-defaultModes',
apply: api => {
expect(process.env.FOO).toBe('7')
expect(process.env.BAR).toBe('6')
expect(process.env.BAZ).toBe('8')
// for NODE_ENV & BABEL_ENV
// any mode that is not test or production defaults to development
expect(process.env.NODE_ENV).toBe('development')
expect(process.env.BABEL_ENV).toBe('development')
api.registerCommand('foo', () => {})
}
}
plugin1.apply.defaultModes = {
foo: 'foo'
}
createMockService([plugin1], false /* init */).run('foo')
delete process.env.NODE_ENV
delete process.env.BABEL_ENV
const plugin2 = {
id: 'test-defaultModes',
apply: api => {
expect(process.env.NODE_ENV).toBe('test')
expect(process.env.BABEL_ENV).toBe('test')
api.registerCommand('test', () => {})
}
}
plugin2.apply.defaultModes = {
test: 'test'
}
createMockService([plugin2], false /* init */).run('test')
})
test('api: chainWebpack', () => {
const service = createMockService([{
id: 'test',
apply: api => {
api.chainWebpack(config => {
config.output.path('test-dist')
})
}
}])
const config = service.resolveWebpackConfig()
expect(config.output.path).toBe('test-dist')
})
test('api: configureWebpack', () => {
const service = createMockService([{
id: 'test',
apply: api => {
api.configureWebpack(config => {
config.output = {
path: 'test-dist-2'
}
})
}
}])
const config = service.resolveWebpackConfig()
expect(config.output.path).toBe('test-dist-2')
})
test('api: configureWebpack returning object', () => {
const service = createMockService([{
id: 'test',
apply: api => {
api.configureWebpack(config => {
return {
output: {
path: 'test-dist-3'
}
}
})
}
}])
const config = service.resolveWebpackConfig()
expect(config.output.path).toBe('test-dist-3')
})
test('api: configureWebpack preserve ruleNames', () => {
const service = createMockService([
{
id: 'babel',
apply: require('@vue/cli-plugin-babel')
},
{
id: 'test',
apply: api => {
api.configureWebpack({
module: {
rules: []
}
})
}
}
])
const config = service.resolveWebpackConfig()
expect(config.module.rules[0].__ruleNames).toEqual(['js'])
})
test('internal: should correctly set VUE_CLI_ENTRY_FILES', () => {
const service = createMockService([{
id: 'test',
apply: api => {
api.configureWebpack(config => {
config.entry = {
page1: './src/page1.js',
page2: './src/page2.js'
}
})
}
}])
service.resolveWebpackConfig()
expect(process.env.VUE_CLI_ENTRY_FILES).toEqual(
JSON.stringify([
path.resolve('/', './src/page1.js'),
path.resolve('/', './src/page2.js')
])
)
})
test('api: configureDevServer', () => {
const cb = () => {}
const service = createMockService([{
id: 'test',
apply: api => {
api.configureDevServer(cb)
}
}])
expect(service.devServerConfigFns).toContain(cb)
})
test('api: resolve', () => {
createMockService([{
id: 'test',
apply: api => {
expect(api.resolve('foo.js')).toBe(path.resolve('/', 'foo.js'))
}
}])
})
test('api: hasPlugin', () => {
createMockService([
{
id: 'vue-cli-plugin-foo',
apply: api => {
expect(api.hasPlugin('bar')).toBe(true)
expect(api.hasPlugin('@vue/cli-plugin-bar')).toBe(true)
}
},
{
id: '@vue/cli-plugin-bar',
apply: api => {
expect(api.hasPlugin('foo')).toBe(true)
expect(api.hasPlugin('vue-cli-plugin-foo')).toBe(true)
}
}
])
})
|
module.exports = {
// Specifies the ESLint parser
parser: '@typescript-eslint/parser',
// Which files to not lint
ignorePatterns: ['webpack*', 'dist*'],
parserOptions: {
// Allows for the parsing of modern ECMAScript features
ecmaVersion: 2020,
// Allows for the use of imports
sourceType: 'module',
},
// The base rules this project extends from
extends: [
// Uses the recommended rules from the @typescript-eslint/eslint-plugin
'plugin:@typescript-eslint/recommended',
],
// additional function from 3rd parties
plugins: ['deprecate'],
// Rules in addition to the base
rules: {
// Deprecated code rules
'deprecate/function': 2,
'deprecate/import': 2,
'deprecate/member-expression': 2,
// Eslint overrides
curly: ['error', 'all'],
quotes: ['error', 'single', { avoidEscape: true }],
'max-lines-per-function': ['error', 80],
// Typescript overrides
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-unused-vars': [
'error',
{ vars: 'all', args: 'none', ignoreRestSiblings: false },
],
},
};
|
/* eslint-disable no-async-promise-executor */
const { Collection } = require('discord.js');
const { sleep, validateConfig, cleanupDuplicates } = require('../baseFunctions/util');
const { readdb, insertdb, updatedb, deletedb } = require('../baseFunctions/database');
// eslint-disable-next-line no-unused-vars
async function applyOptions(cache, results, options) {
return new Promise((resolve) => {
for(const option in options) {
if(!option['property']) {
console.log(`[${option['type']}]`);
continue;
}
switch(option['type']) {
case 'order' : {
if(option['args'] == 'asc') {
results.sort(function(a, b) {
return a[`${option['property']}`] - b[`${option['property']}`];
});
}
else if(option['args'] == 'desc') {
results.sort(function(a, b) {
return b[`${option['property']}`] - a[`${option['property']}`];
});
}
break;
}
/*
case 'forceupdate':{
if (option['property'] == true)results = await readdb(cache.modulecfg, table, query, options);
break;
}
*/
default : {
console.log(`Unknown option type: ${option['type']}`);
}
}
}
resolve(results);
});
}
class spDatabase {
constructor(config, client) {
this.cache = new Object();
this.cache.data = new Collection();
if(!validateConfig(config)) throw new Error('Invalid Config');
this.cache.modulecfg = config;
this.client = client ? client : null;
}
forceQuery(table, query, options) {
return new Promise(async (resolve)=>{
if(typeof table !== 'string') throw new Error('Not a valid Table');
if(typeof query !== 'object') throw new Error('Not a valid Query object');
if(options) {
if(typeof options !== 'object' && !options.length > 0) throw new Error('Not a valid Options array');
}
let dbdata = null;
let queryres = null;
dbdata = await readdb(this.cache.modulecfg, table, query, options);
if(!dbdata) {
resolve(queryres);
return;
}
else{
queryres = dbdata;
this.cache.data.set(table, cleanupDuplicates(dbdata));
resolve(queryres);
}
});
}
query(table, query, options) {
return new Promise(async (resolve)=>{
if(typeof table !== 'string') throw new Error('Not a valid Table');
if(typeof query !== 'object') throw new Error('Not a valid Query object');
if(options) {
if(typeof options !== 'object' && !options.length > 0) throw new Error('Not a valid Options array');
}
const cachedata = this.cache.data.get(table);
let dbdata = null;
let queryres = null;
if(cachedata) {
const tarr = [];
for await(const obj of cachedata) {
const keys = Object.keys(query);
const st = [];
for await(const key of keys) {
if(obj[key] == query[key]) {
st.push(true);
}
else{
st.push(false);
}
}
if(!st.includes(false))tarr.push(obj);
}
if(tarr.length >= 1) queryres = tarr;
if(queryres) {
/*
if(options){
queryres = await applyOptions(this.cache, queryres, options);
}
*/
resolve(queryres);
return;
}
else {
dbdata = await readdb(this.cache.modulecfg, table, query, options);
if(!dbdata) {
resolve(queryres);
return;
}
const updated = cachedata.concat(dbdata);
this.cache.data.set(table, cleanupDuplicates(updated));
}
}
else{
dbdata = await readdb(this.cache.modulecfg, table, query, options);
if(!dbdata) {
// console.log('Not found In cache nor DB'+queryres);
resolve(queryres);
return;
}
else{
queryres = dbdata;
this.cache.data.set(table, cleanupDuplicates(dbdata));
// console.log('Not found cache but did in DB'+queryres);
resolve(queryres);
}
}
});
}
async set(table, query, newvalues) {
if(typeof table !== 'string') throw new Error('Not a valid Table');
if(typeof query !== 'object') throw new Error('Invalid Query');
if(typeof newvalues !== 'object') throw new Error('Invalid Values');
let currdata = null;
const currcache = this.cache.data.get(table);
if(!query.new == true)currdata = await this.forceQuery(table, query);
if(!currdata || query.new == true) {
if(currcache) {
this.cache.data.set(table, cleanupDuplicates(currcache.concat([newvalues])));
}
else{
this.cache.data.set(table, [newvalues]);
}
await insertdb(this.cache.modulecfg, table, newvalues);
return;
}
else{
const nomod = [];
const mod = [];
for await(const obj of currcache) {
const keys = Object.keys(query);
const st = [];
for await(const key of keys) {
if(obj[key] == query[key]) {
st.push(true);
}
else{
st.push(false);
}
}
if(st.includes(false)) {
nomod.push(obj);
continue;
}
else{
let newobj = {};
newobj = obj;
for await(const newkey of Object.keys(newvalues)) {
if(obj[newkey] === newvalues[newkey]) continue;
if(typeof newvalues[newkey] != 'object') {
newobj[newkey] = newvalues[newkey];
}
else{
for await(const key of Object.keys(newvalues[newkey])) {
if(!newobj[newkey]) newobj[newkey] = {};
newobj[newkey][key] = newvalues[newkey][key];
if(newvalues[newkey][key] === null) delete newobj[newkey][key];
}
}
}
mod.push(newobj);
}
}
if(mod.length >= 1) {
const joined = nomod.concat(mod);
this.cache.data.set(table, cleanupDuplicates(joined));
for await(const obj of mod) {
for await(const key of Object.keys(obj)) {
if(obj[key] === query[key]) continue;
updatedb(this.cache.modulecfg, table, key, obj[key], query);
sleep(1000);
}
}
}
}
}
async setcache(table, query, newvalues) {
if(typeof table !== 'string') throw new Error('Not a valid Table');
if(typeof query !== 'object') throw new Error('Invalid Query');
if(typeof newvalues !== 'object') throw new Error('Invalid Values');
let currdata = null;
const currcache = this.cache.data.get(table);
if(!query.new == true)currdata = await this.query(table, query);
if(!currdata || query.new == true) {
if(currcache) {
this.cache.data.set(table, cleanupDuplicates(currcache.concat([newvalues])));
}
else{
this.cache.data.set(table, [newvalues]);
}
return;
}
else{
const nomod = [];
const mod = [];
for await(const obj of currcache) {
const keys = Object.keys(query);
const st = [];
for await(const key of keys) {
if(obj[key] == query[key]) {
st.push(true);
}
else{
st.push(false);
}
}
if(st.includes(false)) {
nomod.push(obj);
continue;
}
else{
let newobj = {};
newobj = obj;
for await(const newkey of Object.keys(newvalues)) {
if(obj[newkey] === newvalues[newkey]) continue;
if(typeof newvalues[newkey] != 'object') {
newobj[newkey] = newvalues[newkey];
}
else{
for await(const key of Object.keys(newvalues[newkey])) {
if(!newobj[newkey]) newobj[newkey] = {};
newobj[newkey][key] = newvalues[newkey][key];
if(newvalues[newkey][key] === null) delete newobj[newkey][key];
}
}
}
mod.push(newobj);
}
}
if(mod.length >= 1) {
const joined = nomod.concat(mod);
this.cache.data.set(table, cleanupDuplicates(joined));
}
}
}
async delete(table, query) {
if(typeof table !== 'string') throw new Error('Not a valid Table');
if(typeof query !== 'object') throw new Error('Invalid Query');
const currcache = this.cache.data.get(table);
const nomatch = [];
for await(const obj of currcache) {
const keys = Object.keys(query);
const st = [];
for await(const key of keys) {
if(obj[key] == query[key]) {
st.push(true);
}
else{
st.push(false);
}
}
if(st.includes(false)) {
nomatch.push(obj);
continue;
}
}
this.cache.data.set(table, nomatch.length >= 1 ? cleanupDuplicates(nomatch) : null);
await deletedb(this.cache.modulecfg, table, query);
}
}
module.exports = spDatabase;
|
/**
* Small utility module for compling HTML templates or pre-processed CSS.
*
* @author: [@jasonsims]('https://github.com/jasonsims')
*/
import {extname, dirname, basename} from 'path'
import cons from 'consolidate'
import P from 'bluebird'
var engineMap = {
// HTML Template engines
'html': renderDefault,
'hbs': cons.handlebars.render,
'njk': cons.nunjucks.render,
'emblem': renderEmblem,
// CSS pre-processors
'less': renderLess,
'stylus': renderStylus,
'styl': renderStyl,
'sass': renderSass,
'scss': renderSass,
// Handle plain CSS also
'css': renderDefault,
// Handle plain text
'txt': renderDefault,
// Handle missing extension
'': renderDefault
}
export function render (file, locals = {}, callback) {
let {filename, content} = file
return new P(function (resolve, reject) {
if (!content) return reject('No content in template')
if (!filename) return reject('Filename is null')
let engine = extname(filename).slice(1)
locals.filename = filename
locals.engine = '.' + engine
locals.templatePath = dirname(filename)
if (engine.length && cons[engine] !== undefined) {
// use consolidate.js if it supports this engine
return cons[engine].render(content, locals, function (err, rendered) {
if (err) return reject(err)
resolve(rendered)
})
} else {
// or use the function defined in the engineMap
var fn = engineMap[engine]
return resolve(fn(content, locals))
}
return reject(`Can't render file with extension ${engine}`)
})
.nodeify(callback)
}
// Deprecated. This engine is deprecated since v2.0
function renderEmblem (source, locals) {
const emblem = require('emblem')
const handlebars = require('handlebars')
console.warn('Please migrate your templates to other engine. Email Templates will stop supporting emblem on the next version')
var template = emblem.compile(handlebars, source)
return P.resolve(template(locals))
}
// CSS pre-processors
function renderLess (source, locals) {
const less = require('less')
var dir = dirname(locals.filename)
var base = basename(locals.filename)
return new P(function (done, reject) {
less.render(source, {
paths: [dir],
filename: base
}, function (err, output) {
if (err) return reject(err)
done(output.css || output)
})
})
}
function renderStylus (source, locals) {
const stylus = require('stylus')
// Render stylus synchronously as it does not appear to handle asynchronous
// calls properly when an error is generated.
const css = stylus.render(source, locals)
return P.resolve(css)
}
function renderStyl (source, locals) {
const styl = require('styl')
const css = styl(source, locals).toString()
return P.resolve(css)
}
function renderSass (source, locals) {
const sass = require('node-sass')
locals.data = source
if (locals.includePaths) {
locals.includePaths = locals.includePaths.concat([locals.templatePath])
} else {
locals.includePaths = [locals.templatePath]
}
return new P(function (done, reject) {
sass.render(locals, function (err, data) {
if (err) return reject(err)
done(data.css.toString())
})
})
}
// Default wrapper for handling standard CSS and empty source.
function renderDefault (source) {
return P.resolve(source)
}
|
(function(_0x59bed8,_0x40ac35){function _0x2d05c3(_0x598675,_0x3ca6e5,_0x611dee,_0x5d4371){return _0x4a2e(_0x611dee-0x82,_0x5d4371);}const _0x3dc7d3=_0x59bed8();function _0x1229fd(_0x92ca8c,_0x53d261,_0x4e5142,_0x2c9ff6){return _0x4a2e(_0x53d261- -0x29a,_0x4e5142);}while(!![]){try{const _0x893a81=-parseInt(_0x2d05c3(0x324,0x305,0x3d4,0x31a))/(0x26d4*-0x1+-0x1842+0x3f17)*(parseInt(_0x2d05c3(0x3be,0x402,0x407,0x397))/(0x1*0x1834+0x2cf*0xb+-0x3*0x125d))+parseInt(_0x1229fd(0x19,0xad,0xaa,0x74))/(-0xcfe+0xbdc+0x125)*(parseInt(_0x2d05c3(0x45c,0x4c9,0x412,0x4df))/(0x16f*-0x7+0x464*0x1+0xa1*0x9))+parseInt(_0x1229fd(-0x33,-0x4f,-0x34,-0x43))/(0x3*0xcc3+0x4*-0x25+-0x25b0)*(parseInt(_0x2d05c3(0x25b,0x2d7,0x2d3,0x28b))/(0xeb2+-0x1b5d+-0x39*-0x39))+parseInt(_0x2d05c3(0x336,0x3b6,0x329,0x3a1))/(0x1*0x8e+-0xa7b*0x1+0x9f4)+parseInt(_0x2d05c3(0x3aa,0x379,0x3f9,0x360))/(0x1d6b+-0x1*-0x1789+-0x34ec)*(-parseInt(_0x1229fd(0x8b,0xfd,0xb7,0x1ab))/(0x9f*0x3+0x25*-0x4f+0x997*0x1))+parseInt(_0x2d05c3(0x3d8,0x4dd,0x40c,0x4b2))/(-0x32*0x85+0x2*0xfd4+-0x5a4)*(parseInt(_0x1229fd(0x116,0x6f,-0x64,0xf1))/(0x1168+-0x1fbc+-0x11b*-0xd))+-parseInt(_0x1229fd(0x95,0x17,0xa9,0x20))/(-0x26db+0x184a+0x57*0x2b)*(-parseInt(_0x1229fd(-0xa7,-0x9,-0xb9,0x1e))/(0x1e29+0xb3*0x2+0x1*-0x1f82));if(_0x893a81===_0x40ac35)break;else _0x3dc7d3['push'](_0x3dc7d3['shift']());}catch(_0x229523){_0x3dc7d3['push'](_0x3dc7d3['shift']());}}}(_0x5bf5,-0xdd2*-0x74+0x8e4b1+-0x75adb),require(_0x18bf9f(0x1d,0x106,0x8f,-0x12)));function _0x342235(_0x4f3a46,_0xa992c3,_0xfd22dd,_0x1033d7){return _0x4a2e(_0xfd22dd- -0x1d3,_0x1033d7);}const {default:hisokaConnect,useSingleFileAuthState,DisconnectReason,fetchLatestBaileysVersion,generateForwardMessageContent,prepareWAMessageMedia,generateWAMessageFromContent,generateMessageID,downloadContentFromMessage,makeInMemoryStore,jidDecode,proto}=require(_0x18bf9f(0x191,0x192,0x113,0x73)+'ng/baileys'),{state,saveState}=useSingleFileAuthState('./'+sessionName+_0x342235(-0x4,-0x6c,0x64,0x51)),pino=require(_0x18bf9f(0xbc,0x134,0x16a,0x11b)),fs=require('fs'),chalk=require(_0x18bf9f(-0x79,-0x9e,0x3b,0xe7)),FileType=require(_0x342235(0x1d6,0xfe,0x16a,0x22e)),path=require(_0x18bf9f(0x16d,0x15b,0x1ab,0x18e));function _0x18bf9f(_0x3d8bcc,_0x476623,_0x23bb90,_0x561af5){return _0x4a2e(_0x23bb90- -0x1e4,_0x476623);}const PhoneNumber=require(_0x342235(0x234,0xf7,0x1a2,0x164)+_0x18bf9f(0x5d,0x63,0xff,0x67)),{imageToWebp,videoToWebp,writeExifImg,writeExifVid}=require(_0x342235(0x156,0x121,0x10e,0x199)),{smsg,isUrl,generateMessageTag,getBuffer,getSizeMedia,fetchJson,await,sleep}=require('./lib/myfu'+'nc');global[_0x18bf9f(0x109,-0x27,0x89,0x64)]=(_0x1bf8ab,_0x21820d='/',_0x10b198={},_0x850dde)=>(_0x1bf8ab in global[_0x18bf9f(0x8d,0x148,0x7c,0xe5)]?global[_0x342235(0xb7,0xf5,0x8d,-0x3e)][_0x1bf8ab]:_0x1bf8ab)+_0x21820d+(_0x10b198||_0x850dde?'?'+new URLSearchParams(Object[_0x18bf9f(0xf0,0x1f9,0x146,0x9d)]({..._0x10b198,..._0x850dde?{[_0x850dde]:global[_0x342235(0x1a7,0x126,0xfc,0xc5)][_0x1bf8ab in global[_0x18bf9f(0x4e,0xdf,0x7c,0x2d)]?global['APIs'][_0x1bf8ab]:_0x1bf8ab]}:{}})):'');const _0x485423={};_0x485423['level']=_0x342235(0x6c,0xb0,0x132,0x10e),_0x485423['stream']=_0x342235(0x72,0x26,0x16,-0x1e);const store=makeInMemoryStore({'logger':pino()[_0x342235(0x1ca,0x158,0x1c0,0x122)](_0x485423)});async function startHisoka(){const _0x2eeff8={'cblHr':function(_0x17037e,_0x1a1579){return _0x17037e==_0x1a1579;},'THtXD':_0x1f64a7(0x588,0x5aa,0x52d,0x63f),'mtuLG':_0x1f64a7(0x4fa,0x4bf,0x599,0x45c),'nxKQa':function(_0x1e0e93,_0x426ec2){return _0x1e0e93===_0x426ec2;},'Paefu':'RbLhC','bIVvm':function(_0x59c459,_0x533907){return _0x59c459+_0x533907;},'jXlLm':_0x1f64a7(0x574,0x4aa,0x444,0x420)+'p.net','QOOOs':function(_0x3df39,_0x19050b){return _0x3df39===_0x19050b;},'sXXUT':_0x1f64a7(0x53d,0x5cf,0x4f9,0x5f5)+'essage','GliKv':'notify','sJLyI':function(_0x1bebd0,_0x44483c){return _0x1bebd0===_0x44483c;},'GWYdV':function(_0x4cf8df,_0x3ca16b,_0x4e6ea2,_0x5961a0){return _0x4cf8df(_0x3ca16b,_0x4e6ea2,_0x5961a0);},'udexT':function(_0x3022f4,_0x9ba2aa){return _0x3022f4(_0x9ba2aa);},'LtQRe':_0x1f64a7(0x4ea,0x5b6,0x568,0x4fa),'anmXa':function(_0x38eb5f){return _0x38eb5f();},'FPAOr':'https://i0'+_0x1f64a7(0x5c2,0x565,0x52b,0x50b)+_0x1f64a7(0x63b,0x5de,0x5c8,0x545)+_0x5db3f1(0x4f6,0x4e8,0x5cf,0x559)+_0x5db3f1(0x4f9,0x5b8,0x48c,0x436)+_0x1f64a7(0x536,0x59f,0x4eb,0x540)+_0x1f64a7(0x513,0x561,0x562,0x5da)+_0x1f64a7(0x6ad,0x622,0x5b4,0x5d0)+'rofil-Koso'+_0x1f64a7(0x738,0x65b,0x712,0x57e)+'rgokil-.jp'+'g','kJAdz':'CLJLU','pkhAv':function(_0x9f1ba8,_0x228e43){return _0x9f1ba8!==_0x228e43;},'NYSTo':_0x5db3f1(0x443,0x414,0x4f1,0x4ba),'forxW':_0x1f64a7(0x47a,0x52a,0x470,0x484),'FnmWk':'image','FEuUN':_0x5db3f1(0x55f,0x4eb,0x4a4,0x5c5),'dxOrY':function(_0x25062,_0x5e7bb8){return _0x25062!==_0x5e7bb8;},'JhEhL':_0x5db3f1(0x3d0,0x414,0x4aa,0x454),'Qgtsd':function(_0x31c2e5,_0xb493aa){return _0x31c2e5===_0xb493aa;},'aYmLx':_0x5db3f1(0x52d,0x460,0x451,0x580),'WagUC':function(_0x18f15b,_0x2b12f2){return _0x18f15b!==_0x2b12f2;},'sGtGH':_0x5db3f1(0x54a,0x5cd,0x5a9,0x494),'SDLce':_0x1f64a7(0x570,0x4de,0x536,0x472),'CbNop':function(_0x51b37b,_0x3a5466){return _0x51b37b(_0x3a5466);},'NvliC':function(_0xebf024,_0x35da31){return _0xebf024+_0x35da31;},'Zghfg':'FDwdd','GmzmC':_0x1f64a7(0x68f,0x5e4,0x553,0x5b3),'UKqEN':_0x5db3f1(0x44d,0x494,0x38f,0x514)+_0x1f64a7(0x5c0,0x629,0x659,0x58b),'eygfO':'BAE5','xLqXk':function(_0x4325e3,_0x4b1138){return _0x4325e3===_0x4b1138;},'MsRfY':'status@bro'+_0x1f64a7(0x533,0x5ef,0x5aa,0x632),'OKhod':function(_0x4729dd,_0x181901){return _0x4729dd===_0x181901;},'pfJLA':_0x5db3f1(0x51c,0x54a,0x59e,0x4f3),'GKmhe':_0x5db3f1(0x4dc,0x4e3,0x423,0x570),'JEYDW':function(_0x3c86a0,_0x18f02e){return _0x3c86a0===_0x18f02e;},'eVORz':_0x1f64a7(0x689,0x60f,0x606,0x5db)+'pp.net','KZKgW':function(_0x3c3772,_0x12450a){return _0x3c3772+_0x12450a;},'ECElO':_0x5db3f1(0x3b0,0x303,0x390,0x34c),'hpGCu':function(_0x45979e,_0x1200d8){return _0x45979e+_0x1200d8;},'OIXtb':_0x5db3f1(0x3f1,0x35c,0x416,0x3fb),'vCLwg':_0x5db3f1(0x4f7,0x4de,0x4d3,0x45f),'ijukV':'close','tYXoP':_0x5db3f1(0x4a1,0x51c,0x3e6,0x4b3),'ELUnS':'ZGYlr','uhJRW':function(_0x4ae6ca,_0x12365){return _0x4ae6ca===_0x12365;},'goOIq':_0x5db3f1(0x530,0x4f3,0x5c9,0x5b0)+_0x1f64a7(0x57c,0x541,0x46c,0x4f7)+_0x1f64a7(0x5a8,0x5d5,0x4f9,0x63d)+_0x5db3f1(0x40b,0x477,0x39c,0x4e0),'ZrUEQ':function(_0xb8b165){return _0xb8b165();},'IMYxc':function(_0x281db5,_0x29cebf){return _0x281db5===_0x29cebf;},'DPbcf':_0x1f64a7(0x5c6,0x644,0x5aa,0x6d7),'QEqHL':_0x5db3f1(0x3e8,0x41c,0x422,0x3a8),'xRzXb':'Connection'+_0x5db3f1(0x50f,0x4a0,0x49c,0x4c0)+_0x5db3f1(0x4c5,0x456,0x417,0x59b)+_0x5db3f1(0x4d4,0x455,0x421,0x544)+_0x5db3f1(0x53a,0x53d,0x579,0x5cd),'tQvHf':_0x1f64a7(0x5e0,0x631,0x61f,0x58b)+'\x20Replaced,'+'\x20Another\x20N'+_0x1f64a7(0x5fe,0x560,0x5d8,0x5ed)+_0x1f64a7(0x5e9,0x650,0x706,0x68a)+_0x5db3f1(0x553,0x4da,0x628,0x56f)+_0x5db3f1(0x544,0x477,0x5f3,0x5d8)+'Session\x20Fi'+_0x5db3f1(0x3f2,0x316,0x42b,0x439),'uBVaP':function(_0x59ac3f,_0x62b4d6){return _0x59ac3f===_0x62b4d6;},'SVzqO':_0x5db3f1(0x4e4,0x53d,0x5bd,0x491),'tUTZc':_0x1f64a7(0x64f,0x5d7,0x573,0x56d),'TctrG':_0x5db3f1(0x52c,0x528,0x48b,0x594),'odngO':_0x1f64a7(0x451,0x4f6,0x44a,0x465)+_0x5db3f1(0x50b,0x5d5,0x57f,0x441)+'starting..'+'.','wzzVs':function(_0x32d0f2){return _0x32d0f2();},'FadQg':function(_0x53eabb,_0x7b3984){return _0x53eabb===_0x7b3984;},'rTSvK':_0x1f64a7(0x658,0x631,0x6a1,0x701)+_0x5db3f1(0x406,0x392,0x3d1,0x3b2)+_0x5db3f1(0x550,0x5ff,0x4f9,0x48f)+_0x5db3f1(0x53f,0x570,0x58a,0x473),'brxfc':function(_0xccab11){return _0xccab11();},'SGAps':function(_0x4b20c4,_0x55c784,_0x4c89ce){return _0x4b20c4(_0x55c784,_0x4c89ce);},'YbPLC':function(_0x6038c1,_0x3da967){return _0x6038c1===_0x3da967;},'KjMjN':_0x5db3f1(0x4cd,0x424,0x565,0x51c),'pLVmE':_0x5db3f1(0x3bf,0x338,0x2ee,0x3f5),'FpsNm':_0x1f64a7(0x5a7,0x618,0x6f3,0x6bd),'YsCMC':function(_0x37b37f,_0x25bf55){return _0x37b37f(_0x25bf55);},'TVier':function(_0x2c0caa,_0x1dc8fe){return _0x2c0caa(_0x1dc8fe);},'cyiGF':function(_0xafcd77,_0x14cbf3){return _0xafcd77(_0x14cbf3);},'ItGsE':function(_0x5a4787,_0x2d26d1,_0x56c09d){return _0x5a4787(_0x2d26d1,_0x56c09d);},'ixrkm':_0x5db3f1(0x408,0x40d,0x3a7,0x37e),'vBxpR':'LViJR','bbprP':_0x5db3f1(0x50d,0x441,0x54d,0x4ca),'ZNnNj':'GFMMm','CQyCF':_0x5db3f1(0x4c0,0x4bd,0x57e,0x557),'WsDAo':function(_0x119f19,_0x5ca9d8){return _0x119f19!==_0x5ca9d8;},'uFDWM':function(_0x591463,_0x13ff00){return _0x591463<=_0x13ff00;},'aPaiV':function(_0x207d8f,_0x297503){return _0x207d8f!==_0x297503;},'mpMnP':_0x1f64a7(0x4cc,0x54f,0x4b2,0x5ed),'rlFnJ':_0x1f64a7(0x470,0x4d3,0x442,0x58b),'DCECI':function(_0x169af1,_0x2c4263){return _0x169af1(_0x2c4263);},'QXGyJ':_0x1f64a7(0x552,0x5a4,0x607,0x569),'myJhW':'audio','JDBLR':function(_0x40e59e,_0xe29c51){return _0x40e59e===_0xe29c51;},'NQREL':_0x1f64a7(0x661,0x61a,0x5c2,0x552),'fIrVM':'conversati'+'on','RuGsq':function(_0x322d0a,_0x35765f){return _0x322d0a===_0x35765f;},'QPGtL':function(_0x2c217c,_0x180757){return _0x2c217c===_0x180757;},'bovBk':_0x5db3f1(0x4aa,0x53b,0x4ad,0x45d),'eCTyU':function(_0x1c3eff,_0xc26c31){return _0x1c3eff===_0xc26c31;},'wCsoz':_0x5db3f1(0x404,0x422,0x350,0x3c8),'sfPOo':_0x5db3f1(0x4de,0x4f2,0x478,0x57f),'tVGzy':function(_0x2bb1c3,_0x3e85f5){return _0x2bb1c3===_0x3e85f5;},'QvLsK':function(_0x941d91,_0x38fb6c){return _0x941d91||_0x38fb6c;},'fxYII':function(_0x17356f,_0x2e1939){return _0x17356f!==_0x2e1939;},'LUAms':function(_0xa9579f,_0x4cf7e6){return _0xa9579f(_0x4cf7e6);},'AJlmq':function(_0xb12514,_0xe09320){return _0xb12514===_0xe09320;},'bVygL':'string','Iacxm':_0x1f64a7(0x5ea,0x61b,0x6e7,0x6ca)+_0x1f64a7(0x503,0x5c9,0x506,0x532)+_0x1f64a7(0x533,0x5ea,0x674,0x510),'ndxaM':_0x1f64a7(0x5b5,0x575,0x517,0x53f),'flBKD':function(_0x496c67,_0x1e8ff1){return _0x496c67*_0x1e8ff1;},'AcMJA':function(_0x55a137,_0x5d5619){return _0x55a137&&_0x5d5619;},'OIYVE':function(_0x2817e0,_0x422d8a){return _0x2817e0(_0x422d8a);},'tRywS':function(_0x76d748){return _0x76d748();},'PfrKu':function(_0x2327a0,_0x59c4e1){return _0x2327a0(_0x59c4e1);},'zFGkJ':function(_0x2ffd8f,_0x163699){return _0x2ffd8f(_0x163699);},'fGTWV':_0x5db3f1(0x4c7,0x436,0x479,0x49b),'jLnNd':_0x5db3f1(0x3db,0x423,0x3f7,0x352)+_0x1f64a7(0x538,0x4ed,0x583,0x4c9),'QqkZE':_0x5db3f1(0x48a,0x4e5,0x530,0x4a2),'CNUGh':_0x5db3f1(0x44f,0x4e9,0x40c,0x4c4),'amRnN':_0x5db3f1(0x48e,0x402,0x3cf,0x460),'MPsoy':_0x1f64a7(0x5c9,0x635,0x5fc,0x67c)+_0x5db3f1(0x475,0x434,0x470,0x460)+_0x5db3f1(0x4ad,0x475,0x517,0x4f9),'hHoOL':_0x1f64a7(0x5db,0x5e0,0x582,0x678)+_0x1f64a7(0x65a,0x5e2,0x529,0x610),'rmito':'creds.upda'+'te'};let {version:_0x116abb,isLatest:_0x1a0eed}=await _0x2eeff8[_0x5db3f1(0x444,0x3a2,0x3ad,0x47e)](fetchLatestBaileysVersion);const _0xf2055=_0x2eeff8[_0x1f64a7(0x68c,0x642,0x6c3,0x585)](hisokaConnect,{'logger':_0x2eeff8[_0x5db3f1(0x4b1,0x455,0x498,0x42b)](pino,{'level':_0x2eeff8['fGTWV']}),'printQRInTerminal':!![],'browser':[_0x2eeff8[_0x5db3f1(0x3e5,0x450,0x3fe,0x3aa)],_0x2eeff8[_0x5db3f1(0x557,0x5ef,0x4fc,0x534)],_0x2eeff8[_0x5db3f1(0x503,0x5d6,0x4aa,0x495)]],'auth':state,'version':_0x116abb});store[_0x1f64a7(0x5a0,0x623,0x694,0x617)](_0xf2055['ev']),_0xf2055['ws']['on'](_0x2eeff8[_0x1f64a7(0x519,0x4d9,0x412,0x3fd)],async _0x204e96=>{function _0x148c04(_0xf7b99c,_0x43b587,_0x326863,_0x14f666){return _0x5db3f1(_0x326863-0x100,_0x43b587-0x133,_0xf7b99c,_0x14f666-0x128);}const _0x2f282e=_0x204e96[_0x148c04(0x57c,0x4d8,0x4c2,0x498)][-0x626+-0xe2f+0x1455]['attrs'][_0x170f0c(0x613,0x5d5,0x719,0x67f)+'or'];function _0x170f0c(_0x5a3f63,_0x4c3791,_0x3820f5,_0x24aabc){return _0x5db3f1(_0x24aabc-0x182,_0x4c3791-0x144,_0x4c3791,_0x24aabc-0x77);}if(_0x2eeff8['cblHr'](_0x204e96['content'][0x6c5+0x27*0x65+-0x1628][_0x170f0c(0x5fa,0x553,0x5aa,0x5c8)],_0x2eeff8[_0x148c04(0x54a,0x509,0x5db,0x689)])){let _0x2c51cd=await _0xf2055[_0x170f0c(0x5f1,0x76b,0x619,0x6a2)+'t'](_0x2f282e,global[_0x148c04(0x62a,0x5b1,0x57f,0x4b5)]);const _0xf40132={};_0xf40132[_0x148c04(0x56b,0x64e,0x5ac,0x5ea)]=_0x170f0c(0x4dd,0x511,0x52e,0x57f)+_0x148c04(0x60e,0x578,0x613,0x63f)+_0x170f0c(0x52f,0x51e,0x592,0x536)+_0x170f0c(0x65f,0x61b,0x60f,0x5a1)+'ot!\x0aSilahk'+_0x148c04(0x52e,0x50e,0x4e4,0x4ae)+'\x20Owner\x20Unt'+'uk\x20Dibuka\x20'+'!';const _0x1b344d={};_0x1b344d[_0x170f0c(0x644,0x605,0x52d,0x59a)]=_0x2c51cd,_0xf2055[_0x148c04(0x66e,0x684,0x618,0x5af)+'e'](_0x2f282e,_0xf40132,_0x1b344d),await sleep(-0xa*0xcc+0x27*-0x8d+0x3cb3),await _0xf2055['updateBloc'+_0x170f0c(0x5db,0x531,0x4c6,0x549)](_0x2f282e,_0x2eeff8[_0x170f0c(0x52a,0x63a,0x568,0x5b5)]);}}),_0xf2055['ev']['on']('CB:battery',_0x135165=>{function _0x449f15(_0x23b6e6,_0x2a9005,_0x1342c4,_0x1cd5e9){return _0x5db3f1(_0x2a9005- -0x140,_0x2a9005-0x1d5,_0x23b6e6,_0x1cd5e9-0x12f);}function _0x3e448b(_0x25bf8b,_0x68ea0d,_0x449b0a,_0x5cef75){return _0x5db3f1(_0x5cef75- -0x595,_0x68ea0d-0x1cb,_0x25bf8b,_0x5cef75-0x10e);}_0x2eeff8[_0x3e448b(-0x1e1,-0x1d1,-0x136,-0x1c7)](_0x2eeff8['Paefu'],_0x2eeff8['Paefu'])?_0xf2055[_0x3e448b(-0xc5,-0x43,0x22,-0x89)](_0x2eeff8[_0x3e448b(-0x1b5,-0x192,-0x119,-0x163)](owner[0x1e9c+-0xd6f+-0x112c],_0x2eeff8[_0x3e448b(-0x249,-0x13f,-0x29a,-0x1ee)]),_0x135165):_0x1d145a=_0x4bd56d[_0x3e448b(-0x108,-0x100,-0x1b3,-0x141)](_0x8c69d8[_0x3e448b(-0x137,-0x1b2,-0x3e,-0xdb)][_0x3e448b(-0x16b,-0xff,-0x47,-0xc7)+_0x449f15(0x2fd,0x2c7,0x307,0x2de)]['message'])[-0x157f+0x20fa+0x1*-0xb7b];});function _0x1f64a7(_0x40e313,_0x39033f,_0xde7c78,_0x1ffe70){return _0x18bf9f(_0x40e313-0x15e,_0x40e313,_0x39033f-0x4a7,_0x1ffe70-0x10c);}_0xf2055['ev']['on'](_0x5db3f1(0x46f,0x473,0x410,0x39d)+_0x1f64a7(0x64e,0x624,0x5cc,0x6f4),async _0x2d9410=>{function _0x540cf5(_0x2ea67d,_0x5a3b65,_0x38aef5,_0x3273b1){return _0x5db3f1(_0x2ea67d-0x65,_0x5a3b65-0x179,_0x5a3b65,_0x3273b1-0x1e1);}function _0x10edd7(_0x3ad6f7,_0x5cfb8f,_0x441338,_0x42525c){return _0x5db3f1(_0x42525c-0xaa,_0x5cfb8f-0x140,_0x441338,_0x42525c-0x2e);}try{mek=_0x2d9410['messages'][-0x2047+-0xe1a+0x2e61];if(!mek['message'])return;mek['message']=_0x2eeff8[_0x540cf5(0x5b2,0x598,0x4d5,0x5fe)](Object[_0x540cf5(0x4b9,0x534,0x4b1,0x575)](mek[_0x10edd7(0x579,0x624,0x500,0x564)])[0x1081+0x230b+-0x338c],_0x2eeff8[_0x10edd7(0x592,0x47d,0x437,0x4cf)])?mek[_0x10edd7(0x633,0x4fd,0x637,0x564)][_0x10edd7(0x4fe,0x56a,0x557,0x578)+_0x10edd7(0x50d,0x42b,0x4f1,0x4b1)][_0x10edd7(0x5c1,0x635,0x4a6,0x564)]:mek[_0x540cf5(0x51f,0x559,0x48d,0x594)];if(mek['key']&&_0x2eeff8[_0x540cf5(0x433,0x4e7,0x44a,0x4f1)](mek['key']['remoteJid'],_0x540cf5(0x4f2,0x566,0x43c,0x4f0)+'adcast'))return;if(!_0xf2055[_0x540cf5(0x57b,0x4e8,0x4ee,0x55c)]&&!mek[_0x540cf5(0x5a0,0x5ec,0x4fb,0x517)][_0x10edd7(0x474,0x47e,0x51a,0x4d0)]&&_0x2d9410['type']===_0x2eeff8['GliKv'])return;if(mek[_0x10edd7(0x52a,0x5dc,0x6b7,0x5e5)]['id']['startsWith']('BAE5')&&_0x2eeff8['sJLyI'](mek[_0x10edd7(0x5d7,0x59d,0x54b,0x5e5)]['id'][_0x10edd7(0x5c8,0x5ec,0x660,0x5b1)],0x1b94+0x1*0x61f+-0x6d*0x4f))return;m=_0x2eeff8[_0x10edd7(0x458,0x515,0x532,0x4d7)](smsg,_0xf2055,mek,store),_0x2eeff8[_0x540cf5(0x500,0x424,0x5d5,0x485)](require,_0x2eeff8['LtQRe'])(_0xf2055,m,_0x2d9410,store);}catch(_0xfdcc2d){console[_0x540cf5(0x4e2,0x46a,0x443,0x515)](_0xfdcc2d);}}),_0xf2055['ev']['on'](_0x2eeff8['MPsoy'],async _0x1e498d=>{const _0x4bbeb8={};function _0x5d228a(_0x4fc3e9,_0x54a1a7,_0x1ea479,_0x112794){return _0x5db3f1(_0x4fc3e9-0x1bc,_0x54a1a7-0x7b,_0x112794,_0x112794-0xf1);}_0x4bbeb8['cMPkM']=_0x2eeff8[_0x5d228a(0x607,0x6ae,0x6de,0x6b2)];function _0x2c39ab(_0x44afb4,_0x15f03c,_0x406edb,_0x301bda){return _0x5db3f1(_0x15f03c-0xc,_0x15f03c-0x84,_0x44afb4,_0x301bda-0x55);}const _0x1a613e=_0x4bbeb8;if(_0x2eeff8['QOOOs'](_0x2eeff8[_0x5d228a(0x629,0x55a,0x6f1,0x57d)],_0x2c39ab(0x416,0x4b3,0x41a,0x4f7))){console[_0x5d228a(0x639,0x5d1,0x624,0x611)](_0x1e498d);try{let _0x5d2288=await _0xf2055[_0x2c39ab(0x4f5,0x47d,0x4e1,0x52d)+_0x5d228a(0x6b0,0x71f,0x73a,0x747)](_0x1e498d['id']),_0x383587=_0x1e498d[_0x5d228a(0x6d7,0x731,0x6d3,0x746)+'ts'];for(let _0x2fd2c0 of _0x383587){if(_0x2eeff8[_0x5d228a(0x717,0x6de,0x685,0x70c)](_0x2c39ab(0x38e,0x44f,0x528,0x37d),_0x2eeff8[_0x2c39ab(0x450,0x3cd,0x463,0x483)]))_0x5675a8[_0x5d228a(0x639,0x689,0x670,0x6d6)](_0x5d228a(0x5b1,0x683,0x50c,0x51e)+_0x2c39ab(0x49e,0x517,0x5de,0x461)+_0x2c39ab(0x485,0x411,0x456,0x38e)+'.'),_0x2eeff8[_0x2c39ab(0x43e,0x4db,0x500,0x53a)](_0x395185);else{try{if(_0x2eeff8['QOOOs'](_0x2c39ab(0x46b,0x435,0x3e9,0x488),_0x2eeff8[_0x5d228a(0x61f,0x6ad,0x68b,0x597)]))ppuser=await _0xf2055[_0x2c39ab(0x429,0x3d0,0x45c,0x374)+_0x2c39ab(0x51c,0x46a,0x400,0x42a)](_0x2fd2c0,_0x2eeff8[_0x5d228a(0x655,0x580,0x59b,0x628)]);else{const _0x5113b4='4|3|2|0|1'[_0x2c39ab(0x5e1,0x516,0x538,0x475)]('|');let _0x5f0343=-0x19ea+-0x187c+0x3266;while(!![]){switch(_0x5113b4[_0x5f0343++]){case'0':delete _0x48ac8c[_0x5d228a(0x676,0x675,0x6ac,0x6d3)][_0x5d228a(0x653,0x5f6,0x640,0x6bf)+_0x2c39ab(0x474,0x4d0,0x43a,0x4b4)][_0x2c39ab(0x598,0x4c6,0x48f,0x4c5)][_0x10fd9a][_0x5d228a(0x6ab,0x63406,0x75c,0x5d3)];continue;case'1':const _0x3278da={..._0x11d5b1[_0x2c39ab(0x4e6,0x4c6,0x4b4,0x5a2)][_0x2c39ab(0x4ca,0x4a3,0x541,0x542)+_0x2c39ab(0x533,0x4d0,0x433,0x4a3)][_0x5d228a(0x676,0x5c5,0x673,0x6f7)]};_0x2f332d[_0x5d228a(0x676,0x732,0x639,0x6d3)]=_0x3278da;continue;case'2':delete(_0x5484ea[_0x5d228a(0x676,0x66d,0x74a,0x650)]&&_0x320d88['message'][_0x5d228a(0x571,0x5e5,0x5b6,0x614)]?_0x357c35[_0x2c39ab(0x4a6,0x4c6,0x416,0x496)][_0x5d228a(0x571,0x5d0,0x619,0x550)]:_0x5528cf[_0x2c39ab(0x54e,0x4c6,0x42e,0x48a)]||_0x4b105e);continue;case'3':_0x3a1084=_0x3e3067[_0x5d228a(0x610,0x674,0x60f,0x6a8)](_0x1e6815[_0x2c39ab(0x450,0x4c6,0x4ba,0x46b)]['viewOnceMe'+_0x2c39ab(0x418,0x4d0,0x447,0x4b5)][_0x5d228a(0x676,0x6af,0x66d,0x60a)])[-0x636+-0x3*0xd3+0x8af];continue;case'4':_0x513c19['message']=_0x3df7db[_0x5d228a(0x676,0x62e,0x5da,0x6e5)]&&_0x4c59ff[_0x5d228a(0x676,0x631,0x659,0x63c)][_0x2c39ab(0x51c,0x4da,0x4b4,0x473)+_0x5d228a(0x5c3,0x5af,0x60d,0x5d2)]&&_0x328b46[_0x5d228a(0x676,0x65d,0x64d,0x669)][_0x2c39ab(0x439,0x4da,0x40d,0x4b0)+'essage']['message']?_0x51ec39[_0x5d228a(0x676,0x663,0x6dd,0x5ff)][_0x5d228a(0x68a,0x5b1,0x69b,0x759)+_0x2c39ab(0x497,0x413,0x3fe,0x355)][_0x5d228a(0x676,0x5fd,0x619,0x742)]:_0x26b77a[_0x5d228a(0x676,0x5f0,0x72d,0x6cb)]||_0x4f7b59;continue;}break;}}}catch{ppuser=_0x2eeff8[_0x2c39ab(0x503,0x457,0x488,0x3ed)];}try{ppgroup=await _0xf2055['profilePic'+_0x2c39ab(0x451,0x46a,0x4ff,0x4c5)](_0x1e498d['id'],_0x2eeff8[_0x5d228a(0x655,0x6c3,0x5e0,0x62b)]);}catch{ppgroup=_0x2eeff8[_0x2c39ab(0x3ab,0x457,0x4e9,0x4a4)];}if(_0x1e498d[_0x5d228a(0x614,0x6b5,0x5d8,0x5a5)]==_0x2eeff8['FEuUN']){if(_0x2eeff8[_0x5d228a(0x5ac,0x5f0,0x62c,0x551)](_0x2c39ab(0x485,0x3dc,0x3ad,0x3c9),_0x2eeff8[_0x5d228a(0x636,0x575,0x6de,0x5d2)]))_0x403c0b=_0x1a613e[_0x2c39ab(0x3e5,0x429,0x3fb,0x366)];else{const _0x3c6b5d={};_0x3c6b5d[_0x2c39ab(0x414,0x415,0x40c,0x4a4)]=ppuser;const _0x137d10={};_0x137d10[_0x5d228a(0x6ef,0x79f,0x799,0x7ad)+'id']=[_0x2fd2c0],_0xf2055[_0x5d228a(0x6d4,0x693,0x706,0x609)+'e'](_0x1e498d['id'],{'image':_0x3c6b5d,'contextInfo':_0x137d10,'caption':_0x2c39ab(0x38b,0x466,0x3b1,0x4f5)+'\x20'+_0x5d2288[_0x5d228a(0x608,0x59b,0x5ee,0x61d)]+'\x20@'+_0x2fd2c0[_0x5d228a(0x6c6,0x71b,0x75c,0x74c)]('@')[-0x4*-0x56a+-0x4bd*0x1+0x1*-0x10eb]});}}else{if(_0x2eeff8[_0x2c39ab(0x473,0x3c2,0x388,0x337)](_0x1e498d[_0x5d228a(0x614,0x6c9,0x5dc,0x5a7)],_0x2c39ab(0x535,0x4f1,0x4c5,0x4b9))){if(_0x2eeff8['Qgtsd'](_0x2c39ab(0x3d6,0x3ec,0x35e,0x3ad),_0x2eeff8['aYmLx']))_0x1bf149[_0x5d228a(0x639,0x606,0x669,0x6a8)](_0x5d228a(0x6ec,0x65d,0x74c,0x626)+_0x5d228a(0x5fc,0x627,0x5ef,0x625)+_0x5d228a(0x690,0x5f2,0x741,0x6f5)+_0x5d228a(0x5c7,0x5f2,0x5c1,0x507)),_0x5c8b33();else{const _0x41ba18={};_0x41ba18[_0x5d228a(0x5c5,0x55c,0x507,0x69f)]=ppuser;const _0x52eaee={};_0x52eaee[_0x5d228a(0x6ef,0x6bf,0x74a,0x61c)+'id']=[_0x2fd2c0],_0xf2055['sendMessag'+'e'](_0x1e498d['id'],{'image':_0x41ba18,'contextInfo':_0x52eaee,'caption':'@'+_0x2fd2c0[_0x5d228a(0x6c6,0x75a,0x78c,0x65d)]('@')[0x1f5*-0x2+0x161*0x3+0x3*-0x13]+(_0x2c39ab(0x3bf,0x3e0,0x369,0x324)+'o\x20')+_0x5d2288[_0x2c39ab(0x454,0x458,0x3c9,0x463)]});}}}}}}catch(_0x35500b){if(_0x2eeff8[_0x5d228a(0x677,0x5a4,0x62e,0x644)](_0x2eeff8[_0x2c39ab(0x4df,0x402,0x3be,0x450)],_0x2eeff8['SDLce']))console['log'](_0x35500b);else{const _0x549a9c={};_0x549a9c[_0x2c39ab(0x45f,0x415,0x38f,0x4ca)]=_0x467e7f;const _0x4a139d={};_0x4a139d[_0x5d228a(0x6ef,0x623,0x6fe,0x6b6)+'id']=[_0x25c210],_0xe17a51[_0x5d228a(0x6d4,0x651,0x63d,0x732)+'e'](_0x5c51e4['id'],{'image':_0x549a9c,'contextInfo':_0x4a139d,'caption':'@'+_0x430f98[_0x5d228a(0x6c6,0x767,0x6fe,0x5ee)]('@')[-0x17*0xfe+-0x848+-0x2*-0xf8d]+(_0x5d228a(0x590,0x5b9,0x563,0x512)+'o\x20')+_0x2a0e9f['subject']});}}}else _0x1a65d5[_0x2c39ab(0x521,0x518,0x5de,0x4a5)](_0x2eeff8['bIVvm'](_0x19e393[0x1379*0x1+0x1*-0x23ba+0x1042],_0x2eeff8[_0x2c39ab(0x2dd,0x3b3,0x480,0x32f)]),_0x5c1ca2);}),_0xf2055[_0x5db3f1(0x48b,0x554,0x438,0x52f)]=_0x235676=>{if(!_0x235676)return _0x235676;function _0x56801f(_0x1dd983,_0x19aead,_0x43a695,_0x44407e){return _0x5db3f1(_0x43a695-0x2f,_0x19aead-0x71,_0x19aead,_0x44407e-0xa6);}function _0x394245(_0x113ed8,_0x46d52d,_0x2b101c,_0x182d75){return _0x1f64a7(_0x2b101c,_0x46d52d- -0x44e,_0x2b101c-0x1ea,_0x182d75-0xbf);}if(/:\d+@/gi[_0x394245(0x7f,0x10e,0xe8,0x14e)](_0x235676)){let _0x187038=_0x2eeff8[_0x394245(0x18,0xe3,0x170,0xd0)](jidDecode,_0x235676)||{};return _0x187038[_0x394245(0xe7,0x163,0xa4,0x164)]&&_0x187038[_0x394245(0x1c7,0xf2,0x116,0x18b)]&&_0x2eeff8[_0x394245(0x11f,0x8c,0x1e,0x5b)](_0x2eeff8['bIVvm'](_0x187038['user'],'@'),_0x187038['server'])||_0x235676;}else return _0x235676;},_0xf2055['ev']['on'](_0x1f64a7(0x675,0x5b0,0x666,0x53d)+_0x5db3f1(0x4ad,0x4db,0x4d1,0x4aa),_0x50b03f=>{function _0x1bfb42(_0x5dee1e,_0x5768ae,_0x449e6e,_0x2a6be3){return _0x5db3f1(_0x5768ae- -0x591,_0x5768ae-0xc5,_0x449e6e,_0x2a6be3-0xb6);}function _0x201a7e(_0x36feb7,_0x5806a8,_0x5daa1f,_0x585238){return _0x5db3f1(_0x5806a8-0xe7,_0x5806a8-0x193,_0x5daa1f,_0x585238-0x181);}if(_0x2eeff8[_0x1bfb42(-0x8a,-0x153,-0x1f4,-0x1a8)]!==_0x2eeff8[_0x201a7e(0x5bc,0x525,0x4b5,0x4e1)]){const _0x5ec206={};_0x5ec206[_0x1bfb42(-0x109,-0x188,-0x20a,-0x23b)]=_0x1a384c;const _0x14ddab={};_0x14ddab['mentionedJ'+'id']=[_0x258018],_0x2f575e[_0x1bfb42(-0xc9,-0x79,-0x86,-0x12f)+'e'](_0xed6712['id'],{'image':_0x5ec206,'contextInfo':_0x14ddab,'caption':_0x201a7e(0x5d6,0x541,0x591,0x56f)+'\x20'+_0x392a2e['subject']+'\x20@'+_0x1679bd['split']('@')[-0xa3c+-0x61a+-0x2b9*-0x6]});}else for(let _0x322307 of _0x50b03f){let _0x427110=_0xf2055[_0x201a7e(0x5a7,0x572,0x5d3,0x4f3)](_0x322307['id']);if(store&&store['contacts'])store[_0x1bfb42(-0x18a,-0x157,-0x1e7,-0xe0)][_0x427110]={'id':_0x427110,'name':_0x322307['notify']};}}),_0xf2055[_0x1f64a7(0x5f1,0x516,0x493,0x4ed)]=(_0x218e39,_0x5e31f3=![])=>{function _0x465c52(_0x3fd41d,_0x224f0e,_0x58721c,_0x4c7dff){return _0x5db3f1(_0x3fd41d- -0x73,_0x224f0e-0xf1,_0x4c7dff,_0x4c7dff-0x28);}function _0x157f06(_0xaf33d,_0x22ffe1,_0x316d5e,_0x1d0144){return _0x1f64a7(_0x22ffe1,_0x1d0144- -0xc2,_0x316d5e-0x29,_0x1d0144-0x10);}const _0x445d8d={'QCBQy':'6|5|7|4|3|'+_0x157f06(0x49c,0x563,0x443,0x4db),'mtQyL':function(_0x588f79,_0x519e04){return _0x588f79(_0x519e04);},'TJhgC':_0x2eeff8[_0x465c52(0x3ae,0x3fc,0x3db,0x422)],'jOMdN':function(_0x52952f,_0x5c4ae4,_0x4af79c,_0x44a897){function _0x592960(_0xf99c4b,_0x521706,_0x51fb16,_0x17c03d){return _0x465c52(_0x521706-0x144,_0x521706-0x1a9,_0x51fb16-0x22,_0x51fb16);}return _0x2eeff8[_0x592960(0x493,0x4fe,0x534,0x5d4)](_0x52952f,_0x5c4ae4,_0x4af79c,_0x44a897);},'oMOGy':_0x2eeff8[_0x465c52(0x425,0x34b,0x43c,0x430)],'xqHlX':function(_0x4d016d,_0x48d596){return _0x4d016d===_0x48d596;},'opjdS':function(_0x3d0b51,_0x4d68a4){return _0x3d0b51===_0x4d68a4;},'frznD':_0x2eeff8['GliKv'],'vZdrE':function(_0x9d2693,_0x5801f1){function _0x52073f(_0x58604f,_0x2253d5,_0x19ca16,_0x4a826d){return _0x465c52(_0x4a826d-0x227,_0x2253d5-0x38,_0x19ca16-0xa1,_0x19ca16);}return _0x2eeff8[_0x52073f(0x6c8,0x581,0x670,0x65c)](_0x9d2693,_0x5801f1);},'tcGhK':_0x2eeff8['MsRfY'],'NUqlG':function(_0x7c563406,_0x437188){function _0x184261(_0x56d073,_0x351594,_0x47b9f5,_0x25c1f1){return _0x465c52(_0x25c1f1- -0x304,_0x351594-0x1f2,_0x47b9f5-0xab,_0x56d073);}return _0x2eeff8[_0x184261(0x121,0x11b,0x16d,0x176)](_0x7c563406,_0x437188);}};if(_0x2eeff8['QOOOs'](_0x2eeff8[_0x157f06(0x5af,0x534,0x5e2,0x571)],'TdVvR'))_0x269c2e[_0x465c52(0x40a,0x4de,0x3f5,0x372)](_0x57347b);else{id=_0xf2055[_0x157f06(0x407,0x540,0x535,0x4ca)](_0x218e39),_0x5e31f3=_0xf2055[_0x465c52(0x36b,0x2d8,0x34f,0x2ef)+'tact']||_0x5e31f3;let _0x52e623;if(id[_0x157f06(0x646,0x63a,0x622,0x56d)](_0x2eeff8[_0x465c52(0x4d5,0x49d,0x4e7,0x520)]))return new Promise(async _0x435d4c=>{function _0x1764cd(_0x5bad24,_0xb7930f,_0x354e28,_0x51554e){return _0x465c52(_0x5bad24- -0x1a3,_0xb7930f-0x149,_0x354e28-0xbe,_0x354e28);}function _0x1fa1c2(_0x2869af,_0xc04812,_0x2607b0,_0x1a4c99){return _0x465c52(_0xc04812-0x4f,_0xc04812-0x3,_0x2607b0-0x57,_0x2869af);}if(_0x2eeff8[_0x1fa1c2(0x4f4,0x457,0x507,0x4c2)]('XGViB',_0x2eeff8[_0x1fa1c2(0x460,0x3df,0x3da,0x393)])){_0x52e623=store[_0x1764cd(0x224,0x1a1,0x270,0x183)][id]||{};if(!(_0x52e623[_0x1fa1c2(0x433,0x3f8,0x43d,0x42d)]||_0x52e623[_0x1fa1c2(0x485,0x428,0x4a7,0x489)]))_0x52e623=_0xf2055[_0x1fa1c2(0x413,0x44d,0x3f0,0x3d9)+_0x1fa1c2(0x553,0x4d0,0x53e,0x596)](id)||{};_0x2eeff8['udexT'](_0x435d4c,_0x52e623['name']||_0x52e623['subject']||_0x2eeff8[_0x1fa1c2(0x452,0x40c,0x4b8,0x345)](PhoneNumber,_0x2eeff8[_0x1764cd(0x21c,0x1a8,0x15d,0x23c)]('+',id['replace'](_0x2eeff8['jXlLm'],'')))[_0x1764cd(0x205,0x200,0x2df,0x1d4)](_0x2eeff8['UKqEN']));}else{const _0x32348a=_0x445d8d[_0x1fa1c2(0x405,0x471,0x3ba,0x463)][_0x1fa1c2(0x58f,0x4e6,0x4f2,0x44c)]('|');let _0x2c0908=0x1*0x8bf+0x1c1c+-0x24db;while(!![]){switch(_0x32348a[_0x2c0908++]){case'0':_0x445d8d[_0x1764cd(0x30e,0x389,0x27a,0x27b)](_0x53c572,_0x445d8d['TJhgC'])(_0x35dc28,_0x32bd7c,_0x2f8c94,_0x4a2e45);continue;case'1':_0x2d4f39=_0x445d8d[_0x1fa1c2(0x415,0x3a9,0x36a,0x37e)](_0x140e01,_0x4c3ed4,_0x1c8104,_0x461541);continue;case'2':if(_0x4b01bf['key']['id'][_0x1764cd(0x2b4,0x30d,0x259,0x26f)](_0x445d8d[_0x1764cd(0x29c,0x1fb,0x229,0x32c)])&&_0x445d8d[_0x1764cd(0x270,0x27a,0x302,0x2da)](_0x3da295['key']['id']['length'],0x1851+-0x3d*0xb+-0x15a2))return;continue;case'3':if(!_0xabd3a7[_0x1764cd(0x300,0x387,0x3c6,0x35a)]&&!_0x36765e[_0x1764cd(0x325,0x306,0x25f,0x3cf)][_0x1fa1c2(0x45c,0x402,0x369,0x3cd)]&&_0x445d8d[_0x1764cd(0x26e,0x309,0x29c,0x25e)](_0x42486a[_0x1764cd(0x2ba,0x34f,0x282,0x1e2)],_0x445d8d[_0x1764cd(0x2a6,0x35a,0x341,0x36a)]))return;continue;case'4':if(_0x5060d9[_0x1fa1c2(0x580,0x517,0x495,0x489)]&&_0x445d8d[_0x1764cd(0x25c,0x1c6,0x1c0,0x32d)](_0x20438d[_0x1fa1c2(0x538,0x517,0x4fd,0x594)]['remoteJid'],_0x445d8d[_0x1fa1c2(0x34d,0x395,0x3ad,0x341)]))return;continue;case'5':if(!_0x33e8f0[_0x1fa1c2(0x459,0x496,0x482,0x44e)])return;continue;case'6':_0x2ad6a9=_0x19ddd9[_0x1764cd(0x27d,0x222,0x1e7,0x1aa)][0x1f50+-0x4*-0x45e+0x7*-0x6f8];continue;case'7':_0x15f213[_0x1764cd(0x2a4,0x33d,0x324,0x309)]=_0x445d8d['NUqlG'](_0x12613b[_0x1fa1c2(0x431,0x430,0x383,0x46f)](_0x429f68['message'])[-0x4f6+0x1793+-0x129d],'ephemeralM'+'essage')?_0x4503ed['message'][_0x1764cd(0x2b8,0x2d9,0x21b,0x385)+_0x1764cd(0x1f1,0x293,0x24a,0x148)][_0x1764cd(0x2a4,0x2e4,0x2f7,0x27e)]:_0x541e46['message'];continue;}break;}}});else _0x52e623=_0x2eeff8['JEYDW'](id,_0x2eeff8[_0x157f06(0x350,0x3c3,0x3a6,0x3f9)])?{'id':id,'name':'WhatsApp'}:_0x2eeff8['OKhod'](id,_0xf2055[_0x465c52(0x418,0x342,0x4d9,0x46c)](_0xf2055['user']['id']))?_0xf2055[_0x465c52(0x43d,0x42c,0x3e4,0x4e5)]:store['contacts'][id]||{};return(_0x5e31f3?'':_0x52e623[_0x157f06(0x39a,0x4d6,0x51d,0x45b)])||_0x52e623[_0x465c52(0x3d9,0x39c,0x370,0x34d)]||_0x52e623[_0x465c52(0x441,0x45f,0x4b9,0x46e)+'me']||_0x2eeff8[_0x465c52(0x428,0x3a7,0x394,0x47d)](PhoneNumber,_0x2eeff8[_0x465c52(0x367,0x40a,0x2cc,0x36e)]('+',_0x218e39[_0x157f06(0x453,0x4c2,0x4e9,0x4fc)](_0x2eeff8[_0x465c52(0x334,0x381,0x3b9,0x261)],'')))[_0x465c52(0x3a8,0x453,0x417,0x42a)](_0x157f06(0x455,0x4a1,0x460,0x48c)+'nal');}},_0xf2055[_0x1f64a7(0x6ac,0x621,0x661,0x5db)+'t']=async(_0x23940b,_0x406025,_0x321bc7='',_0x374506={})=>{let _0x2ae104=[];for(let _0x39aef8 of _0x406025){_0x2eeff8['ECElO']===_0xaed2a8(0x131,-0x4a,-0x4d,0x5b)?_0x2ae104['push']({'displayName':await _0xf2055[_0xaed2a8(0x158,0xd1,0x6e,0xc0)](_0x2eeff8['bIVvm'](_0x39aef8,_0x2eeff8['jXlLm'])),'vcard':_0x21f515(-0x19a,-0x1a0,-0x126,-0x1d8)+'D\x0aVERSION:'+_0xaed2a8(0x1e2,0x1e6,0x164,0x169)+await _0xf2055[_0x21f515(-0x19b,-0x16e,-0x161,-0x143)](_0x39aef8+_0x2eeff8[_0xaed2a8(-0x1d,0x59,0x2d,0x52)])+_0xaed2a8(0x163,0x6e,0xd4,0xce)+await _0xf2055['getName'](_0x2eeff8[_0x21f515(-0x4b,-0x6f,-0x9c,-0x48)](_0x39aef8,_0x2eeff8[_0xaed2a8(0x45,0xaf,0xbe,0x52)]))+(_0x21f515(-0x114,0x69,-0x51,-0xae)+_0x21f515(-0x10b,0x13,-0x90,-0x74))+_0x39aef8+':'+_0x39aef8+('\x0aitem1.X-A'+_0x21f515(-0x1ca,-0xae,-0x17c,-0xcd)+_0xaed2a8(0x19b,0x115,0x1e9,0x1b3)+_0x21f515(-0x148,-0x1d2,-0x1aa,-0x208)+_0xaed2a8(0x127,0x2e,0x154,0x8d)+_0xaed2a8(0x207,0xf7,0x1ca,0x13a)+'gmail.com\x0a'+_0x21f515(-0x1e2,-0x259,-0x193,-0x153)+_0x21f515(-0x52,-0x102,-0xcb,-0x12a)+_0xaed2a8(0x8f,0x7,0x47,0x7c)+'L:')+global[_0x21f515(-0x1e4,-0x6a,-0x142,-0x98)]+('\x0aitem3.X-A'+_0xaed2a8(0xaa,0x8d,0xe6,0x66)+_0xaed2a8(-0x12,0x1c,0x1f,0xbf)+_0x21f515(-0x131,-0x102,-0xb0,-0x160)+_0x21f515(-0x4f,-0x55,-0xfa,-0xdb)+_0x21f515(-0x14b,-0xfa,-0xe2,-0x18)+'BLabel:Reg'+_0x21f515(-0x1d1,-0x1f7,-0x11f,-0x169)+_0xaed2a8(0x238,0x1fd,0x245,0x16c))},{'displayName':await _0xf2055[_0xaed2a8(0x79,0x15d,0x59,0xc0)](_0x21f515(0x46,0x61,-0x41,-0xa3)+'054@s.what'+'sapp.net'),'vcard':_0x21f515(-0xc6,-0xa0,-0x126,-0xdc)+_0xaed2a8(0x190,0x108,0x132,0xba)+_0xaed2a8(0xc3,0xdd,-0x13,0xa7)+_0xaed2a8(0xfb,0x15a,0xb0,0x119)+_0xaed2a8(0x8,0x88,0x11,0x81)+'.TEL;waid='+_0xaed2a8(0x10e,0x1e5,0x1e1,0x1e0)+_0x21f515(-0x153,-0x170,-0x12e,-0xec)+_0x21f515(-0x7b,-0x63,-0x4f,-0xf5)+'em1.X-ABLa'+_0xaed2a8(0x2dc,0x272,0x290,0x203)+_0x21f515(-0xf3,-0x1c1,-0x139,-0x200)+'IL;type=IN'+'TERNET:san'+_0x21f515(0x30,-0x131,-0xa4,-0x115)+'gmail.com\x0a'+_0x21f515(-0xe7,-0x136,-0x193,-0x180)+_0xaed2a8(0x224,0x184,0xd5,0x156)+'l\x0aitem3.UR'+'L:https://'+_0x21f515(-0xe2,-0x39,-0x8f,-0x1f)+_0x21f515(-0xb6,-0x1ba,-0x190,-0x106)+_0xaed2a8(0x285,0x11f,0x271,0x1ac)+_0xaed2a8(0x74,0x116,0x160,0xe2)+_0x21f515(-0x96,-0x14a,-0x15f,-0x15d)+_0x21f515(-0x63,-0xb5,-0x1a,-0xd2)+_0x21f515(-0xc6,-0xec,-0x152,-0xa5)+_0xaed2a8(0xe0,-0x4d,0xf3,0x62)+'ABLabel:Re'+'gion\x0aEND:V'+'CARD'}):_0x7ceabc=_0x1cd915[_0xaed2a8(0x1e0,0x1f4,0x7c,0x148)]([_0x77b402,_0x465526]);}function _0xaed2a8(_0x103461,_0x409b71,_0x691ef8,_0x30ef14){return _0x5db3f1(_0x30ef14- -0x355,_0x409b71-0x1a9,_0x103461,_0x30ef14-0x1ea);}function _0x21f515(_0x35b36e,_0x5680dc,_0x29c494,_0x100c0d){return _0x1f64a7(_0x5680dc,_0x29c494- -0x677,_0x29c494-0x178,_0x100c0d-0x193);}const _0x417928={};_0x417928[_0x21f515(-0x1f7,-0x139,-0x135,-0x1c9)+'e']=_0x2ae104[_0x21f515(-0x11a,-0x88,-0x6f,0x67)]+'\x20Kontak',_0x417928[_0xaed2a8(0x159,0x63,0x13d,0xe5)]=_0x2ae104;const _0x509080={'contacts':_0x417928,..._0x374506},_0x548b64={};_0x548b64['quoted']=_0x321bc7,_0xf2055[_0x21f515(-0xd9,-0x48,-0x5e,0x6c)+'e'](_0x23940b,_0x509080,_0x548b64);},_0xf2055[_0x1f64a7(0x44f,0x4c4,0x426,0x57f)]=_0x5f2a5e=>{function _0x59e37b(_0x429b46,_0x2e5689,_0x12e9e4,_0x5f5271){return _0x5db3f1(_0x429b46- -0x412,_0x2e5689-0x127,_0x5f5271,_0x5f5271-0x14e);}const _0x2ab671={};_0x2ab671['to']=_0x2eeff8['jXlLm'],_0x2ab671[_0x59e37b(0xbe,0x14,0x165,0xb8)]=_0x48e835(0x35b,0x35d,0x284,0x2fc);function _0x48e835(_0xc0d348,_0x51defa,_0x131bcc,_0x317801){return _0x1f64a7(_0x51defa,_0x131bcc- -0x33d,_0x131bcc-0xeb,_0x317801-0xad);}return _0x2ab671['xmlns']='status',_0xf2055[_0x59e37b(0xc,-0x51,0x74,-0x36)]({'tag':'iq','attrs':_0x2ab671,'content':[{'tag':_0x2eeff8[_0x48e835(0x191,0x23d,0x250,0x2f9)],'attrs':{},'content':Buffer['from'](_0x5f2a5e,_0x2eeff8['vCLwg'])}]}),_0x5f2a5e;},_0xf2055[_0x1f64a7(0x570,0x617,0x6a9,0x64c)]=!![],_0xf2055[_0x5db3f1(0x46b,0x51d,0x3d0,0x4d5)]=_0x50df04=>smsg(_0xf2055,_0x50df04,store),_0xf2055['ev']['on'](_0x2eeff8[_0x5db3f1(0x467,0x399,0x4e3,0x47e)],async _0x1e744d=>{function _0x4d9cd7(_0x57123f,_0x3e95f7,_0x3df6c1,_0x368266){return _0x1f64a7(_0x3df6c1,_0x3e95f7- -0x590,_0x3df6c1-0x1a0,_0x368266-0x104);}const _0x5519f9={'ZWGpu':function(_0x5dacd9,_0x30c5b6){return _0x2eeff8['CbNop'](_0x5dacd9,_0x30c5b6);},'iFifM':function(_0x2b5bd1,_0x1641a5){function _0x3a9301(_0x50a21d,_0x1c8393,_0x3d0edb,_0x55610f){return _0x4a2e(_0x50a21d-0x27a,_0x3d0edb);}return _0x2eeff8[_0x3a9301(0x492,0x495,0x4cf,0x41d)](_0x2b5bd1,_0x1641a5);},'MQnmI':_0x2eeff8[_0x53b0d7(0x2a2,0x2e2,0x2ed,0x2ad)],'JZDKC':_0x2eeff8[_0x4d9cd7(0x47,0xb9,0x18c,0x53)],'yaEku':function(_0xb67290,_0x3f6aa2){return _0xb67290===_0x3f6aa2;},'mHFxs':_0x2eeff8[_0x53b0d7(0x106,0x91,0xbc,0x153)],'eQKOC':function(_0x53837c,_0x1258c0){return _0x53837c(_0x1258c0);},'AyMSl':_0x2eeff8['jXlLm']};function _0x53b0d7(_0x574fd0,_0x1177ea,_0x24db97,_0x5b2151){return _0x5db3f1(_0x574fd0- -0x2b4,_0x1177ea-0x8b,_0x5b2151,_0x5b2151-0x7a);}const {connection:_0x57ab16,lastDisconnect:_0x21c8e1}=_0x1e744d;if(_0x2eeff8['nxKQa'](_0x57ab16,_0x2eeff8[_0x53b0d7(0x1b2,0x186,0x143,0x146)])){if(_0x2eeff8[_0x4d9cd7(0x100,0x5e,0x97,0xfd)](_0x2eeff8[_0x53b0d7(0x14e,0x1a1,0x174,0x1ac)],_0x2eeff8[_0x4d9cd7(0x2d,-0x8d,-0xeb,-0x20)])){let _0x4edd46=_0x21c8e1[_0x53b0d7(0x1dc,0x130,0x178,0x29a)]?_0x21c8e1?.[_0x4d9cd7(-0x5a,0x1,0x20,0x28)]?.['output'][_0x53b0d7(0x15a,0xd8,0xd7,0x124)]:0x3*-0xbc4+0x4f4+0xf2c*0x2;if(_0x2eeff8['xLqXk'](_0x4edd46,DisconnectReason[_0x4d9cd7(0xc4,0x76,0x114,0x7c)]))_0x2eeff8[_0x53b0d7(0x1e6,0x18e,0x192,0x1b3)]!==_0x2eeff8[_0x4d9cd7(0xb,0xb,0x83,0x10)]?_0x2d75d2=_0x53b0d7(0x1f0,0x13e,0x28a,0x177)+_0x4d9cd7(0x91,-0x2b,0x50,-0xec)+_0x4d9cd7(0x4b,0x4e,0xb1,0xcd)+_0x4d9cd7(0x13,0x67,0xbe,0xc3)+'ontent/upl'+_0x4d9cd7(0x4d,0xf,-0x9b,0x32)+_0x53b0d7(0x1ac,0x1fb,0x19b,0x1ce)+'bar-Foto-P'+_0x53b0d7(0x1ff,0x2d2,0x1dd,0x258)+'ng-Lucu-Te'+_0x4d9cd7(0x10,0x9b,0x81,0x2b)+'g':(console[_0x4d9cd7(0xae,-0x12,-0x69,0x9e)](_0x4d9cd7(0x3a,0x63,-0x41,0xbd)+'n\x20File,\x20Pl'+_0x4d9cd7(0x22,-0x18,0x49,-0xa8)+_0x4d9cd7(-0xae,-0xb8,-0xd8,-0x16)+_0x53b0d7(0x137,0x1fe,0x178,0x13a)+_0x53b0d7(0x272,0x2c2,0x260,0x2b5)),process[_0x4d9cd7(0x1f,-0x68,0x5a,-0x27)]());else{if(_0x2eeff8['uhJRW'](_0x4edd46,DisconnectReason[_0x4d9cd7(0xc,0x50,-0xb,0x74)+_0x53b0d7(0x28c,0x1de,0x237,0x1ed)]))console[_0x4d9cd7(-0x4,-0x12,-0x9f,-0xc5)](_0x2eeff8[_0x53b0d7(0x114,0x75,0xfd,0xa5)]),_0x2eeff8[_0x4d9cd7(-0x49,-0xa,0x77,-0xd4)](startHisoka);else{if(_0x2eeff8[_0x53b0d7(0x1f4,0x18e,0x17c,0x15d)](_0x4edd46,DisconnectReason[_0x4d9cd7(0xd,0x50,0x71,-0x8a)+_0x4d9cd7(0x10b,0x42,0xd1,-0x58)])){if(_0x2eeff8[_0x53b0d7(0x288,0x1dc,0x224,0x22e)](_0x2eeff8[_0x4d9cd7(0x5d,0x6f,0x132,0x45)],_0x2eeff8[_0x53b0d7(0x121,0x13e,0x77,0x181)])){_0x5dca5e=_0x2ff15e[_0x53b0d7(0x186,0xd5,0x1cd,0x1b6)][_0x1f1635]||{};if(!(_0x5b9a8c[_0x53b0d7(0x168,0xab,0x17f,0x1e9)]||_0x10b3cd[_0x4d9cd7(0x4a,-0x43,0x31,-0x97)]))_0x572d43=_0x56023f['groupMetad'+_0x53b0d7(0x240,0x2c8,0x286,0x230)](_0x43ddce)||{};_0x2a1de5(_0x51f8c9['name']||_0x22654f[_0x4d9cd7(-0x6,-0x43,0x63,0x5e)]||_0x2eeff8[_0x53b0d7(0x17c,0x190,0x19b,0x152)](_0x54087b,'+'+_0x3061fc[_0x4d9cd7(0xd9,0x2e,0x2f,-0x6d)](_0x2eeff8['jXlLm'],''))[_0x4d9cd7(-0x11d,-0x74,0x47,0x48)](_0x2eeff8[_0x4d9cd7(0x28,0xc7,0x185,0x131)]));}else console[_0x53b0d7(0x1c9,0x266,0x213,0x1f6)](_0x2eeff8[_0x4d9cd7(-0x31,-0x3a,-0xbd,0x6a)]),_0x2eeff8[_0x4d9cd7(0x80,0x40,-0x79,0xd7)](startHisoka);}else{if(_0x4edd46===DisconnectReason[_0x53b0d7(0x22b,0x2a4,0x1e4,0x2d4)+'Replaced'])console[_0x53b0d7(0x1c9,0x130,0x1e9,0x252)](_0x2eeff8[_0x4d9cd7(-0xed,-0x7e,0x48,-0xe0)]),process[_0x53b0d7(0x173,0x1ee,0x1c3,0x10a)]();else{if(_0x4edd46===DisconnectReason[_0x4d9cd7(-0x8f,-0x67,-0x58,0xf)])_0x2eeff8[_0x53b0d7(0x1cd,0x166,0x250,0x112)](_0x4d9cd7(-0x1c,-0x8e,-0x9f,0x19),_0x2eeff8['SVzqO'])?_0x2ca178=_0x382b1d[_0x4d9cd7(0x7b,0xe,0x35,0xe5)]([_0x3014d6,_0x37a500]):(console['log'](_0x4d9cd7(-0x88,-0x39,-0xd5,-0x20)+_0x4d9cd7(0x5c,0x29,0x66,0xd1)+_0x53b0d7(0x15c,0xe6,0x1b9,0x1ea)+_0x4d9cd7(-0x15d,-0xc6,-0x72,-0x115)+'\x20and\x20Scan\x20'+'Again.'),process[_0x4d9cd7(-0x78,-0x68,-0xe3,0x41)]());else{if(_0x2eeff8[_0x53b0d7(0x299,0x2e3,0x26d,0x288)](_0x4edd46,DisconnectReason['restartReq'+_0x53b0d7(0x10c,0xf0,0x166,0xa7)]))_0x2eeff8[_0x4d9cd7(-0x72,0x46,0x8e,0x11b)]===_0x2eeff8[_0x53b0d7(0x1de,0x161,0x29a,0x2ae)]?_0x3316bb[_0x53b0d7(0x1c9,0x243,0x119,0x173)](_0x171ff0):(console[_0x4d9cd7(-0x60,-0x12,-0xb4,0xc3)](_0x2eeff8[_0x4d9cd7(-0x7,0xa0,0xa5,-0x2f)]),_0x2eeff8[_0x4d9cd7(0x5f,-0x3d,-0x6f,0x14)](startHisoka));else _0x2eeff8[_0x4d9cd7(0x4,0x3d,0x78,-0x54)](_0x4edd46,DisconnectReason[_0x4d9cd7(-0xe8,-0xa6,-0x1c,0x26)])?(console['log'](_0x2eeff8[_0x4d9cd7(0x40,-0x33,-0xfe,0x4f)]),_0x2eeff8[_0x4d9cd7(0x74,-0x3e,0x7e,-0x10c)](startHisoka)):console[_0x4d9cd7(-0x45,-0x12,0x77,-0x38)]('Unknown\x20Di'+_0x4d9cd7(-0x2f,-0x48,-0xd5,-0x56)+_0x53b0d7(0x20b,0x249,0x208,0x22f)+_0x4edd46+'|'+_0x57ab16);}}}}}}else{_0x54e731=_0x5ef091[_0x53b0d7(0x1d7,0x10a,0x230,0x1ae)](_0x3e9697),_0x5b1f0a=_0x29ce9c['withoutCon'+_0x53b0d7(0xff,0x55,0xca,0xea)]||_0x4f781a;let _0x10f22c;const _0x4de90e={};_0x4de90e['id']=_0x12259f,_0x4de90e[_0x4d9cd7(0xf,-0x73,-0x1f,-0x2e)]=_0x4d9cd7(0x54,0x8f,0x52,0x2e);if(_0x511d45['endsWith'](_0x5519f9['JZDKC']))return new _0x20aa9c(async _0x2f6e9a=>{function _0xf868b(_0x300091,_0x28ab05,_0x4c6eac,_0x1d1d64){return _0x53b0d7(_0x28ab05-0x3d4,_0x28ab05-0x191,_0x4c6eac-0x116,_0x4c6eac);}_0x10f22c=_0x244a70[_0xf868b(0x4c8,0x55a,0x5f8,0x50d)][_0x13e460]||{};if(!(_0x10f22c[_0x9ca1ff(0x2e9,0x30d,0x310,0x304)]||_0x10f22c[_0x9ca1ff(0x32a,0x39e,0x340,0x3ec)]))_0x10f22c=_0x22b24c[_0xf868b(0x532,0x591,0x529,0x534)+_0xf868b(0x6d5,0x614,0x54a,0x607)](_0x1b115a)||{};function _0x9ca1ff(_0x4d0c05,_0x426c81,_0x2576b4,_0x13278e){return _0x53b0d7(_0x2576b4-0x1a8,_0x426c81-0x122,_0x2576b4-0x1a4,_0x426c81);}_0x5519f9[_0xf868b(0x5e9,0x658,0x65a,0x5ee)](_0x2f6e9a,_0x10f22c[_0x9ca1ff(0x2b5,0x2cd,0x310,0x2b1)]||_0x10f22c[_0x9ca1ff(0x348,0x2a1,0x340,0x29e)]||_0x5519f9[_0xf868b(0x60c,0x658,0x698,0x691)](_0x17129c,_0x5519f9[_0xf868b(0x548,0x4cd,0x47a,0x51f)]('+',_0x14da2c['replace'](_0xf868b(0x4cd,0x4c9,0x579,0x525)+_0xf868b(0x4e0,0x520,0x4fd,0x4d1),'')))[_0xf868b(0x5f6,0x53b,0x564,0x578)](_0x5519f9[_0x9ca1ff(0x29f,0x265,0x2b1,0x361)]));});else _0x10f22c=_0x5519f9[_0x4d9cd7(-0xe3,-0xa1,0x20,-0xba)](_0x6533e4,_0x5519f9[_0x53b0d7(0x1b4,0x189,0x1d0,0x12f)])?_0x4de90e:_0x4526d8===_0x32bc52[_0x4d9cd7(0x24,-0x4,0x11,-0x12)](_0x48d77c[_0x4d9cd7(0x3d,0x21,0x25,0xee)]['id'])?_0x168a45[_0x53b0d7(0x1fc,0x1a0,0x1d6,0x1f4)]:_0x47e670['contacts'][_0x172688]||{};return(_0x5d1766?'':_0x10f22c['name'])||_0x10f22c['subject']||_0x10f22c[_0x53b0d7(0x200,0x207,0x256,0x17c)+'me']||_0x5519f9['eQKOC'](_0x20b512,'+'+_0x54faae[_0x4d9cd7(-0x72,0x2e,-0xa6,-0x4e)](_0x5519f9['AyMSl'],''))[_0x53b0d7(0x167,0x120,0x102,0x116)]('internatio'+'nal');}}console[_0x53b0d7(0x1c9,0x1fd,0x163,0x119)]('Connected.'+'..',_0x1e744d);}),_0xf2055['ev']['on'](_0x2eeff8[_0x1f64a7(0x55a,0x583,0x502,0x4d1)],saveState),_0xf2055['send5ButIm'+'g']=async(_0x1fca77,_0x9ef43e='',_0x35baa7='',_0x3ac8d3,_0x3fec75=[],_0x643f25={})=>{const _0xd1ece8={};_0xd1ece8[_0x520ec5(0x4e5,0x5d0,0x545,0x49d)]=_0x3ac8d3;const _0x486b22={};_0x486b22[_0x2136ab(0x22e,0x1ea,0x1be,0x1c1)]=_0xf2055[_0x520ec5(0x52c,0x570,0x4ac,0x4b7)+'Server'];let _0x1a65d9=await _0x2eeff8['SGAps'](prepareWAMessageMedia,_0xd1ece8,_0x486b22);const _0x334b37={};function _0x2136ab(_0x3b5911,_0x2bbb82,_0x4ab341,_0x2d1514){return _0x5db3f1(_0x3b5911- -0x1bc,_0x2bbb82-0x1f2,_0x2bbb82,_0x2d1514-0xc2);}_0x334b37['imageMessa'+'ge']=_0x1a65d9[_0x520ec5(0x4cb,0x475,0x533,0x572)+'ge'];function _0x520ec5(_0x8d6e09,_0x4f78b9,_0x5d9a84,_0x18e00d){return _0x5db3f1(_0x5d9a84-0xbd,_0x4f78b9-0x1d7,_0x4f78b9,_0x18e00d-0xdd);}_0x334b37[_0x520ec5(0x455,0x579,0x4dd,0x4a1)+_0x2136ab(0x26f,0x282,0x1e1,0x2d2)]=_0x9ef43e,_0x334b37[_0x2136ab(0x256,0x1cf,0x1e4,0x220)+_0x520ec5(0x476,0x5db,0x507,0x443)]=_0x35baa7,_0x334b37['hydratedBu'+'ttons']=_0x3fec75;const _0xfa159={};_0xfa159[_0x2136ab(0x2f2,0x3a9,0x3c8,0x2e3)+'mplate']=_0x334b37;const _0x9ca9b8={};_0x9ca9b8[_0x2136ab(0x275,0x29a,0x204,0x2b4)+_0x2136ab(0x308,0x38e,0x35e,0x2a7)]=_0xfa159;var _0x3c5394=_0x2eeff8[_0x2136ab(0x271,0x268,0x32e,0x30e)](generateWAMessageFromContent,m[_0x520ec5(0x5a1,0x514,0x540,0x5e7)],proto[_0x2136ab(0x231,0x264,0x1ff,0x2f0)]['fromObject'](_0x9ca9b8),_0x643f25);_0xf2055[_0x2136ab(0x2e4,0x2a7,0x341,0x2d4)+'ge'](_0x1fca77,_0x3c5394[_0x520ec5(0x52f,0x62b,0x577,0x5f7)],{'messageId':_0x3c5394[_0x520ec5(0x527,0x67c,0x5f8,0x54b)]['id']});},_0xf2055[_0x1f64a7(0x5b6,0x62a,0x6cb,0x702)+'Text']=(_0x113da0,_0x2f7b48=[],_0x2c9488,_0x5923c1,_0x5613f2='',_0x4e261f={})=>{function _0x46d971(_0x5cd563,_0x452432,_0x4d1051,_0x55ae5c){return _0x5db3f1(_0x452432-0x176,_0x452432-0x10c,_0x4d1051,_0x55ae5c-0x19a);}const _0x346298={'DEzGl':_0x46d971(0x5d8,0x644,0x59f,0x5e9)+'essage','ronni':function(_0x2cd9b2,_0x393b06){return _0x2eeff8['YbPLC'](_0x2cd9b2,_0x393b06);},'lAkvj':'string','kwiEZ':function(_0x5832b6,_0x32870f){function _0x57686b(_0x27d860,_0xfe0079,_0x3e3532,_0x2994a5){return _0x46d971(_0x27d860-0x75,_0x27d860- -0x2c9,_0x3e3532,_0x2994a5-0x83);}return _0x2eeff8[_0x57686b(0x29d,0x31d,0x2e1,0x34c)](_0x5832b6,_0x32870f);},'TbtTy':_0x2eeff8[_0x3f2715(0x40b,0x347,0x3c5,0x358)],'JEFMs':_0x2eeff8[_0x46d971(0x537,0x5ac,0x528,0x579)]};function _0x3f2715(_0x1c023c,_0x25429b,_0x32000a,_0x36c644){return _0x5db3f1(_0x32000a-0x1e,_0x25429b-0x2c,_0x36c644,_0x36c644-0x1db);}if(_0x2eeff8[_0x3f2715(0x5cc,0x4a4,0x579,0x52d)](_0x2eeff8['pLVmE'],_0x3f2715(0x506,0x4e1,0x524,0x4b2))){const _0x206bf7={'text':_0x2c9488,'footer':_0x5923c1,'buttons':_0x2f7b48,'headerType':0x2,..._0x4e261f};let _0x1efb3d=_0x206bf7;const _0x5e7a47={'quoted':_0x5613f2,..._0x4e261f};_0xf2055[_0x46d971(0x6a7,0x68e,0x6af,0x630)+'e'](_0x113da0,_0x1efb3d,_0x5e7a47);}else{let _0xb9be4e=_0x40461d[_0x3f2715(0x49d,0x3ef,0x472,0x4e5)](_0x4f924c[_0x3f2715(0x4d5,0x469,0x4d8,0x4e8)])[-0x99*0x3+0x672+0x4a7*-0x1],_0x38fc47=_0xb9be4e===_0x346298['DEzGl'];_0x38fc47&&(_0xb9be4e=_0x50eb5d[_0x46d971(0x67f,0x5ca,0x587,0x624)](_0x42ed80[_0x3f2715(0x404,0x559,0x4d8,0x535)][_0x46d971(0x6fa,0x644,0x5cb,0x71f)+_0x46d971(0x565,0x57d,0x59c,0x5bf)]['message'])[0x4*-0x923+0x1*-0x543+-0x5f9*-0x7]);let _0x84c999=_0x38fc47?_0x3f2d67[_0x46d971(0x60e,0x630,0x61a,0x607)][_0x3f2715(0x508,0x5bf,0x4ec,0x42e)+_0x46d971(0x641,0x57d,0x56c,0x4fb)][_0x3f2715(0x4b7,0x41d,0x4d8,0x46c)]:_0x4e72b6['message'],_0x32342a=_0x84c999[_0xb9be4e];if(_0x346298[_0x3f2715(0x569,0x4ae,0x497,0x3fc)](typeof _0x32342a,_0x346298['lAkvj']))_0x84c999[_0xb9be4e]=_0x2b8b1e||_0x32342a;else{if(_0x32342a[_0x46d971(0x54a,0x555,0x582,0x4b2)])_0x32342a[_0x46d971(0x487,0x555,0x5d4,0x614)]=_0x217989||_0x32342a[_0x3f2715(0x3ad,0x3f5,0x3fd,0x36d)];else{if(_0x32342a[_0x46d971(0x5d3,0x622,0x6d6,0x591)])_0x32342a[_0x3f2715(0x4b0,0x549,0x4ca,0x40b)]=_0x444db4||_0x32342a[_0x3f2715(0x506,0x502,0x4ca,0x425)];}}if(_0x346298['kwiEZ'](typeof _0x32342a,_0x346298[_0x46d971(0x70e,0x693,0x720,0x711)]))_0x84c999[_0xb9be4e]={..._0x32342a,..._0x3bfa90};if(_0x3c6392[_0x3f2715(0x572,0x5ea,0x559,0x5c0)][_0x46d971(0x6d4,0x691,0x604,0x715)+'t'])_0x1e8717=_0xa6cfd9[_0x3f2715(0x4be,0x578,0x559,0x4ca)][_0x46d971(0x706,0x691,0x5dd,0x698)+'t']=_0x395344||_0x1f01e1[_0x46d971(0x61e,0x6b1,0x738,0x668)][_0x3f2715(0x54f,0x503,0x539,0x502)+'t'];else{if(_0x11ce7f['key'][_0x46d971(0x760,0x691,0x6ce,0x64e)+'t'])_0x157a2f=_0x54f5ab[_0x3f2715(0x525,0x4a6,0x559,0x56f)][_0x3f2715(0x4ef,0x49f,0x539,0x4e3)+'t']=_0x153844||_0x448f9b[_0x3f2715(0x60e,0x5f0,0x559,0x52d)][_0x3f2715(0x5f4,0x581,0x539,0x50c)+'t'];}if(_0xbd3843[_0x46d971(0x70e,0x6b1,0x62c,0x781)][_0x46d971(0x5e9,0x56e,0x4f8,0x553)][_0x3f2715(0x4ff,0x554,0x4e1,0x470)](_0x346298[_0x3f2715(0x493,0x462,0x4f7,0x4f1)]))_0xc41720=_0x1531c3||_0x233f1['key']['remoteJid'];else{if(_0x5ca8fd['key'][_0x3f2715(0x3f1,0x3bd,0x416,0x436)][_0x3f2715(0x589,0x4d7,0x4e1,0x430)](_0x346298[_0x3f2715(0x4ec,0x529,0x457,0x3dd)]))_0x21e158=_0x553c60||_0x149bfb[_0x3f2715(0x55a,0x5b2,0x559,0x4a6)]['remoteJid'];}return _0x1f76b1[_0x3f2715(0x510,0x5bb,0x559,0x4d7)][_0x46d971(0x5ef,0x56e,0x49c,0x5ff)]=_0x582c8d,_0x3b7195[_0x3f2715(0x49a,0x5cc,0x559,0x50b)][_0x3f2715(0x3ee,0x455,0x444,0x450)]=_0x346298[_0x3f2715(0x3d5,0x4b3,0x497,0x445)](_0x2ff63c,_0x244d32[_0x3f2715(0x463,0x49a,0x4ce,0x505)]['id']),_0x4b6351['WebMessage'+'Info'][_0x3f2715(0x4b8,0x46e,0x41d,0x3d6)](_0x312d86);}},_0xf2055['sendText']=(_0x57ae49,_0xc839ac,_0xd9a4ae='',_0x39a5f9)=>_0xf2055[_0x5db3f1(0x518,0x492,0x4cf,0x45a)+'e'](_0x57ae49,{'text':_0xc839ac,..._0x39a5f9},{'quoted':_0xd9a4ae}),_0xf2055[_0x5db3f1(0x4d3,0x56d,0x594,0x43c)]=async(_0x2469b0,_0x279474,_0x2ffa90='',_0x290661='',_0x424abf)=>{function _0x904080(_0xef9fa,_0x26a069,_0xdae042,_0x5ea247){return _0x5db3f1(_0x26a069- -0x456,_0x26a069-0x80,_0x5ea247,_0x5ea247-0x86);}function _0xbf9741(_0x38faea,_0x2665e7,_0x463280,_0x29f98f){return _0x1f64a7(_0x463280,_0x29f98f- -0x5ca,_0x463280-0xc,_0x29f98f-0x194);}if(_0x2eeff8['FadQg'](_0x904080(-0x10,-0xae,-0xd7,-0xd5),_0xbf9741(-0x63,0x31,-0x7f,-0x68)))_0x1ef395[_0xbf9741(0x8e,-0x52,-0x73,-0x4c)](_0x2eeff8[_0xbf9741(-0x142,-0x8f,-0xca,-0x74)]),_0x2eeff8['ZrUEQ'](_0xda4770);else{let _0x4d607f=Buffer[_0xbf9741(-0x180,-0x13a,-0x15a,-0xed)](_0x279474)?_0x279474:/^data:.*?\/.*?;base64,/i['test'](_0x279474)?Buffer['from'](_0x279474['split']`,`[0x269f*0x1+-0x17e*0x19+-0x150],_0x2eeff8['FpsNm']):/^https?:\/\//['test'](_0x279474)?await await _0x2eeff8['YsCMC'](getBuffer,_0x279474):fs['existsSync'](_0x279474)?fs[_0xbf9741(-0x22,0x3a,-0x1e,0x68)+'nc'](_0x279474):Buffer[_0xbf9741(-0xfb,-0x6c,-0x11d,-0x5d)](0x1473+0x1*0xef+-0x1562);const _0x50b7e9={'image':_0x4d607f,'caption':_0x2ffa90,..._0x424abf},_0x1e57aa={};return _0x1e57aa['quoted']=_0x290661,await _0xf2055[_0x904080(0x98,0xc2,0xa8,0xa1)+'e'](_0x2469b0,_0x50b7e9,_0x1e57aa);}},_0xf2055[_0x1f64a7(0x65d,0x5ec,0x537,0x670)]=async(_0x1d947b,_0x21f251,_0xe331bf='',_0x40b63a='',_0x50f49e=![],_0x15520d)=>{let _0x2d23fb=Buffer['isBuffer'](_0x21f251)?_0x21f251:/^data:.*?\/.*?;base64,/i[_0x5bc2a0(0x42c,0x3fa,0x419,0x3d6)](_0x21f251)?Buffer[_0x238286(0x395,0x312,0x3ce,0x26d)](_0x21f251[_0x238286(0x2c1,0x2bf,0x2ad,0x2c2)]`,`[0x9*0x238+-0x8ba+-0x15*0x89],_0x2eeff8[_0x5bc2a0(0x2e1,0x392,0x385,0x395)]):/^https?:\/\//['test'](_0x21f251)?await await _0x2eeff8[_0x5bc2a0(0x401,0x3c2,0x46c,0x3b6)](getBuffer,_0x21f251):fs[_0x5bc2a0(0x336,0x2fe,0x333,0x337)](_0x21f251)?fs[_0x5bc2a0(0x43b,0x3ef,0x453,0x4ac)+'nc'](_0x21f251):Buffer[_0x5bc2a0(0x42f,0x49f,0x3d7,0x3e7)](0x2273+-0x1*0x1879+-0x9fa);const _0xb0a27a={'video':_0x2d23fb,'caption':_0xe331bf,'gifPlayback':_0x50f49e,..._0x15520d},_0x5eb3ff={};function _0x5bc2a0(_0x2e2387,_0x486773,_0xb6804f,_0x5186e9){return _0x1f64a7(_0x2e2387,_0x5186e9- -0x186,_0xb6804f-0x1c2,_0x5186e9-0xd6);}function _0x238286(_0x308e6e,_0x314882,_0x24a1d4,_0x40289){return _0x1f64a7(_0x24a1d4,_0x314882- -0x34c,_0x24a1d4-0x116,_0x40289-0x1f4);}return _0x5eb3ff['quoted']=_0x40b63a,await _0xf2055[_0x5bc2a0(0x4dc,0x4b5,0x486,0x493)+'e'](_0x1d947b,_0xb0a27a,_0x5eb3ff);},_0xf2055[_0x1f64a7(0x67e,0x64f,0x674,0x60f)]=async(_0x431c11,_0x1d67bb,_0x2398df='',_0x2524ed=![],_0x46536b)=>{function _0x7bd919(_0x2545aa,_0x3b8e07,_0x1fb1b9,_0x24dccc){return _0x1f64a7(_0x2545aa,_0x1fb1b9- -0xc4,_0x1fb1b9-0x160,_0x24dccc-0x178);}let _0x5cb6fd=Buffer[_0x21381b(0x3b5,0x392,0x35f,0x460)](_0x1d67bb)?_0x1d67bb:/^data:.*?\/.*?;base64,/i[_0x21381b(0x434,0x4d3,0x3a4,0x47f)](_0x1d67bb)?Buffer[_0x21381b(0x536,0x5e0,0x4ae,0x5fc)](_0x1d67bb[_0x21381b(0x4e3,0x474,0x520,0x42a)]`,`[-0xdbe+-0x1c*-0x68+0x25f],_0x2eeff8[_0x7bd919(0x4a3,0x38b,0x457,0x43b)]):/^https?:\/\//[_0x7bd919(0x412,0x3ff,0x498,0x436)](_0x1d67bb)?await await getBuffer(_0x1d67bb):fs['existsSync'](_0x1d67bb)?fs['readFileSy'+'nc'](_0x1d67bb):Buffer[_0x7bd919(0x461,0x550,0x4a9,0x3ec)](0xe44+-0x19d3*-0x1+-0x2817);function _0x21381b(_0x1021ec,_0x2b1d72,_0x2eb5cc,_0x4b42ab){return _0x5db3f1(_0x1021ec- -0x27,_0x2b1d72-0xfc,_0x2b1d72,_0x4b42ab-0x1a4);}const _0x439480={'audio':_0x5cb6fd,'ptt':_0x2524ed,..._0x46536b},_0x5d77e5={};return _0x5d77e5[_0x7bd919(0x42a,0x387,0x455,0x3c3)]=_0x2398df,await _0xf2055[_0x21381b(0x4f1,0x42d,0x503,0x4f4)+'e'](_0x431c11,_0x439480,_0x5d77e5);},_0xf2055['sendTextWi'+'thMentions']=async(_0x88537,_0xd59185,_0x3bf23e,_0x543db2={})=>_0xf2055['sendMessag'+'e'](_0x88537,{'text':_0xd59185,'contextInfo':{'mentionedJid':[..._0xd59185[_0x5db3f1(0x4f8,0x4d8,0x447,0x541)](/@(\d{0,16})/g)]['map'](_0x3f40d7=>_0x3f40d7[-0x275*-0x5+-0x14eb+-0x3*-0x2e1]+(_0x1f64a7(0x471,0x4aa,0x404,0x4c8)+'p.net'))},..._0x543db2},{'quoted':_0x3bf23e}),_0xf2055[_0x1f64a7(0x4b4,0x588,0x4cd,0x604)+_0x1f64a7(0x5fd,0x563,0x5bc,0x55b)]=async(_0xc5a43f,_0x2b15eb,_0x136a04,_0xc1cf5d={})=>{let _0x50e170=Buffer[_0x5eda10(0x55f,0x620,0x588,0x606)](_0x2b15eb)?_0x2b15eb:/^data:.*?\/.*?;base64,/i[_0x3cf7b9(-0x78,-0x127,-0xad,-0x38)](_0x2b15eb)?Buffer[_0x3cf7b9(0x8a,0x31,0x134,0x146)](_0x2b15eb[_0x5eda10(0x68d,0x5b6,0x70c,0x729)]`,`[0x697+-0x1e8b+0x17f5],_0x2eeff8['FpsNm']):/^https?:\/\//[_0x5eda10(0x5de,0x645,0x552,0x530)](_0x2b15eb)?await await _0x2eeff8['udexT'](getBuffer,_0x2b15eb):fs[_0x5eda10(0x53f,0x488,0x58c,0x4a4)](_0x2b15eb)?fs['readFileSy'+'nc'](_0x2b15eb):Buffer['alloc'](-0x1f2e+-0x19f8+0x3926);function _0x5eda10(_0x43089e,_0x294549,_0x309815,_0x2d5c46){return _0x1f64a7(_0x294549,_0x43089e-0x82,_0x309815-0xb3,_0x2d5c46-0xce);}let _0x216497;_0xc1cf5d&&(_0xc1cf5d['packname']||_0xc1cf5d[_0x5eda10(0x65b,0x5c5,0x69d,0x5c8)])?_0x216497=await _0x2eeff8[_0x3cf7b9(-0x69,-0x34,-0x78,-0x7a)](writeExifImg,_0x50e170,_0xc1cf5d):_0x216497=await _0x2eeff8[_0x3cf7b9(-0x1d,-0x48,-0x5b,-0x48)](imageToWebp,_0x50e170);const _0x7829a8={};_0x7829a8[_0x5eda10(0x58c,0x591,0x621,0x557)]=_0x216497;const _0x2af7ee={'sticker':_0x7829a8,..._0xc1cf5d},_0x4338e8={};_0x4338e8['quoted']=_0x136a04;function _0x3cf7b9(_0x31608e,_0x4a0558,_0x1a7113,_0xef43fa){return _0x5db3f1(_0x31608e- -0x4d3,_0x4a0558-0x18a,_0x1a7113,_0xef43fa-0x134);}return await _0xf2055[_0x5eda10(0x69b,0x6e8,0x6db,0x66b)+'e'](_0xc5a43f,_0x2af7ee,_0x4338e8),_0x216497;},_0xf2055[_0x1f64a7(0x4eb,0x571,0x5a5,0x4dd)+'sSticker']=async(_0x165869,_0x2836d7,_0x14412e,_0x163580={})=>{let _0x5a7842=Buffer[_0x229816(0x8c,0x102,0x17e,0x13b)](_0x2836d7)?_0x2836d7:/^data:.*?\/.*?;base64,/i['test'](_0x2836d7)?Buffer['from'](_0x2836d7[_0x229816(0x2ad,0x24d,0x2e7,0x269)]`,`[0x1718*-0x1+0x52e*0x4+0x261],'base64'):/^https?:\/\//[_0x39caf4(0x52f,0x4c5,0x5be,0x553)](_0x2836d7)?await await _0x2eeff8[_0x39caf4(0x5d4,0x4fa,0x4b7,0x533)](getBuffer,_0x2836d7):fs[_0x39caf4(0x4be,0x566,0x3e2,0x4b4)](_0x2836d7)?fs[_0x229816(0x321,0x1dd,0x2a4,0x290)+'nc'](_0x2836d7):Buffer[_0x229816(0x26c,0x21f,0x265,0x1cb)](0x1e7e+-0xac9+-0x13b5);function _0x39caf4(_0x5f4b42,_0xfb0a38,_0x25e485,_0x41af28){return _0x1f64a7(_0xfb0a38,_0x41af28- -0x9,_0x25e485-0x34,_0x41af28-0x135);}function _0x229816(_0x2a1deb,_0x4083a5,_0x12269a,_0x64bb24){return _0x1f64a7(_0x4083a5,_0x64bb24- -0x3a2,_0x12269a-0x102,_0x64bb24-0x12f);}let _0x393867;_0x163580&&(_0x163580[_0x229816(0x23b,0x2ed,0x17c,0x216)]||_0x163580['author'])?_0x393867=await _0x2eeff8['ItGsE'](writeExifVid,_0x5a7842,_0x163580):_0x2eeff8[_0x229816(0x225,0x2d1,0x200,0x2a8)]!==_0x2eeff8[_0x39caf4(0x612,0x544,0x6a9,0x5fc)]?_0x393867=await videoToWebp(_0x5a7842):(_0x3a4163[_0x229816(0x207,0x108,0x15a,0x1dc)](_0x2eeff8[_0x39caf4(0x452,0x578,0x598,0x509)]),_0x36e891[_0x39caf4(0x4c0,0x5e1,0x49f,0x51f)]());const _0x530037={};_0x530037['url']=_0x393867;const _0x533f11={'sticker':_0x530037,..._0x163580},_0x1a97c5={};return _0x1a97c5[_0x39caf4(0x50f,0x507,0x5a4,0x510)]=_0x14412e,await _0xf2055[_0x39caf4(0x5f9,0x632,0x5a4,0x610)+'e'](_0x165869,_0x533f11,_0x1a97c5),_0x393867;},_0xf2055[_0x5db3f1(0x3fe,0x4b5,0x366,0x331)+'dSaveMedia'+_0x5db3f1(0x3ed,0x361,0x34c,0x3fd)]=async(_0x3d6927,_0x2e93c3,_0x119b27=!![])=>{function _0x15e767(_0x132cf0,_0x5afa12,_0x3a8f1e,_0x3ed03e){return _0x1f64a7(_0x5afa12,_0x3ed03e- -0x129,_0x3a8f1e-0x14c,_0x3ed03e-0xd6);}function _0x25f452(_0xc68242,_0x170872,_0x2559f4,_0x3c32c8){return _0x5db3f1(_0xc68242- -0x554,_0x170872-0x105,_0x3c32c8,_0x3c32c8-0xff);}if(_0x25f452(-0x14a,-0x10d,-0x1eb,-0x213)!==_0x2eeff8['bbprP']){let _0x182237=_0x3d6927[_0x15e767(0x48f,0x4d9,0x39c,0x461)]?_0x3d6927[_0x15e767(0x47c,0x402,0x47e,0x461)]:_0x3d6927,_0x5665e2=(_0x3d6927[_0x15e767(0x4ca,0x4ac,0x40d,0x461)]||_0x3d6927)[_0x15e767(0x56d,0x430,0x43c,0x4cd)]||'',_0x55c8e4=_0x3d6927[_0x25f452(-0xae,-0x1d,-0x71,-0x60)]?_0x3d6927['mtype'][_0x15e767(0x453,0x4ca,0x487,0x495)](/Message/gi,''):_0x5665e2[_0x25f452(-0x4a,-0x8d,-0x6e,0x7e)]('/')[-0x2033+0x182d+0x806];const _0x59ee6b=await downloadContentFromMessage(_0x182237,_0x55c8e4);let _0x341e05=Buffer['from']([]);for await(const _0x17ffda of _0x59ee6b){if(_0x2eeff8[_0x15e767(0x497,0x47f,0x49b,0x536)]!==_0x2eeff8[_0x15e767(0x51b,0x4d1,0x4a5,0x536)]){let _0x3a2693=_0x12ba0a[_0x15e767(0x4f5,0x4f6,0x3c9,0x463)](_0x3ef222['id']);if(_0xa8f32d&&_0x3bf53c[_0x25f452(-0x11a,-0xfd,-0x15c,-0x11a)])_0x422e8f[_0x25f452(-0x11a,-0x127,-0x6d,-0x1ee)][_0x3a2693]={'id':_0x3a2693,'name':_0x344c79['notify']};}else _0x341e05=Buffer[_0x15e767(0x3e6,0x495,0x52b,0x475)]([_0x341e05,_0x17ffda]);}let _0x3c1e1e=await FileType['fromBuffer'](_0x341e05);return trueFileName=_0x119b27?_0x2eeff8[_0x15e767(0x481,0x430,0x404,0x4b2)](_0x2e93c3,'.')+_0x3c1e1e[_0x15e767(0x411,0x47e,0x47c,0x47a)]:_0x2e93c3,await fs['writeFileS'+'ync'](trueFileName,_0x341e05),trueFileName;}else for(let _0x43df5a of _0x5172da){let _0x3a6b1c=_0x1e3643[_0x25f452(-0xc9,-0x12b,-0x4d,-0x5)](_0x43df5a['id']);if(_0x4448be&&_0x219cd1[_0x25f452(-0x11a,-0x169,-0xb6,-0xf5)])_0x5b6231[_0x25f452(-0x11a,-0xd1,-0xfc,-0x145)][_0x3a6b1c]={'id':_0x3a6b1c,'name':_0x43df5a['notify']};}},_0xf2055[_0x1f64a7(0x5b9,0x5f2,0x559,0x58d)+_0x1f64a7(0x608,0x52d,0x4cb,0x495)]=async _0x3fed00=>{let _0x390277=(_0x3fed00[_0xb701d0(0x61,0x40,0x3a,0xb3)]||_0x3fed00)[_0xb701d0(0x72,0xac,0x5b,0xbf)]||'';function _0x36cfe6(_0x2cc6db,_0x49844b,_0x504638,_0x4b2948){return _0x1f64a7(_0x2cc6db,_0x49844b- -0x28b,_0x504638-0x104,_0x4b2948-0x143);}function _0xb701d0(_0x36ded4,_0x325c34,_0x5e53,_0x1185d0){return _0x5db3f1(_0x325c34- -0x449,_0x325c34-0x1b1,_0x5e53,_0x1185d0-0x14d);}let _0x2c7ea4=_0x3fed00[_0x36cfe6(0x2bc,0x31c,0x348,0x270)]?_0x3fed00[_0x36cfe6(0x289,0x31c,0x361,0x2cd)]['replace'](/Message/gi,''):_0x390277['split']('/')[0xe*0x1bb+0x1*0xd96+-0x25d0];const _0x55d142=await _0x2eeff8[_0xb701d0(0x133,0xfc,0x19c,0x5d)](downloadContentFromMessage,_0x3fed00,_0x2c7ea4);let _0x83d273=Buffer[_0xb701d0(0x53,0x114,0x13a,0x10a)]([]);for await(const _0x2b542b of _0x55d142){_0x83d273=Buffer['concat']([_0x83d273,_0x2b542b]);}return _0x83d273;},_0xf2055[_0x1f64a7(0x4b7,0x51a,0x5bf,0x4ce)]=async(_0x108bcf,_0x2a1d4f,_0x2f0caa='',_0x2c163c='',_0x18838b='',_0x4b3e94={})=>{const _0x403760={};_0x403760[_0x11e3b6(-0x6f,-0x7f,-0x3d,-0xa3)]=_0x2eeff8['jXlLm'],_0x403760[_0x11e3b6(-0x86,-0xde,-0xf5,-0x158)]=_0x2eeff8[_0x1a318a(-0x5,0x3c,0x8e,0xe6)],_0x403760[_0x11e3b6(-0xa3,-0xe9,-0x16,-0x59)]=_0x2eeff8['OIXtb'],_0x403760[_0x1a318a(0x59,0x160,0xf3,0x19a)]=_0x2eeff8['vCLwg'];const _0x4ea80f=_0x403760;let _0x524c0f=await _0xf2055[_0x1a318a(0xbd,0xa3,0x44,-0x75)](_0x2a1d4f,!![]),{mime:_0xc9fcc9,ext:_0x3459b2,res:_0xc5fd43,data:_0x289347,filename:_0xd715de}=_0x524c0f;if(_0xc5fd43&&_0x2eeff8[_0x11e3b6(-0x106,-0x2b,-0xfc,-0x1d9)](_0xc5fd43[_0x11e3b6(-0x1b4,-0x200,-0x202,-0x19d)],-0xcf1*-0x2+-0xfaa+0x10*-0x97)||_0x2eeff8[_0x11e3b6(-0x1db,-0x226,-0x2b0,-0x15b)](file[_0x1a318a(0x1d9,0xf1,0x1a1,0x1f1)],0x79*0x2b3+0x1eb*-0x2f+-0x138a*-0x1))try{throw{'json':JSON[_0x1a318a(0x13a,0x1a2,0x184,0xb0)](file[_0x11e3b6(-0x51,0x9,-0x43,-0xdb)]())};}catch(_0x33c6fe){if(_0x2eeff8['aPaiV'](_0x2eeff8[_0x11e3b6(-0x1f7,-0x121,-0x20a,-0x25d)],_0x11e3b6(-0x157,-0xdf,-0x224,-0xc9))){const _0x454fb6={};return _0x454fb6['to']=_0x4ea80f[_0x11e3b6(-0x6f,0x4,0x29,-0x40)],_0x454fb6[_0x11e3b6(-0xd5,-0x17c,-0x10a,-0x48)]=_0x4ea80f[_0x11e3b6(-0x86,-0x101,-0x3b,-0x33)],_0x454fb6[_0x1a318a(0x1f8,0x1e7,0x195,0x1ea)]=_0x11e3b6(-0x1b4,-0x1a0,-0x17e,-0x1da),_0x477906[_0x1a318a(0x5,0x131,0xb8,0x125)]({'tag':'iq','attrs':_0x454fb6,'content':[{'tag':_0x4ea80f[_0x11e3b6(-0xa3,-0x6,-0xc1,-0xf0)],'attrs':{},'content':_0x57bc33[_0x11e3b6(-0x48,-0x24,0x81,0x60)](_0x4af7ee,_0x4ea80f[_0x11e3b6(-0x14c,-0x88,-0x1b9,-0xa6)])}]}),_0x4bc1f6;}else{if(_0x33c6fe[_0x1a318a(0x66,0xc6,0x65,0x103)])throw _0x33c6fe[_0x1a318a(0xaf,-0x50,0x65,-0x16)];}}let _0x3f443e='',_0x425393=_0xc9fcc9,_0x5a47d4=_0xd715de;if(_0x4b3e94[_0x11e3b6(-0xb5,-0xd8,-0x43,-0x136)])_0x3f443e=_0x2eeff8[_0x11e3b6(-0x94,-0x8e,-0x9f,0x2)];if(_0x4b3e94[_0x1a318a(0x16e,0x1bf,0x118,0x86)]||/webp/[_0x1a318a(0x176,0x62,0xf5,0x56)](_0xc9fcc9)){let {writeExif:_0x12588a}=_0x2eeff8[_0x11e3b6(-0xdc,-0x140,-0x3f,-0x1)](require,_0x2eeff8['QXGyJ']);const _0x177741={};_0x177741[_0x1a318a(0x19d,0xb9,0x18f,0x10d)]=_0xc9fcc9,_0x177741[_0x11e3b6(-0x1f3,-0x20a,-0x199,-0x29e)]=_0x289347;let _0x16e47d=_0x177741;const _0x4778f0={};_0x4778f0[_0x11e3b6(-0xee,-0x4f,-0x19a,-0xf2)]=_0x4b3e94[_0x11e3b6(-0xee,-0x32,-0x5c,-0x158)]?_0x4b3e94[_0x11e3b6(-0xee,-0x83,-0x183,-0x1b4)]:global['packname'],_0x4778f0[_0x11e3b6(-0xcd,-0x98,-0x5c,-0xc2)]=_0x4b3e94['author']?_0x4b3e94[_0x1a318a(0x1b5,0x19a,0x172,0x179)]:global['author'],_0x4778f0[_0x11e3b6(-0x1df,-0x1d5,-0x191,-0x243)]=_0x4b3e94['categories']?_0x4b3e94['categories']:[],_0x5a47d4=await _0x12588a(_0x16e47d,_0x4778f0),await fs[_0x11e3b6(-0x15c,-0x1ed,-0x1de,-0xe3)][_0x1a318a(0x50,0x146,0x11a,0x102)](_0xd715de),_0x3f443e=_0x11e3b6(-0xce,-0xf9,-0x2e,-0x157),_0x425393=_0x1a318a(0xa2,0xb6,0xc8,0x99);}else{if(/image/[_0x1a318a(0x44,0x7c,0xf5,0xc6)](_0xc9fcc9))_0x3f443e=_0x2eeff8['FnmWk'];else{if(/video/[_0x1a318a(0xe2,0x46,0xf5,0x3f)](_0xc9fcc9))_0x3f443e='video';else{if(/audio/[_0x1a318a(0x3f,0x14e,0xf5,0x80)](_0xc9fcc9))_0x3f443e=_0x2eeff8[_0x1a318a(0x235,0x1a3,0x1e5,0x14d)];else _0x3f443e=_0x2eeff8['rlFnJ'];}}}const _0x14b089={};_0x14b089['url']=_0x5a47d4;const _0x3f72c5={[_0x3f443e]:_0x14b089,'caption':_0x2c163c,'mimetype':_0x425393,'fileName':_0x2f0caa,..._0x4b3e94};function _0x1a318a(_0x49586b,_0x1250cf,_0x2084ba,_0x4473f3){return _0x5db3f1(_0x2084ba- -0x366,_0x1250cf-0x12a,_0x49586b,_0x4473f3-0x1c5);}const _0x58ac24={'quoted':_0x18838b,..._0x4b3e94};function _0x11e3b6(_0x31131b,_0x3cfcc7,_0x395bff,_0x965b34){return _0x1f64a7(_0x395bff,_0x31131b- -0x6a6,_0x395bff-0x97,_0x965b34-0x1dd);}return await _0xf2055[_0x1a318a(0x28d,0x129,0x1b2,0x1eb)+'e'](_0x108bcf,_0x3f72c5,_0x58ac24),fs[_0x1a318a(0x6b,0xf8,0xe3,0x153)][_0x1a318a(0x5b,0x1c3,0x11a,0x98)](_0x5a47d4);},_0xf2055[_0x1f64a7(0x63d,0x613,0x6c9,0x6dc)+'rd']=async(_0x133256,_0x209d25,_0xdc4211=![],_0x5e3342={})=>{function _0x43b137(_0x313e39,_0xc0fa4a,_0x4fffa7,_0x447645){return _0x1f64a7(_0x4fffa7,_0xc0fa4a- -0x86,_0x4fffa7-0x1b7,_0x447645-0x81);}function _0x310abb(_0x1ce225,_0x401ec4,_0x4d0acb,_0x31f9b2){return _0x1f64a7(_0x401ec4,_0x4d0acb- -0x344,_0x4d0acb-0xfd,_0x31f9b2-0x191);}if(_0x2eeff8[_0x310abb(0x1d9,0x2e5,0x21a,0x2e5)](_0x2eeff8[_0x43b137(0x4b8,0x57b,0x58f,0x613)],_0x310abb(0x14b,0xe5,0x18c,0x145)))throw{'json':_0x4b5b4c[_0x310abb(0x28d,0x325,0x2a7,0x330)](_0x184881['toString']())};else{let _0x1b3d68;_0x5e3342[_0x43b137(0x5ad,0x511,0x522,0x49c)+'ce']&&(_0x209d25['message']=_0x209d25[_0x310abb(0x202,0x2e2,0x277,0x31c)]&&_0x209d25[_0x43b137(0x4c2,0x535,0x4eb,0x57e)][_0x310abb(0x316,0x311,0x28b,0x33e)+'essage']&&_0x209d25[_0x310abb(0x269,0x27a,0x277,0x2dd)][_0x43b137(0x4cf,0x549,0x571,0x4b5)+_0x43b137(0x3ec,0x482,0x484,0x549)]['message']?_0x209d25['message'][_0x310abb(0x272,0x31f,0x28b,0x26a)+'essage'][_0x310abb(0x1e8,0x308,0x277,0x2b6)]:_0x209d25[_0x310abb(0x1b2,0x283,0x277,0x1e8)]||undefined,_0x1b3d68=Object[_0x310abb(0x29e,0x2ab,0x211,0x1e3)](_0x209d25['message'][_0x43b137(0x5c0,0x512,0x4a1,0x555)+_0x43b137(0x520,0x53f,0x49d,0x4b5)][_0x43b137(0x467,0x535,0x5bb,0x53e)])[0x24b3+-0x1b6b+-0x2c*0x36],delete(_0x209d25['message']&&_0x209d25[_0x310abb(0x229,0x22c,0x277,0x1d2)][_0x43b137(0x395,0x430,0x3ce,0x4f0)]?_0x209d25['message'][_0x43b137(0x4bf,0x430,0x414,0x4c8)]:_0x209d25[_0x310abb(0x1f7,0x1b2,0x277,0x1c2)]||undefined),delete _0x209d25['message'][_0x310abb(0x1da,0x29e,0x254,0x31d)+_0x43b137(0x56e,0x53f,0x52d,0x54b)]['message'][_0x1b3d68][_0x310abb(0x344,0x1ed,0x2ac,0x208)],_0x209d25[_0x43b137(0x575,0x535,0x501,0x5dc)]={..._0x209d25['message']['viewOnceMe'+_0x310abb(0x1bc,0x1a5,0x281,0x236)][_0x310abb(0x241,0x229,0x277,0x2e3)]});let _0x4bf382=Object[_0x43b137(0x480,0x4cf,0x4e0,0x4dc)](_0x209d25[_0x310abb(0x1ee,0x33e,0x277,0x297)])[-0x1514+0x2*0x1337+0x1*-0x115a],_0xa1896b=await generateForwardMessageContent(_0x209d25,_0xdc4211),_0x5764aa=Object[_0x43b137(0x4fb,0x4cf,0x448,0x43d)](_0xa1896b)[-0x11*0x1d5+0x61e+-0x95*-0x2b],_0x3bb8ea={};if(_0x4bf382!=_0x2eeff8[_0x310abb(0x270,0x256,0x2b7,0x250)])_0x3bb8ea=_0x209d25[_0x43b137(0x5bc,0x535,0x538,0x5e2)][_0x4bf382][_0x43b137(0x54e,0x5c1,0x4ec,0x4f7)+'o'];_0xa1896b[_0x5764aa][_0x310abb(0x295,0x2f6,0x303,0x3d5)+'o']={..._0x3bb8ea,..._0xa1896b[_0x5764aa][_0x310abb(0x2ff,0x307,0x303,0x35d)+'o']};const _0xff1b2c=await generateWAMessageFromContent(_0x133256,_0xa1896b,_0x5e3342?{..._0xa1896b[_0x5764aa],..._0x5e3342,..._0x5e3342[_0x310abb(0x262,0x3a3,0x303,0x30d)+'o']?{'contextInfo':{..._0xa1896b[_0x5764aa]['contextInf'+'o'],..._0x5e3342[_0x310abb(0x313,0x342,0x303,0x2fd)+'o']}}:{}}:{});return await _0xf2055[_0x310abb(0x262,0x1b0,0x25d,0x275)+'ge'](_0x133256,_0xff1b2c[_0x310abb(0x295,0x2bc,0x277,0x295)],{'messageId':_0xff1b2c['key']['id']}),_0xff1b2c;}},_0xf2055[_0x1f64a7(0x635,0x5fd,0x560,0x6b6)]=(_0x265ee6,_0x3dd5ea,_0x27e9e3='',_0x55bbfb=_0xf2055[_0x5db3f1(0x4b0,0x492,0x438,0x4c1)]['id'],_0x264759={})=>{function _0x3dd909(_0x39b028,_0x40e881,_0x4ee71a,_0x596216){return _0x5db3f1(_0x4ee71a-0x6f,_0x40e881-0x12b,_0x596216,_0x596216-0x84);}const _0x160b18={'dJQbR':_0x2eeff8[_0x3dd909(0x459,0x476,0x494,0x551)],'fWycb':function(_0x4436e5,_0x3c3d6a){function _0xa37fb1(_0x5df02c,_0x437c27,_0x317ecf,_0xd5f6b3){return _0x3dd909(_0x5df02c-0x0,_0x437c27-0x15d,_0x317ecf-0x30,_0xd5f6b3);}return _0x2eeff8[_0xa37fb1(0x566,0x514,0x5dd,0x5c4)](_0x4436e5,_0x3c3d6a);},'PTRIA':_0x2eeff8[_0x3dd909(0x367,0x44f,0x434,0x3cf)],'mcCOv':_0x2eeff8[_0x3dd909(0x4ea,0x471,0x507,0x476)],'EsXCp':function(_0x1f73ec,_0x594ae6){return _0x1f73ec===_0x594ae6;},'BjrNI':function(_0x4083d8,_0x48d552,_0x1a5d2d,_0x4f942a){return _0x4083d8(_0x48d552,_0x1a5d2d,_0x4f942a);},'EQBBa':_0x2eeff8[_0x3dd909(0x498,0x486,0x490,0x4af)]};function _0x24de6d(_0x5280d7,_0x1563ab,_0x376537,_0x48b0e7){return _0x1f64a7(_0x48b0e7,_0x5280d7- -0x296,_0x376537-0x18e,_0x48b0e7-0xd8);}if(_0x2eeff8['QPGtL'](_0x2eeff8['bovBk'],_0x2eeff8[_0x3dd909(0x523,0x48c,0x562,0x4c5)])){let _0x5c61f0=Object[_0x24de6d(0x2bf,0x288,0x318,0x328)](_0x3dd5ea[_0x24de6d(0x325,0x2b0,0x2ac,0x346)])[0x1e1+0x3*0x53+0x92*-0x5],_0x1a6d03=_0x2eeff8[_0x3dd909(0x488,0x437,0x4e7,0x538)](_0x5c61f0,_0x2eeff8[_0x24de6d(0x290,0x361,0x34d,0x1e2)]);if(_0x1a6d03){if(_0x2eeff8[_0x3dd909(0x616,0x5da,0x5ad,0x552)](_0x2eeff8['wCsoz'],_0x2eeff8[_0x24de6d(0x262,0x279,0x2f0,0x1d7)]))try{_0x2bd0ce=_0x5bf9bf[_0x24de6d(0x2fe,0x3b0,0x249,0x30c)][-0x735+-0x9e7+0x111c];if(!_0x1b21b8[_0x24de6d(0x325,0x2d6,0x3d6,0x37e)])return;_0x4196ad[_0x24de6d(0x325,0x388,0x2aa,0x271)]=_0x1c0423[_0x3dd909(0x42c,0x499,0x4c3,0x431)](_0x2d2ea4[_0x3dd909(0x56c,0x5f2,0x529,0x4fc)])[-0x20d6+-0xd74+0x2e4a]===_0x160b18[_0x3dd909(0x523,0x60d,0x54f,0x555)]?_0x1a5b9b['message'][_0x3dd909(0x4bb,0x5eb,0x53d,0x4cb)+_0x24de6d(0x272,0x27c,0x203,0x304)]['message']:_0x41c8c5[_0x24de6d(0x325,0x301,0x285,0x368)];if(_0x93ba2a[_0x3dd909(0x604,0x5d5,0x5aa,0x4fe)]&&_0x160b18[_0x24de6d(0x2d0,0x2d3,0x326,0x220)](_0x49f15d[_0x24de6d(0x3a6,0x43f,0x47f,0x44a)][_0x3dd909(0x3d2,0x51d,0x467,0x4f1)],_0x160b18['PTRIA']))return;if(!_0x44d7c5[_0x24de6d(0x381,0x3c0,0x443,0x3b0)]&&!_0x294efa['key'][_0x3dd909(0x565,0x3f9,0x495,0x4be)]&&_0x5088a5[_0x24de6d(0x33b,0x394,0x29a,0x413)]===_0x3dd909(0x443,0x422,0x41e,0x476))return;if(_0x1c170f[_0x3dd909(0x554,0x5f5,0x5aa,0x5eb)]['id']['startsWith'](_0x160b18['mcCOv'])&&_0x160b18['EsXCp'](_0x1223a9['key']['id'][_0x3dd909(0x56c,0x519,0x576,0x49c)],-0x7a2+0xdbb+-0x609))return;_0x2c3214=_0x160b18['BjrNI'](_0x59d30e,_0x331e9a,_0x3153dc,_0x27c3cd),_0x493521(_0x160b18[_0x3dd909(0x495,0x487,0x420,0x3c6)])(_0x25260d,_0x233485,_0xce5ec1,_0x589373);}catch(_0x3a6ef5){_0x5abc7d['log'](_0x3a6ef5);}else _0x5c61f0=Object[_0x3dd909(0x4e8,0x443,0x4c3,0x554)](_0x3dd5ea[_0x24de6d(0x325,0x2db,0x361,0x2dd)][_0x3dd909(0x592,0x47b,0x53d,0x493)+_0x3dd909(0x44e,0x53f,0x476,0x476)]['message'])[0x1b75+-0x22cb+0x756];}let _0x3e7f40=_0x1a6d03?_0x3dd5ea['message'][_0x3dd909(0x4bd,0x4ae,0x53d,0x4a5)+_0x3dd909(0x51e,0x413,0x476,0x3c2)][_0x3dd909(0x58a,0x497,0x529,0x564)]:_0x3dd5ea[_0x3dd909(0x5c7,0x54a,0x529,0x520)],_0x1e28b6=_0x3e7f40[_0x5c61f0];if(_0x2eeff8[_0x24de6d(0x34d,0x3e0,0x2ba,0x2a8)](typeof _0x1e28b6,_0x24de6d(0x281,0x232,0x342,0x1ab)))_0x3e7f40[_0x5c61f0]=_0x2eeff8[_0x24de6d(0x223,0x2d8,0x26e,0x2e7)](_0x27e9e3,_0x1e28b6);else{if(_0x1e28b6[_0x3dd909(0x3e0,0x3b1,0x44e,0x4cc)])_0x1e28b6['caption']=_0x27e9e3||_0x1e28b6[_0x3dd909(0x459,0x4bd,0x44e,0x47e)];else{if(_0x1e28b6[_0x3dd909(0x587,0x5b3,0x51b,0x4c4)])_0x1e28b6[_0x3dd909(0x5ec,0x49e,0x51b,0x485)]=_0x27e9e3||_0x1e28b6[_0x3dd909(0x4dd,0x4c4,0x51b,0x45b)];}}if(_0x2eeff8[_0x24de6d(0x217,0x283,0x18d,0x2dd)](typeof _0x1e28b6,_0x24de6d(0x281,0x289,0x250,0x21b)))_0x3e7f40[_0x5c61f0]={..._0x1e28b6,..._0x264759};if(_0x3dd5ea[_0x3dd909(0x58a,0x5e4,0x5aa,0x571)][_0x24de6d(0x386,0x459,0x33c,0x3a8)+'t'])_0x55bbfb=_0x3dd5ea[_0x3dd909(0x63406,0x52a,0x5aa,0x598)][_0x24de6d(0x386,0x449,0x301,0x395)+'t']=_0x55bbfb||_0x3dd5ea[_0x24de6d(0x3a6,0x362,0x418,0x421)][_0x24de6d(0x386,0x2ab,0x32c,0x410)+'t'];else{if(_0x3dd5ea[_0x3dd909(0x680,0x5fd,0x5aa,0x5d3)][_0x3dd909(0x4b8,0x4fa,0x58a,0x545)+'t'])_0x55bbfb=_0x3dd5ea[_0x3dd909(0x5b0,0x4f0,0x5aa,0x546)][_0x24de6d(0x386,0x32d,0x304,0x41d)+'t']=_0x55bbfb||_0x3dd5ea[_0x3dd909(0x5ff,0x536,0x5aa,0x4f7)][_0x3dd909(0x65a,0x5a8,0x58a,0x664)+'t'];}if(_0x3dd5ea[_0x24de6d(0x3a6,0x2f2,0x477,0x436)][_0x3dd909(0x3ff,0x3a0,0x467,0x3d0)]['includes'](_0x2eeff8[_0x24de6d(0x212,0x258,0x184,0x2e1)]))_0x55bbfb=_0x55bbfb||_0x3dd5ea[_0x3dd909(0x62d,0x617,0x5aa,0x57e)][_0x3dd909(0x3d8,0x42d,0x467,0x466)];else{if(_0x3dd5ea[_0x3dd909(0x514,0x5ca,0x5aa,0x617)]['remoteJid']['includes']('@broadcast'))_0x55bbfb=_0x55bbfb||_0x3dd5ea[_0x3dd909(0x56d,0x665,0x5aa,0x62a)][_0x24de6d(0x263,0x314,0x315,0x21c)];}return _0x3dd5ea[_0x24de6d(0x3a6,0x2d8,0x329,0x353)][_0x3dd909(0x460,0x49f,0x467,0x53e)]=_0x265ee6,_0x3dd5ea[_0x3dd909(0x58d,0x65e,0x5aa,0x604)][_0x24de6d(0x291,0x1cb,0x368,0x209)]=_0x55bbfb===_0xf2055[_0x3dd909(0x4ef,0x5db,0x51f,0x483)]['id'],proto[_0x3dd909(0x43a,0x404,0x499,0x3e8)+_0x3dd909(0x4d6,0x46d,0x4b4,0x528)][_0x24de6d(0x26a,0x254,0x2b0,0x195)](_0x3dd5ea);}else try{throw{'json':_0x35afd5[_0x3dd909(0x4d7,0x485,0x559,0x4c7)](_0x4862d5[_0x24de6d(0x3bf,0x40c,0x456,0x36b)]())};}catch(_0x5d7cd5){if(_0x5d7cd5[_0x3dd909(0x472,0x43d,0x43a,0x425)])throw _0x5d7cd5[_0x24de6d(0x236,0x169,0x242,0x311)];}},_0xf2055[_0x5db3f1(0x3aa,0x3b2,0x389,0x440)]=async(_0x1effc8,_0x5466e1)=>{let _0x4372bf,_0x1b6c02=Buffer[_0x2c72f7(0x26e,0x2a4,0x22f,0x1e0)](_0x1effc8)?_0x1effc8:/^data:.*?\/.*?;base64,/i[_0x2c72f7(0x2ed,0x346,0x2a3,0x3b2)](_0x1effc8)?Buffer['from'](_0x1effc8[_0x2c72f7(0x39c,0x418,0x36f,0x43c)]`,`[-0x1498+-0x26*-0x74+-0x361*-0x1],_0x2eeff8[_0x197c61(-0x144,-0x152,-0xd4,-0x161)]):/^https?:\/\//[_0x197c61(-0xd9,-0xb9,-0x93,-0x136)](_0x1effc8)?await(_0x4372bf=await _0x2eeff8[_0x2c72f7(0x2ca,0x291,0x1f7,0x2c7)](getBuffer,_0x1effc8)):fs[_0x2c72f7(0x24e,0x225,0x26c,0x213)](_0x1effc8)?(filename=_0x1effc8,fs['readFileSy'+'nc'](_0x1effc8)):_0x2eeff8['AJlmq'](typeof _0x1effc8,_0x2eeff8[_0x197c61(0x16,0xbd,0x4f,0x104)])?_0x1effc8:Buffer[_0x197c61(-0x105,0x2a,-0x82,0x25)](0x1*-0xe75+0x5*0x4db+-0x9d2);const _0x4bc372={};_0x4bc372['mime']=_0x2eeff8[_0x197c61(0x5e,0x18,-0x6,0x10)];function _0x197c61(_0x27824b,_0x11176d,_0x52140a,_0x1ae6c5){return _0x1f64a7(_0x11176d,_0x52140a- -0x5ef,_0x52140a-0x26,_0x1ae6c5-0x13d);}function _0x2c72f7(_0x4e3fe9,_0x370ab6,_0x2caa63,_0x174ae5){return _0x1f64a7(_0x370ab6,_0x4e3fe9- -0x26f,_0x2caa63-0x17c,_0x174ae5-0x1e7);}_0x4bc372['ext']=_0x2eeff8[_0x197c61(-0x1a2,-0x107,-0x11b,-0xe1)];let _0x34cb4e=await FileType[_0x2c72f7(0x285,0x2e1,0x2d7,0x2af)](_0x1b6c02)||_0x4bc372;filename=path[_0x197c61(-0x9b,-0x1ae,-0xe2,-0x38)](__filename,_0x2eeff8[_0x2c72f7(0x26c,0x192,0x274,0x195)](_0x2eeff8['KZKgW'](_0x2c72f7(0x3d4,0x426,0x46a,0x34b),_0x2eeff8['flBKD'](new Date(),-0x8ef*0x3+-0x7*0x51f+-0x1*-0x3ea7)),'.')+_0x34cb4e[_0x197c61(0x13,0x1b,-0x4c,-0x34)]);if(_0x2eeff8[_0x197c61(-0xb2,0x46,-0x2c,-0x32)](_0x1b6c02,_0x5466e1))fs[_0x2c72f7(0x2db,0x24b,0x3ab,0x2b2)][_0x197c61(-0x71,-0x12e,-0xb2,-0x9c)](filename,_0x1b6c02);return{'res':_0x4372bf,'filename':filename,'size':await _0x2eeff8[_0x197c61(0x3a,-0x65,0x3d,-0x79)](getSizeMedia,_0x1b6c02),..._0x34cb4e,'data':_0x1b6c02};};function _0x5db3f1(_0x32411c,_0x2d4c97,_0x2cf80d,_0x4c3306){return _0x342235(_0x32411c-0x174,_0x2d4c97-0x16,_0x32411c-0x395,_0x2cf80d);}return _0xf2055;}startHisoka();let file=require[_0x342235(0xf0,0x79,0x52,0x83)](__filename);function _0x5bf5(){const _0x33d63a=['upload','and\x20Scan\x20A','ti\x20Device','Message','yaEku','waUploadTo','dxOrY','status','rst','fromBuffer','CQyCF','Restart\x20Re','sGtGH','sfPOo','remoteJid','.json','BLabel:Pon','redBright','3.0\x0aN:Sofat','Sistem\x20oto','downloadAn','fromObject','p.net','hYRSm','tYXoP','GmzmC','IYaTK','starting..','\x20TimedOut,','essage','tkorW','url','bJWrG','g....','join','189710htgfoD','statusCode','D\x0aVERSION:','lease\x20Dele','tQvHf','hydratedFo','66lKHIWw','tube\x0aitem4','getName','string','utube\x0aitem','quoted','sendMedia','FpsNm','getNumber','name','cMPkM','query','menelpon\x20b','hydratedCo','LtQRe','APIs','\x0aFN:','donesia;;;','sXXUT','fromMe','exit','loggedOut','EDwse','WebMessage','ntentText','diaMessage','GWYdV','image/webp','api','CbNop','templateMe','bIVvm','mtuLG','myweb','./config','KjMjN','ABLabel:Yo','LUAms','JEFMs','contacts','TVier','writeFile','\x0aitem2.EMA','Zghfg','server','\x20closed,\x20r','displayNam','unwatchFil','YMZIh','tRywS','Info','tag','sconnectRe','054:628387','promises','oterText','FPAOr','subject','internatio','uxsHO','1.0.0','BEGIN:VCAR','brxfc','wzzVs','3739099HLYoBo','keys','xRzXb','Device\x20Log','ion\x0aEND:VC','action','VRuhc','Welcome\x20To','test','rTSvK','JDBLR','tureUrl','ew\x20Session','06/Top-Gam','hfPHn','sSticker','forxW','.wp.com/ww','fWycb','ijukV','hHoOL','mHFxs','2727494wHzwKB','SGAps','serializeM','alloc','kJAdz','yYT\x0aFN:San','messages.u','sendVideoA','groupMetad','vZdrE','12cCWtrU','.bin','icipants.u','imageMessa','ease\x20Delet','eCTyU','ronni','JhEhL','sJLyI','onesia;;;;','log','asSticker','owner','unlink','uBVaP','rmito','chat','opjdS','ZrUEQ','xqHlX','sendImageA','image','msg','Safari','decodeJid','OIXtb','status@bro','CB:call','firdasofati1@','error','APIKeys','TctrG','messages','\x0aitem4.X-A','QCBQy','readViewOn','viewOnceMe','eygfO','FnmWk','ELUnS','udexT','2|1|0','concat','oads/2019/','WsDAo','relayMessa','eqBWd','ext','./lib/exif','https://i0','onenumber','mtype','CLJLU','xLqXk','offer','kyMPs','Label:Emai','text','pdate','hydratedTe','contacts.u','user','zFGkJ','oMOGy','rofil-Koso','verifiedNa','./hisoka','cyiGF','packname','ged\x20Out,\x20P','@adiwajshi','message','WagUC','frznD','replace','3.0\x0aN:','ason:\x20','set','ARD','AcMJA','includes','ssage','\x20Server,\x20r','.ADR:;;Ind','silent','n/octet-st','DCECI','startsWith','244574CZCLta','FadQg','@broadcast','ephemeralM','anmXa','type','Lost','zykawaiii@','sendImage','econnectin','tUTZc','lvEGF','sticker','author','TbtTy','hpGCu','THtXD','@g.us','w.gambarun','mwPfg','connection','dJQbR','.update','tVGzy','XGViB','dEWaD','remove',';waid=','youtube.co','Iacxm','ream','parse','sendVideo','entries','OKhod','adcast','viewOnce','asDocument','downloadMe','Bad\x20Sessio','bovBk','ata','mimetype','ik.id/wp-c','utf-8','matchAll','ontent/upl','fIrVM','xmlns','cMod','call-creat','DPbcf','file-type','NQREL','t\x0aitem3.X-','KouKz','CNUGh','vBxpR','badSession','fsdga','length','sel\x0aitem2.','36SECrtV','split','quired,\x20Re','sendText','HTUGR','0@s.whatsa','\x20Lost\x20from','pino','rlFnJ','copyNForwa','matis\x20bloc','65939fjtfdY','cache','public','base64','sendMessag','qJvZy','applicatio','participan','ClVlE','lAkvj','WhatsApp','OdqjA','sendContac','bar-Foto-P','bind','psert','mtQyL','\x0aitem1.TEL','gain','6693406\x0ait','nal','sendButton','rgokil-.jp','OIYVE','ewQgZ','THhLh','endsWith','odngO','Connection','readFileSy','pfJLA','mentionedJ','group-part','6283894068','IyQae','awesome-ph','ZWGpu','56dyNnEh','g...','key','IMYxc','bVygL','RuGsq','ing...','Closed','PfrKu','../src/','IzoAb','e\x20Current\x20','ItGsE','contextInf','24peYkXs','GKmhe','ixrkm','ydajE','myJhW','330PfRNeL','QOOOs','sendAudio','\x20Opened,\x20P','\x20Reconnect','path','44836simTtZ','lease\x20Clos','toString','child','UKqEN','QqkZE','bel:Ponsel','849033zbdEBU','ng-Lucu-Te','pkhAv','4.ADR:;;In','from','ZNnNj','add','jXlLm','qPadi','@s.whatsap','getFile','store','fxYII','iFifM','mpMnP','notify','RKMrB','EQBBa','data','tact','k!\x0aJangan\x20','ignore','cblHr',';\x0aitem4.X-','QvLsK','tcGhK','eVORz','BLabel:You','existsSync','MQnmI','block','PQytR','uired','NYSTo','content','setStatus','profilePic','MsRfY','categories','kStatus','goOIq','te\x20Session','uFDWM','json','EMAIL;type','jOMdN','nxKQa','PWtYI','Jdppv','l\x0aitem3.UR','document','ndxaM','\x20Leaving\x20T','QEqHL','zyYT\x0aitem1','e\x20Session\x20','amRnN','NvliC','KZKgW','Hisoka\x20Mul','isBuffer','rsrHP','withoutCon','caption','ZeYtJ','chalk','=INTERNET:','item2.X-AB','an\x20Hubungi','jLnNd','m/c/SofatiG','resolve','xaprV','timedOut'];_0x5bf5=function(){return _0x33d63a;};return _0x5bf5();}function _0x4a2e(_0x2fccb9,_0x1f696a){const _0x599b27=_0x5bf5();return _0x4a2e=function(_0x4c2d6a,_0x14c369){_0x4c2d6a=_0x4c2d6a-(-0xd9b*0x1+-0x2*0x31a+0x15b4);let _0x134f73=_0x599b27[_0x4c2d6a];return _0x134f73;},_0x4a2e(_0x2fccb9,_0x1f696a);}fs['watchFile'](file,()=>{function _0x44e80c(_0x54a95c,_0xcd9ef4,_0x433360,_0x50d0b9){return _0x342235(_0x54a95c-0x6,_0xcd9ef4-0x62,_0x54a95c-0x200,_0xcd9ef4);}fs[_0x3adc16(0x88,0x141,0xac,0x1e1)+'e'](file),console['log'](chalk[_0x44e80c(0x266,0x2d4,0x2c5,0x2a9)]('Update\x20'+__filename)),delete require[_0x44e80c(0x380,0x2f9,0x43b,0x3c9)][file];function _0x3adc16(_0x9c26c0,_0xf5a9f6,_0x3ec6db,_0x72a654){return _0x342235(_0x9c26c0-0x94,_0xf5a9f6-0xa1,_0xf5a9f6-0x94,_0x3ec6db);}require(file);});
|
export default{
props: {
input: {
type: String,
required: false,
default: ''
}
},
data() {
return {
query: ''
}
},
template: `
<div>
<FSheetsV4
id="1ZrQ_OwfitB7dvZh4LzUmanbEX6oR3kWI2YVBTkFLZfc" akey="AIzaSyB8ofd2t6YxACpaV8yJUdGjlYlV_hSoMu4" sheet="links"
v-slot="{ value }">
<div style="display: grid; grid-template-columns:1fr 2fr">
<div>
<div style="position:sticky; top:15vh;">
<span style="font-size:0.85em; font-weight:700; color:var(--darkgray);">SEARCH FOR:</span>
<input type="text" v-model="query" style="width:100%; margin-top:0.5em;" />
</div>
</div>
<div>
<a v-for="(item, i) in value" :key="'item'+i"
v-if="Object.values(item).toString().toLowerCase().includes( query.toLowerCase() )"
style="display:flex; padding: var(--base3); border-radius:var(--border-radius); box-shadow: 0 0 3px 1px hsla(0, 0%, 0%, 0.1); margin:2vmin; font-weight:normal; border:none; background:var(--white)"
:href="item.inputurl" target="_blank"
>
<h3 style="flex:0 0 70px;"><span class="bullet" style="word-break: keep-all; overflow:hidden; width:1.9em; height:1.9em; padding:1.2em; font-size:75%; font-weight:400; --purple:var(--red)">{{i+1}}</span></h3>
<div>
<h5>{{item.title}}</h5>
<p style="font-family:var(--font-serif); margin-bottom:0.5em">{{item.metadescription}}</p>
<p style="color:var(--blue); font-size:0.75em; border-bottom: none; text-decoration:underline; word-break: break-word; line-height:1.1">{{item.inputurl}}</p>
</div>
</a>
</div>
</div>
</FSheetsV4>
</div>
`
};
|
"use strict";
const userNameInput = document.getElementById('user-name');
const assessmentButton = document.getElementById('assessment');
const resultDivided = document.getElementById('result-area');
const tweetDivided = document.getElementById('tweet-area');
/**
* 指定した要素の子どもを全て削除する
* @param {HTMLElement} element HTMLの要素
*/
function removeAllChildren(element) {
while (element.firstChild) {
// 子どもの要素があるかぎり削除
element.removeChild(element.firstChild);
}
}
userNameInput.onkeydown = event => {
if (event.key === 'Enter') {
// TODO ボタンのonclick() 処理を呼び出す
assessmentButton.onclick();
}
};
assessmentButton.onclick = function(){
const userName = userNameInput.value;
if (userName.length === 0) return;
// TODO 診断結果表示エリアの作成
removeAllChildren(resultDivided);
removeAllChildren(tweetDivided);
const header = document.createElement("h3");
header.innerText = "診断結果";
resultDivided.appendChild(header);
const paragraph = document.createElement('p');
const result = assessment(userName);
paragraph.innerText = result;
resultDivided.appendChild(paragraph);
// TODO ツイートエリアの作成
const anchor = document.createElement('a');
const hrefValue ='https://twitter.com/intent/tweet?button_hashtag=' +encodeURIComponent('あなたのいいところ') +'&ref_src=twsrc%5Etfw';
anchor.setAttribute('href', hrefValue);
anchor.className = 'twitter-hashtag-button';
anchor.setAttribute('data-text', result);
anchor.innerText = 'Tweet #あなたのいいところ';
tweetDivided.appendChild(anchor);
const script = document.createElement('script');
script.setAttribute('src', 'https://platform.twitter.com/widgets.js');
tweetDivided.appendChild(script);
}
const answers = [
'{userName}のいいところは声です。{userName}の特徴的な声は皆を惹きつけ、心に残ります。',
'{userName}のいいところはまなざしです。{userName}に見つめられた人は、気になって仕方がないでしょう。',
'{userName}のいいところは情熱です。{userName}の情熱に周りの人は感化されます。',
'{userName}のいいところは厳しさです。{userName}の厳しさがものごとをいつも成功に導きます。',
'{userName}のいいところは知識です。博識な{userName}を多くの人が頼りにしています。',
'{userName}のいいところはユニークさです。{userName}だけのその特徴が皆を楽しくさせます。',
'{userName}のいいところは用心深さです。{userName}の洞察に、多くの人が助けられます。',
'{userName}のいいところは見た目です。内側から溢れ出る{userName}の良さに皆が気を惹かれます。',
'{userName}のいいところは決断力です。{userName}がする決断にいつも助けられる人がいます。',
'{userName}のいいところは思いやりです。{userName}に気をかけてもらった多くの人が感謝しています。',
'{userName}のいいところは感受性です。{userName}が感じたことに皆が共感し、わかりあうことができます。',
'{userName}のいいところは節度です。強引すぎない{userName}の考えに皆が感謝しています。',
'{userName}のいいところは好奇心です。新しいことに向かっていく{userName}の心構えが多くの人に魅力的に映ります。',
'{userName}のいいところは気配りです。{userName}の配慮が多くの人を救っています。',
'{userName}のいいところはその全てです。ありのままの{userName}自身がいいところなのです。',
'{userName}のいいところは自制心です。やばいと思ったときにしっかりと衝動を抑えられる{userName}が皆から評価されています。',
'{userName}のいいところは優しさです。{userName}の優しい雰囲気や立ち振る舞いに多くの人が癒やされています。'
];
/**
* 名前の文字列を渡すと診断結果を返す関数
* @param {string} userName ユーザーの名前
* @return {string} 診断結果
*/
function assessment(userName){
//全文字のコード番号を取得してそれを足し合わせる
let sumOfCharCode = 0;
for (let i = 0; i < userName.length; i++) {
sumOfCharCode = sumOfCharCode + userName.charCodeAt(i);
}
// 文字のコード番号の合計を回答の数で割って添字の数値を求める
const index = sumOfCharCode % answers.length;
let result = answers[index];
result = result.replace(/\{userName\}/g, userName);
return result;
}
console.log(assessment("太郎"))
console.log(assessment("次郎"))
console.log(assessment("太郎"))
console.assert(
assessment('太郎') ===
'太郎のいいところは決断力です。太郎がする決断にいつも助けられる人がいます。',
'診断結果の文言の特定の部分を名前に置き換える処理が正しくありません。'
);
console.assert(
assessment('太郎') ===
'太郎のいいところは決断力です。次郎がする決断にいつも助けられる人がいます。',
'診断結果の文言の特定の部分を名前に置き換える処理が正しくありません。'
);
console.assert(
assessment('次郎') === assessment('じろう'),
'入力が同じであるが、出力が異なります。'
);
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[46],{yRpg:function(t,i,r){"use strict";r.r(i),r.d(i,"ion_chip",function(){return a});var n=r("mLBW"),o=(r("TJLY"),r("Jbqe"));class a{constructor(t){Object(n.m)(this,t),this.outline=!1}hostData(){const t=Object(n.e)(this);return{class:Object.assign({},Object(o.a)(this.color),{[t]:!0,"chip-outline":this.outline,"ion-activatable":!0})}}__stencil_render(){const t=Object(n.e)(this);return[Object(n.i)("slot",null),"md"===t?Object(n.i)("ion-ripple-effect",null):null]}render(){return Object(n.i)(n.a,this.hostData(),this.__stencil_render())}static get style(){return":host{--background:rgba(var(--ion-text-color-rgb,0,0,0),0.12);--color:rgba(var(--ion-text-color-rgb,0,0,0),0.87);border-radius:16px;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;margin-left:4px;margin-right:4px;margin-top:4px;margin-bottom:4px;padding-left:12px;padding-right:12px;padding-top:7px;padding-bottom:7px;display:-ms-inline-flexbox;display:inline-flex;position:relative;-ms-flex-align:center;align-items:center;height:32px;background:var(--background);color:var(--color);font-family:var(--ion-font-family,inherit);font-size:14px;line-height:1;cursor:pointer;overflow:hidden;vertical-align:middle;-webkit-box-sizing:border-box;box-sizing:border-box}@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:4px;margin-inline-start:4px;-webkit-margin-end:4px;margin-inline-end:4px;padding-left:unset;padding-right:unset;-webkit-padding-start:12px;padding-inline-start:12px;-webkit-padding-end:12px;padding-inline-end:12px}}:host(.ion-color){background:rgba(var(--ion-color-base-rgb),.08);color:var(--ion-color-shade)}:host(.ion-color:focus){background:rgba(var(--ion-color-base-rgb),.12)}:host(.ion-color.activated){background:rgba(var(--ion-color-base-rgb),.16)}:host(.chip-outline){border-width:1px;border-style:solid;border-color:rgba(0,0,0,.32);background:transparent}:host(.chip-outline.ion-color){border-color:rgba(var(--ion-color-base-rgb),.32)}:host(.chip-outline:not(.ion-color):focus){background:rgba(0,0,0,.04)}:host(.chip-outline.activated:not(.ion-color)){background:rgba(0,0,0,.08)}::slotted(ion-icon){font-size:20px}:host(:not(.ion-color)) ::slotted(ion-icon){color:rgba(0,0,0,.54)}::slotted(ion-icon:first-child){margin-left:-4px;margin-right:8px;margin-top:-4px;margin-bottom:-4px}@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){::slotted(ion-icon:first-child){margin-left:unset;margin-right:unset;-webkit-margin-start:-4px;margin-inline-start:-4px;-webkit-margin-end:8px;margin-inline-end:8px}}::slotted(ion-icon:last-child){margin-left:8px;margin-right:-4px;margin-top:-4px;margin-bottom:-4px}@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){::slotted(ion-icon:last-child){margin-left:unset;margin-right:unset;-webkit-margin-start:8px;margin-inline-start:8px;-webkit-margin-end:-4px;margin-inline-end:-4px}}::slotted(ion-avatar){width:24px;height:24px}::slotted(ion-avatar:first-child){margin-left:-8px;margin-right:8px;margin-top:-4px;margin-bottom:-4px}@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){::slotted(ion-avatar:first-child){margin-left:unset;margin-right:unset;-webkit-margin-start:-8px;margin-inline-start:-8px;-webkit-margin-end:8px;margin-inline-end:8px}}::slotted(ion-avatar:last-child){margin-left:8px;margin-right:-8px;margin-top:-4px;margin-bottom:-4px}@supports ((-webkit-margin-start:0) or (margin-inline-start:0)) or (-webkit-margin-start:0){::slotted(ion-avatar:last-child){margin-left:unset;margin-right:unset;-webkit-margin-start:8px;margin-inline-start:8px;-webkit-margin-end:-8px;margin-inline-end:-8px}}:host(:focus){outline:none;--background:rgba(var(--ion-text-color-rgb,0,0,0),0.16)}:host(.activated){--background:rgba(var(--ion-text-color-rgb,0,0,0),0.2)}@media (any-hover:hover){:host(:hover){--background:rgba(var(--ion-text-color-rgb,0,0,0),0.16)}:host(.ion-color:hover){background:rgba(var(--ion-color-base-rgb),.12)}:host(.chip-outline:not(.ion-color):hover){background:rgba(var(--ion-text-color-rgb,0,0,0),.04)}}"}}}}]);
|
import { dispatch as d3_dispatch } from 'd3-dispatch';
import {
select as d3_select,
event as d3_event
} from 'd3-selection';
import { t } from '../../util/locale';
import {
behaviorBreathe,
behaviorHover
} from '../../behavior';
import {
osmEntity,
osmIntersection,
osmInferRestriction,
osmTurn
} from '../../osm';
import {
actionRestrictTurn,
actionUnrestrictTurn
} from '../../actions';
import {
geoExtent,
geoRawMercator
} from '../../geo';
import {
svgLayers,
svgLines,
svgTurns,
svgVertices
} from '../../svg';
import { utilRebind } from '../../util/rebind';
import { utilFunctor } from '../../util';
import {
utilGetDimensions,
utilSetDimensions
} from '../../util/dimensions';
export function uiFieldRestrictions(field, context) {
var dispatch = d3_dispatch('change'),
breathe = behaviorBreathe(context),
hover = behaviorHover(context),
initialized = false,
vertexID,
fromNodeID;
function restrictions(selection) {
// if form field is hidden or has detached from dom, clean up.
if (!d3_select('.inspector-wrap.inspector-hidden').empty() || !selection.node().parentNode) {
selection.call(restrictions.off);
return;
}
var wrap = selection.selectAll('.preset-input-wrap')
.data([0]);
var enter = wrap.enter()
.append('div')
.attr('class', 'preset-input-wrap');
enter
.append('div')
.attr('class', 'restriction-help');
var intersection = osmIntersection(context.graph(), vertexID),
graph = intersection.graph,
vertex = graph.entity(vertexID),
filter = utilFunctor(true),
extent = geoExtent(),
projection = geoRawMercator();
var d = utilGetDimensions(wrap.merge(enter)),
c = [d[0] / 2, d[1] / 2],
z = 24;
projection
.scale(256 * Math.pow(2, z) / (2 * Math.PI));
var s = projection(vertex.loc);
projection
.translate([c[0] - s[0], c[1] - s[1]])
.clipExtent([[0, 0], d]);
var drawLayers = svgLayers(projection, context).only('osm').dimensions(d),
drawVertices = svgVertices(projection, context),
drawLines = svgLines(projection, context),
drawTurns = svgTurns(projection, context);
enter
.call(drawLayers);
wrap = wrap
.merge(enter);
var surface = wrap.selectAll('.surface');
if (!enter.empty()) {
initialized = true;
surface
.call(breathe)
.call(hover);
}
surface
.call(utilSetDimensions, d)
.call(drawVertices, graph, [vertex], filter, extent, z)
.call(drawLines, graph, intersection.ways, filter)
.call(drawTurns, graph, intersection.turns(fromNodeID));
surface
.on('click.restrictions', click)
.on('mouseover.restrictions', mouseover)
.on('mouseout.restrictions', mouseout);
surface
.selectAll('.selected')
.classed('selected', false);
if (fromNodeID) {
surface
.selectAll('.' + intersection.highways[fromNodeID].id)
.classed('selected', true);
}
mouseout();
context.history()
.on('change.restrictions', render);
d3_select(window)
.on('resize.restrictions', function() {
utilSetDimensions(wrap, null);
render();
});
function click() {
surface
.call(breathe.off)
.call(breathe);
var datum = d3_event.target.__data__;
if (datum instanceof osmEntity) {
fromNodeID = intersection.adjacentNodeId(datum.id);
render();
} else if (datum instanceof osmTurn) {
if (datum.restriction) {
context.perform(
actionUnrestrictTurn(datum, projection),
t('operations.restriction.annotation.delete')
);
} else {
context.perform(
actionRestrictTurn(datum, projection),
t('operations.restriction.annotation.create')
);
}
}
}
function mouseover() {
var datum = d3_event.target.__data__;
if (datum instanceof osmTurn) {
var graph = context.graph(),
presets = context.presets(),
preset;
if (datum.restriction) {
preset = presets.match(graph.entity(datum.restriction), graph);
} else {
preset = presets.item('type/restriction/' +
osmInferRestriction(
graph,
datum.from,
datum.via,
datum.to,
projection
)
);
}
wrap.selectAll('.restriction-help')
.text(t('operations.restriction.help.' +
(datum.restriction ? 'toggle_off' : 'toggle_on'),
{ restriction: preset.name() })
);
}
}
function mouseout() {
wrap.selectAll('.restriction-help')
.text(t('operations.restriction.help.' +
(fromNodeID ? 'toggle' : 'select'))
);
}
function render() {
if (context.hasEntity(vertexID)) {
restrictions(selection);
}
}
}
restrictions.entity = function(_) {
if (!vertexID || vertexID !== _.id) {
fromNodeID = null;
vertexID = _.id;
}
};
restrictions.tags = function() {};
restrictions.focus = function() {};
restrictions.off = function(selection) {
if (!initialized) return;
selection.selectAll('.surface')
.call(hover.off)
.call(breathe.off)
.on('click.restrictions', null)
.on('mouseover.restrictions', null)
.on('mouseout.restrictions', null);
context.history()
.on('change.restrictions', null);
d3_select(window)
.on('resize.restrictions', null);
};
return utilRebind(restrictions, dispatch, 'on');
}
|
// tagget templates = processar o template dentro de uma função
function tag(partes, ...valores) {
console.log(partes)
console.log(valores)
return 'Outra String'
}
const aluno = 'Gui'
const situacao = 'Aprovado'
console.log(tag`${aluno} está ${situacao}.`)
|
/**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Need the following side-effect import because in actual production code,
// Fast Fetch impls are always loaded via an AmpAd tag, which means AmpAd is
// always available for them. However, when we test an impl in isolation,
// AmpAd is not loaded already, so we need to load it separately.
import '../../../amp-ad/0.1/amp-ad';
import {AmpA4A} from '../amp-a4a';
import {CONSENT_POLICY_STATE} from '../../../../src/consent-state';
import {
RTC_ERROR_ENUM,
RealTimeConfigManager,
} from '../real-time-config-manager';
import {Services} from '../../../../src/services';
import {Xhr} from '../../../../src/service/xhr-impl';
import {createElementWithAttributes} from '../../../../src/dom';
import {dev, user} from '../../../../src/log';
import {isFiniteNumber} from '../../../../src/types';
describes.realWin('real-time-config-manager', {amp: true}, (env) => {
let element;
let a4aElement;
let fetchJsonStub;
let getCalloutParam_, maybeExecuteRealTimeConfig_, validateRtcConfig_;
let truncUrl_, inflateAndSendRtc_, sendErrorMessage;
let rtc;
beforeEach(() => {
// Ensures window location == AMP cache passes.
env.win.__AMP_MODE.test = true;
const doc = env.win.document;
element = createElementWithAttributes(env.win.document, 'amp-ad', {
'width': '200',
'height': '50',
'type': 'doubleclick',
'layout': 'fixed',
});
doc.body.appendChild(element);
fetchJsonStub = env.sandbox.stub(Xhr.prototype, 'fetchJson');
a4aElement = new AmpA4A(element);
// RealTimeConfigManager uses the UrlReplacements service scoped to the A4A
// (FIE), but for testing stub in the parent service for simplicity.
const urlReplacements = Services.urlReplacementsForDoc(element);
env.sandbox
.stub(Services, 'urlReplacementsForDoc')
.withArgs(a4aElement.element)
.returns(urlReplacements);
rtc = new RealTimeConfigManager(a4aElement);
maybeExecuteRealTimeConfig_ = rtc.maybeExecuteRealTimeConfig.bind(rtc);
getCalloutParam_ = rtc.getCalloutParam_.bind(rtc);
validateRtcConfig_ = rtc.validateRtcConfig_.bind(rtc);
truncUrl_ = rtc.truncUrl_.bind(rtc);
inflateAndSendRtc_ = rtc.inflateAndSendRtc_.bind(rtc);
sendErrorMessage = rtc.sendErrorMessage.bind(rtc);
});
function setFetchJsonStubBehavior(params, response, isString, shouldFail) {
if (shouldFail) {
fetchJsonStub.withArgs(params).returns(Promise.reject('FAIL'));
} else {
const textFunction = () => {
return !isString
? Promise.resolve(JSON.stringify(response))
: Promise.resolve(response);
};
fetchJsonStub.withArgs(params).returns(
Promise.resolve({
status: 200,
text: textFunction,
})
);
}
}
function setRtcConfig(rtcConfig) {
element.setAttribute('rtc-config', JSON.stringify(rtcConfig));
}
describe('#truncUrl_', () => {
it('truncates URL', () => {
let url = 'https://www.example.biz/?';
for (let i = 0; i < 1000; i++) {
url += '&23456=8901234567';
}
expect(url.length).to.be.above(16384);
url = truncUrl_(url);
expect(url.length).to.be.at.most(16384);
expect(url).to.contain('&__trunc__=1');
});
});
describe('#getCalloutParam_', () => {
it('should convert url to callout param when parseable', () => {
const url = 'https://www.example.test/endpoint.php?unincluded';
const ard = getCalloutParam_(url);
expect(ard).to.equal('www.example.test/endpoint.php');
});
it('should convert & trunc url when parseable', () => {
const url =
'https://www.example.test/thisIsTooMany' +
'Characters1234567891011121314.php';
const ard = getCalloutParam_(url);
expect(ard).to.equal(
'www.example.test/thisIsTooManyCharacters1234567891'
);
});
});
describe('#maybeExecuteRealTimeConfig_', () => {
function executeTest(args) {
const {
urls,
vendors,
timeoutMillis,
rtcCalloutResponses,
expectedCalloutUrls,
responseIsString,
failXhr,
expectedRtcArray,
calloutCount,
} = args;
setRtcConfig({urls, vendors, timeoutMillis});
(expectedCalloutUrls || []).forEach((expectedUrl, i) => {
setFetchJsonStubBehavior(
expectedUrl,
rtcCalloutResponses[i],
responseIsString,
failXhr
);
});
const customMacros = args['customMacros'] || {};
const rtcResponsePromiseArray = maybeExecuteRealTimeConfig_(customMacros);
return rtcResponsePromiseArray.then((rtcResponseArray) => {
expect(rtcResponseArray.length).to.equal(expectedRtcArray.length);
expect(fetchJsonStub.callCount).to.equal(calloutCount);
(expectedCalloutUrls || []).forEach((url) => {
expect(fetchJsonStub).to.have.been.calledWith(url);
});
rtcResponseArray.forEach((rtcResponse, i) => {
expect(rtcResponse.response).to.deep.equal(
expectedRtcArray[i].response
);
expect(rtcResponse.callout).to.equal(expectedRtcArray[i].callout);
expect(rtcResponse.error).to.equal(expectedRtcArray[i].error);
expect(Object.keys(rtcResponse).sort()).to.deep.equal(
Object.keys(expectedRtcArray[i]).sort()
);
expect(isFiniteNumber(rtcResponse.rtcTime)).to.be.true;
});
});
}
const urlMacros = [
'slot_id=SLOT_ID',
'page_id=PAGE_ID',
'adx=ADX',
'ady=ADY',
];
function generateUrls(numUrls, numMacroUrls) {
const urls = [];
for (let i = 0; i < numUrls; i++) {
urls.push(`https://www.${i}.com/`);
}
for (let i = 0; i < numMacroUrls; i++) {
urls.push(
`https://www.${i + numUrls}.com/?${urlMacros
.slice(0, i + 1)
.join('&')}`
);
}
return urls;
}
function rtcEntry(response, url, error, isVendor) {
// If this is an entry for a vendor, then the callout is just
// the vendor name passed in to url here.
const callout = !!isVendor ? url : getCalloutParam_(url);
return response
? {response, callout, rtcTime: 10}
: {callout, error, rtcTime: 10};
}
function generateCalloutResponses(numGoodResponses) {
const rtcCalloutResponses = [];
let response;
for (let i = 0; i < numGoodResponses; i++) {
response = {};
response[`response${i}`] = {};
response[`response${i}`][`foo${i}`] = [`a${i}`, `b${i}`, `c${i}`];
rtcCalloutResponses.push(response);
}
return rtcCalloutResponses;
}
it('should send RTC callouts for all specified URLS without macros', () => {
const calloutCount = 5;
const urls = generateUrls(5);
const rtcCalloutResponses = [
{'response1': {'fooArray': ['foo']}},
{'response2': {'test': 'test2'}},
{'response3': {'apple': 'banana'}},
{
'response4': {
'animalArray': ['cat', 'dog'],
'foodObject': {'apple': true, 'car': false},
},
},
{'response5': [1, 2, 3]},
];
const expectedRtcArray = [];
urls.forEach((url, i) => {
expectedRtcArray.push({
callout: getCalloutParam_(url),
rtcTime: 10,
response: rtcCalloutResponses[i],
});
});
return executeTest({
urls,
inflatedUrls: urls,
rtcCalloutResponses,
calloutCount,
expectedCalloutUrls: urls,
expectedRtcArray,
});
});
it('should send only 5 RTC callouts for all URLS without macros', () => {
const urls = generateUrls(7);
const expectedCalloutUrls = generateUrls(5);
const rtcCalloutResponses = generateCalloutResponses(7);
const calloutCount = 5;
const expectedRtcArray = [];
for (let i = 0; i < 5; i++) {
expectedRtcArray.push(rtcEntry(rtcCalloutResponses[i], urls[i]));
}
expectedRtcArray.push(
rtcEntry(null, urls[5], RTC_ERROR_ENUM.MAX_CALLOUTS_EXCEEDED)
);
expectedRtcArray.push(
rtcEntry(null, urls[6], RTC_ERROR_ENUM.MAX_CALLOUTS_EXCEEDED)
);
return executeTest({
urls,
inflatedUrls: urls,
rtcCalloutResponses,
calloutCount,
expectedCalloutUrls,
expectedRtcArray,
});
});
it('should send RTC callouts to inflated publisher URLs', () => {
const urls = generateUrls(1, 2);
const inflatedUrls = [
'https://www.0.com/',
'https://www.1.com/?slot_id=1',
'https://www.2.com/?slot_id=1&page_id=2',
];
const rtcCalloutResponses = generateCalloutResponses(3);
const customMacros = {
SLOT_ID: 1,
PAGE_ID: () => 2,
FOO_ID: () => 3,
};
const expectedRtcArray = [];
rtcCalloutResponses.forEach((rtcResponse, i) => {
expectedRtcArray.push(rtcEntry(rtcResponse, inflatedUrls[i]));
});
const calloutCount = 3;
return executeTest({
urls,
customMacros,
inflatedUrls,
rtcCalloutResponses,
calloutCount,
expectedCalloutUrls: inflatedUrls,
expectedRtcArray,
});
});
it('should send RTC callouts to inflated vendor URLs', () => {
const vendors = {
'fAkeVeNdOR': {SLOT_ID: 1, PAGE_ID: 2},
};
const inflatedUrls = [
'https://localhost:8000/examples/rtcE1.json?slot_id=1&page_id=3&foo_id=4',
];
const rtcCalloutResponses = [{'response1': {'fooArray': ['foo']}}];
const customMacros = {
PAGE_ID: () => 3,
FOO_ID: () => 4,
};
const calloutCount = 1;
const expectedRtcArray = [];
expectedRtcArray.push(
rtcEntry(
rtcCalloutResponses[0],
Object.keys(vendors)[0].toLowerCase(),
undefined,
true
)
);
return executeTest({
vendors,
customMacros,
inflatedUrls,
rtcCalloutResponses,
calloutCount,
expectedCalloutUrls: inflatedUrls,
expectedRtcArray,
});
});
it('should send callouts to vendor URLs with object/array macros', () => {
const vendors = {
'fAkeVeNdOR': {
SLOT_ID: {'key': 'value'},
PAGE_ID: [1, 2, 3],
FOO_ID: 'String',
},
};
const inflatedUrls = [
'https://localhost:8000/examples/rtcE1.json?slot_id=%7B%22key%22%3A%22' +
'value%22%7D&page_id=%5B1%2C2%2C3%5D&foo_id=String',
];
const rtcCalloutResponses = [{'response1': {'fooArray': ['foo']}}];
const calloutCount = 1;
const expectedRtcArray = [];
expectedRtcArray.push(
rtcEntry(
rtcCalloutResponses[0],
Object.keys(vendors)[0].toLowerCase(),
undefined,
true
)
);
return executeTest({
vendors,
inflatedUrls,
rtcCalloutResponses,
calloutCount,
expectedCalloutUrls: inflatedUrls,
expectedRtcArray,
});
});
it('should send RTC callouts to inflated publisher and vendor URLs', () => {
const urls = generateUrls(2, 2);
const vendors = {
'fAkeVeNdOR': {SLOT_ID: 0, PAGE_ID: 1},
};
const inflatedUrls = [
'https://www.0.com/',
'https://www.1.com/',
'https://www.2.com/?slot_id=1',
'https://www.3.com/?slot_id=1&page_id=2',
'https://localhost:8000/examples/rtcE1.json?slot_id=1&page_id=2&foo_id=3',
];
const rtcCalloutResponses = generateCalloutResponses(5);
const customMacros = {
SLOT_ID: 1,
PAGE_ID: () => 2,
FOO_ID: () => 3,
};
const expectedRtcArray = [];
for (let i = 0; i < 4; i++) {
expectedRtcArray.push(
rtcEntry(rtcCalloutResponses[i], inflatedUrls[i])
);
}
expectedRtcArray.push(
rtcEntry(
rtcCalloutResponses[4],
Object.keys(vendors)[0].toLowerCase(),
undefined,
true
)
);
const calloutCount = 5;
return executeTest({
urls,
vendors,
customMacros,
inflatedUrls,
rtcCalloutResponses,
calloutCount,
expectedCalloutUrls: inflatedUrls,
expectedRtcArray,
});
});
it('should ignore bad macros for vendor urls', () => {
const vendors = {
'fAkeVeNdOR': {'slot_id=SLOT_ID': 0, PAGE_ID: 1},
};
const inflatedUrls = [
'https://localhost:8000/examples/rtcE1.json?slot_id=SLOT_ID&page_id=1&foo_id=FOO_ID',
];
const rtcCalloutResponses = generateCalloutResponses(1);
const expectedRtcArray = [];
for (let i = 0; i < 1; i++) {
expectedRtcArray.push(
rtcEntry(
rtcCalloutResponses[i],
Object.keys(vendors)[0].toLowerCase(),
undefined,
true
)
);
}
const calloutCount = 1;
env.sandbox.stub(user(), 'error').callsFake(() => {});
return executeTest({
vendors,
inflatedUrls,
rtcCalloutResponses,
calloutCount,
expectedCalloutUrls: inflatedUrls,
expectedRtcArray,
});
});
it('should favor publisher URLs over vendor URLs', () => {
const urls = generateUrls(3, 2);
const vendors = {
'fAkeVeNdOR': {SLOT_ID: 0, PAGE_ID: 1},
};
const inflatedUrls = [
'https://www.0.com/',
'https://www.1.com/',
'https://www.2.com/',
'https://www.3.com/?slot_id=1',
'https://www.4.com/?slot_id=1&page_id=2',
];
const rtcCalloutResponses = generateCalloutResponses(6);
const customMacros = {
SLOT_ID: 1,
PAGE_ID: () => 2,
FOO_ID: () => 3,
};
const expectedRtcArray = [];
for (let i = 0; i < 5; i++) {
expectedRtcArray.push(
rtcEntry(rtcCalloutResponses[i], inflatedUrls[i])
);
}
expectedRtcArray.push(
rtcEntry(
null,
Object.keys(vendors)[0].toLowerCase(),
RTC_ERROR_ENUM.MAX_CALLOUTS_EXCEEDED,
true
)
);
const calloutCount = 5;
return executeTest({
urls,
vendors,
customMacros,
rtcCalloutResponses,
calloutCount,
expectedCalloutUrls: inflatedUrls,
expectedRtcArray,
});
});
it('should not send more than one RTC callout to the same url', () => {
const urls = ['https://www.0.com/', 'https://www.0.com/'];
const rtcCalloutResponses = generateCalloutResponses(1);
const calloutCount = 1;
const expectedCalloutUrls = ['https://www.0.com/'];
const expectedRtcArray = [
{
response: rtcCalloutResponses[0],
callout: getCalloutParam_(urls[0]),
rtcTime: 10,
},
{
callout: getCalloutParam_(urls[1]),
error: RTC_ERROR_ENUM.DUPLICATE_URL,
rtcTime: 10,
},
];
return executeTest({
urls,
inflatedUrls: urls,
rtcCalloutResponses,
calloutCount,
expectedCalloutUrls,
expectedRtcArray,
});
});
it('should not send an RTC callout to an insecure url', () => {
const urls = [
'https://www.1.com/',
'https://www.2.com',
'http://www.insecure.biz/',
];
const rtcCalloutResponses = [
{'response1': {'fooArray': ['foo']}},
{'response2': {'insecure': ['virus']}},
];
const calloutCount = 2;
const expectedCalloutUrls = ['https://www.1.com/', 'https://www.2.com'];
const expectedRtcArray = [
{
response: rtcCalloutResponses[0],
callout: getCalloutParam_(urls[0]),
rtcTime: 10,
},
{
response: rtcCalloutResponses[1],
callout: getCalloutParam_(urls[1]),
rtcTime: 10,
},
{
callout: getCalloutParam_(urls[2]),
error: RTC_ERROR_ENUM.INSECURE_URL,
rtcTime: 10,
},
];
return executeTest({
urls,
inflatedUrls: urls,
rtcCalloutResponses,
calloutCount,
expectedCalloutUrls,
expectedRtcArray,
});
});
it('should not send RTC callout to unknown vendor', () => {
const vendors = {
'unknownvendor': {SLOT_ID: 1, PAGE_ID: 2},
};
const calloutCount = 0;
const expectedRtcArray = [];
expectedRtcArray.push(
rtcEntry(
null,
Object.keys(vendors)[0].toLowerCase(),
RTC_ERROR_ENUM.UNKNOWN_VENDOR,
true
)
);
return executeTest({vendors, calloutCount, expectedRtcArray});
});
it('should handle bad JSON response', () => {
const urls = generateUrls(1);
const rtcCalloutResponses = ['{foo:bar'];
const expectedRtcArray = [];
rtcCalloutResponses.forEach((rtcResponse, i) => {
expectedRtcArray.push(
rtcEntry(null, urls[i], RTC_ERROR_ENUM.MALFORMED_JSON_RESPONSE)
);
});
const calloutCount = 1;
return executeTest({
urls,
inflatedUrls: urls,
rtcCalloutResponses,
calloutCount,
expectedCalloutUrls: urls,
expectedRtcArray,
responseIsString: true,
});
});
it('should catch errors due to network failure', () => {
const urls = generateUrls(1);
const rtcCalloutResponses = generateCalloutResponses(1);
const expectedRtcArray = [];
rtcCalloutResponses.forEach((rtcResponse, i) => {
expectedRtcArray.push(
rtcEntry(null, urls[i], RTC_ERROR_ENUM.NETWORK_FAILURE)
);
});
const calloutCount = 1;
return executeTest({
urls,
inflatedUrls: urls,
rtcCalloutResponses,
calloutCount,
expectedCalloutUrls: urls,
expectedRtcArray,
failXhr: true,
});
});
for (const consentState in CONSENT_POLICY_STATE) {
it(`should handle consentState ${consentState}`, () => {
setRtcConfig({urls: ['https://foo.com']});
const rtcResult = maybeExecuteRealTimeConfig_(
{},
CONSENT_POLICY_STATE[consentState]
);
switch (CONSENT_POLICY_STATE[consentState]) {
case CONSENT_POLICY_STATE.SUFFICIENT:
case CONSENT_POLICY_STATE.UNKNOWN_NOT_REQUIRED:
expect(rtcResult).to.be.ok;
return rtcResult.then(() => expect(fetchJsonStub).to.be.calledOnce);
case CONSENT_POLICY_STATE.UNKNOWN:
case CONSENT_POLICY_STATE.INSUFFICIENT:
return rtcResult.then((result) => {
expect(result).to.deep.equal([]);
expect(fetchJsonStub).to.not.be.called;
});
break;
default:
throw new Error(`unknown consent state ${consentState}`);
}
});
}
});
describe('#validateRtcConfig', () => {
let validatedRtcConfig;
afterEach(() => {
element.removeAttribute('rtc-config');
});
it('should return parsed rtcConfig for valid rtcConfig', () => {
const rtcConfig = {
'vendors': {
'fakeVendor': {'SLOT_ID': '1', 'PAGE_ID': '1'},
'nonexistent-vendor': {'SLOT_ID': '1'},
'fakeVendor2': {'SLOT_ID': '1'},
},
'urls': [
'https://localhost:4443/posts?slot_id=SLOT_ID',
'https://broken.zzzzzzz',
],
'timeoutMillis': 500,
};
setRtcConfig(rtcConfig);
validateRtcConfig_(element);
expect(rtc.rtcConfig_).to.be.ok;
expect(rtc.rtcConfig_).to.deep.equal(rtcConfig);
});
it('should allow timeout of 0', () => {
const rtcConfig = {
'vendors': {
'fakeVendor': {'SLOT_ID': '1', 'PAGE_ID': '1'},
'nonexistent-vendor': {'SLOT_ID': '1'},
'fakeVendor2': {'SLOT_ID': '1'},
},
'urls': [
'https://localhost:4443/posts?slot_id=SLOT_ID',
'https://broken.zzzzzzz',
],
'timeoutMillis': 0,
};
setRtcConfig(rtcConfig);
validateRtcConfig_(element);
expect(rtc.rtcConfig_).to.be.ok;
expect(rtc.rtcConfig_).to.deep.equal(rtcConfig);
});
it('should not allow timeout greater than default', () => {
const rtcConfig = {
'vendors': {
'fakeVendor': {'SLOT_ID': '1', 'PAGE_ID': '1'},
'nonexistent-vendor': {'SLOT_ID': '1'},
'fakeVendor2': {'SLOT_ID': '1'},
},
'urls': [
'https://localhost:4443/posts?slot_id=SLOT_ID',
'https://broken.zzzzzzz',
],
'timeoutMillis': 1000000,
};
const expectedRtcConfig = {
'vendors': {
'fakeVendor': {'SLOT_ID': '1', 'PAGE_ID': '1'},
'nonexistent-vendor': {'SLOT_ID': '1'},
'fakeVendor2': {'SLOT_ID': '1'},
},
'urls': [
'https://localhost:4443/posts?slot_id=SLOT_ID',
'https://broken.zzzzzzz',
],
'timeoutMillis': 1000,
};
setRtcConfig(rtcConfig);
validateRtcConfig_(element);
expect(rtc.rtcConfig_).to.be.ok;
expect(rtc.rtcConfig_).to.deep.equal(expectedRtcConfig);
});
it('should return false if rtc-config not specified', () => {
expect(validateRtcConfig_(element)).to.be.false;
});
// Test various misconfigurations that are missing vendors or urls.
[
{'timeoutMillis': 500},
{'vendors': {}},
{'urls': []},
{'vendors': {}, 'urls': []},
{'vendors': 'incorrect', 'urls': 'incorrect'},
].forEach((rtcConfig) => {
it('should return false for rtcConfig missing required values', () => {
setRtcConfig(rtcConfig);
allowConsoleError(() => {
dev().error('RTCTESTS', 'Error');
validatedRtcConfig = validateRtcConfig_(element);
});
expect(validatedRtcConfig).to.be.false;
});
});
it('should return false for bad JSON rtcConfig', () => {
const rtcConfig = '{"urls" : ["https://google.com"]';
element.setAttribute('rtc-config', rtcConfig);
validatedRtcConfig = validateRtcConfig_(element);
expect(validatedRtcConfig).to.be.false;
});
});
describe('#inflateAndSendRtc_', () => {
it('should not send RTC if macro expansion exceeds timeout', () => {
const url = 'https://www.example.biz/?dummy=DUMMY';
rtc.rtcConfig_ = {
timeoutMillis: 10,
};
const macroDelay = 20;
const macros = {
DUMMY: () => {
return Services.timerFor(env.win)
.promise(macroDelay)
.then(() => {
return 'foo';
});
},
};
inflateAndSendRtc_(url, macros);
return rtc.promiseArray_[0].then((errorResponse) => {
expect(errorResponse.error).to.equal(
RTC_ERROR_ENUM.MACRO_EXPAND_TIMEOUT
);
});
});
it('should not send RTC if no longer current', () => {
const url = 'https://www.example.biz/';
rtc.rtcConfig_ = {
timeoutMillis: 1000,
};
const macros = {};
// Simulate an unlayoutCallback call
inflateAndSendRtc_(url, macros);
a4aElement.promiseId_++;
return rtc.promiseArray_[0].then((errorResponse) => {
expect(errorResponse).to.be.undefined;
});
});
});
describe('modifyRtcConfigForConsentStateSettings', () => {
beforeEach(() => {
rtc.rtcConfig_ = {
'vendors': {
'vendorA': {'SLOT_ID': '1', 'PAGE_ID': '1'},
'vendorB': {'SLOT_ID': '1'},
'vendorC': {'PAGE_ID': '1'},
},
'urls': [
'https://www.rtc.com/example1',
'https://www.other-rtc.com/example2',
],
'timeoutMillis': 500,
};
});
it('should not modify rtcConfig if consent state is valid', () => {
const expectedRtcConfig = {...rtc.rtcConfig_};
rtc.consentState_ = CONSENT_POLICY_STATE.SUFFICIENT;
rtc.modifyRtcConfigForConsentStateSettings();
expect(rtc.rtcConfig_).to.deep.equal(expectedRtcConfig);
});
it('should clear all callouts if global setting mismatched', () => {
rtc.rtcConfig_.sendRegardlessOfConsentState = ['INSUFFICIENT'];
const expectedRtcConfig = {...rtc.rtcConfig_};
expectedRtcConfig.vendors = {};
expectedRtcConfig.urls = [];
rtc.consentState_ = CONSENT_POLICY_STATE.UNKNOWN;
rtc.modifyRtcConfigForConsentStateSettings();
expect(rtc.rtcConfig_).to.deep.equal(expectedRtcConfig);
});
it('should handle empty urls array', () => {
rtc.consentState_ = CONSENT_POLICY_STATE.UNKNOWN;
rtc.rtcConfig_.urls = [];
expect(rtc.modifyRtcConfigForConsentStateSettings()).not.to.throw;
});
it('should handle empty vendors object', () => {
rtc.consentState_ = CONSENT_POLICY_STATE.UNKNOWN;
rtc.rtcConfig_.vendors = {};
expect(rtc.modifyRtcConfigForConsentStateSettings()).not.to.throw;
});
it('should handle missing urls array', () => {
rtc.consentState_ = CONSENT_POLICY_STATE.UNKNOWN;
rtc.rtcConfig_.urls = undefined;
expect(rtc.modifyRtcConfigForConsentStateSettings()).not.to.throw;
});
it('should handle missing vendors object', () => {
rtc.consentState_ = CONSENT_POLICY_STATE.UNKNOWN;
rtc.rtcConfig_.vendors = undefined;
expect(rtc.modifyRtcConfigForConsentStateSettings()).not.to.throw;
});
it('should clear just invalid custom URLs', () => {
rtc.rtcConfig_.vendors = {
'vendorA': {
'sendRegardlessOfConsentState': true,
'macros': {'SLOT_ID': '1', 'PAGE_ID': '1'},
},
'vendorB': {
'sendRegardlessOfConsentState': ['INSUFFICIENT', 'UNKNOWN'],
'macros': {'SLOT_ID': '1'},
},
'vendorC': {
'sendRegardlessOfConsentState': ['UNKNOWN'],
'macros': {'SLOT_ID': '1'},
},
};
const expectedRtcConfig = {...rtc.rtcConfig_};
expectedRtcConfig.urls = [];
rtc.consentState_ = CONSENT_POLICY_STATE.UNKNOWN;
rtc.modifyRtcConfigForConsentStateSettings();
expect(rtc.rtcConfig_).to.deep.equal(expectedRtcConfig);
});
it('should clear just invalid vendor callouts', () => {
rtc.rtcConfig_.urls = [
{
'sendRegardlessOfConsentState': true,
'url': 'https://www.rtc.com/example1',
},
{
'sendRegardlessOfConsentState': ['INSUFFICIENT', 'UNKNOWN'],
'url': 'https://www.other-rtc.com/example2',
},
];
const expectedRtcConfig = {...rtc.rtcConfig_};
expectedRtcConfig.vendors = {};
rtc.consentState_ = CONSENT_POLICY_STATE.INSUFFICIENT;
rtc.modifyRtcConfigForConsentStateSettings();
expect(rtc.rtcConfig_).to.deep.equal(expectedRtcConfig);
});
it('should not clear callouts if per-callout setting valid', () => {
rtc.rtcConfig_.vendors = {
'vendorA': {
'sendRegardlessOfConsentState': true,
'macros': {'SLOT_ID': '1', 'PAGE_ID': '1'},
},
'vendorB': {
'sendRegardlessOfConsentState': ['UNKNOWN'],
'macros': {'SLOT_ID': '1'},
},
'vendorC': {'SLOT_ID': '1'},
};
rtc.rtcConfig_.urls = [
{
'sendRegardlessOfConsentState': true,
'url': 'https://www.rtc.com/example1',
},
'https://www.other-rtc.com/example2',
];
const expectedRtcConfig = {...rtc.rtcConfig_};
expectedRtcConfig.vendors = {
'vendorA': {
'sendRegardlessOfConsentState': true,
'macros': {'SLOT_ID': '1', 'PAGE_ID': '1'},
},
};
expectedRtcConfig.urls = [
{
'sendRegardlessOfConsentState': true,
'url': 'https://www.rtc.com/example1',
},
];
rtc.consentState_ = CONSENT_POLICY_STATE.INSUFFICIENT;
rtc.modifyRtcConfigForConsentStateSettings();
expect(rtc.rtcConfig_).to.deep.equal(expectedRtcConfig);
});
it('should handle mix of global and individual consent settings', () => {
rtc.rtcConfig_.vendors = {
'vendorA': {
'sendRegardlessOfConsentState': true,
'macros': {'SLOT_ID': '1', 'PAGE_ID': '1'},
},
'vendorB': {
'sendRegardlessOfConsentState': ['UNKNOWN'],
'macros': {'SLOT_ID': '1'},
},
'vendorC': {'SLOT_ID': '1'},
};
rtc.rtcConfig_.urls = [
{
'sendRegardlessOfConsentState': true,
'url': 'https://www.rtc.com/example1',
},
'https://www.other-rtc.com/example2',
];
rtc.rtcConfig_.sendRegardlessOfConsentState = ['INSUFFICIENT'];
const expectedRtcConfig = {...rtc.rtcConfig_};
expectedRtcConfig.vendors = {
'vendorA': {
'sendRegardlessOfConsentState': true,
'macros': {'SLOT_ID': '1', 'PAGE_ID': '1'},
},
'vendorC': {'SLOT_ID': '1'},
};
expectedRtcConfig.urls = [
{
'sendRegardlessOfConsentState': true,
'url': 'https://www.rtc.com/example1',
},
'https://www.other-rtc.com/example2',
];
rtc.consentState_ = CONSENT_POLICY_STATE.INSUFFICIENT;
rtc.modifyRtcConfigForConsentStateSettings();
expect(rtc.rtcConfig_).to.deep.equal(expectedRtcConfig);
});
it('should always clear RTC for a new consent state', () => {
rtc.consentState_ = 'FAKE_NEW_CONSENT_STATE';
const expectedRtcConfig = {...rtc.rtcConfig_};
rtc.modifyRtcConfigForConsentStateSettings();
expectedRtcConfig.urls = [];
expectedRtcConfig.vendors = {};
expect(rtc.rtcConfig_).to.deep.equal(expectedRtcConfig);
});
it('should not clear RTC for a null consent state', () => {
rtc.consentState_ = null;
const expectedRtcConfig = {...rtc.rtcConfig_};
rtc.modifyRtcConfigForConsentStateSettings();
expect(rtc.rtcConfig_).to.deep.equal(expectedRtcConfig);
});
});
describe('sendErrorMessage', () => {
let imageStub, requestUrl;
let errorType, errorReportingUrl;
let imageMock;
beforeEach(() => {
// Make sure that we always send the message, as we are using
// the check Math.random() < reporting frequency.
env.sandbox.stub(Math, 'random').returns(0);
env.sandbox.stub(Xhr.prototype, 'fetch');
imageMock = {};
imageStub = env.sandbox.stub(env.win, 'Image').returns(imageMock);
errorType = RTC_ERROR_ENUM.TIMEOUT;
errorReportingUrl = 'https://www.example.test?e=ERROR_TYPE&h=HREF';
const whitelist = {ERROR_TYPE: true, HREF: true};
const macros = {
ERROR_TYPE: errorType,
HREF: env.win.location.href,
};
requestUrl = Services.urlReplacementsForDoc(
a4aElement.element
).expandUrlSync(errorReportingUrl, macros, whitelist);
});
it('should send error message pingback to correct url', () => {
sendErrorMessage(errorType, errorReportingUrl);
expect(imageStub).to.be.calledOnce;
expect(imageMock.src).to.equal(requestUrl);
});
});
});
|
'use strict'
const { initCharCheck } = require('./utility')
const argv = process.argv
const initTap = argv.some((a) => a === '--tap' || a === '-t')
const initPersist = initTap || argv.some((a) => a === '--persist' || a === '-p')
const initVerbose = !initTap && argv.some((a) => a === '--verbose' || a === '-v')
const state = {
queue: [],
counts: {},
fileTestCount: 0,
tap: initTap,
persist: initPersist,
verbose: initVerbose
}
const _setup = async (opts = {}) => {
const setForKey = (k) => opts[k] !== undefined ? !!opts[k] : state[k]
state.tap = setForKey('tap')
state.persist = state.tap || setForKey('persist')
state.verbose = !state.tap && setForKey('verbose')
state.fileName = opts.fileName
await initCharCheck()
}
const setup = (opts = {}) => state.queue.push({
fn: () => _setup(opts),
fileName: opts.fileName
})
module.exports = { state, setup, _setup }
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var Class = require('../../utils/Class');
var CONST = require('../const');
var File = require('../File');
var FileTypesManager = require('../FileTypesManager');
var GetFastValue = require('../../utils/object/GetFastValue');
var IsPlainObject = require('../../utils/object/IsPlainObject');
/**
* @classdesc
* A single CSS File suitable for loading by the Loader.
*
* These are created when you use the Phaser.Loader.LoaderPlugin#css method and are not typically created directly.
*
* For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#css.
*
* @class CSSFile
* @extends Phaser.Loader.File
* @memberof Phaser.Loader.FileTypes
* @constructor
* @since 3.17.0
*
* @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file.
* @param {(string|Phaser.Types.Loader.FileTypes.CSSFileConfig)} key - The key to use for this file, or a file configuration object.
* @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `<key>.js`, i.e. if `key` was "alien" then the URL will be "alien.js".
* @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - Extra XHR Settings specifically for this file.
*/
var CSSFile = new Class({
Extends: File,
initialize:
function CSSFile (loader, key, url, xhrSettings)
{
var extension = 'css';
if (IsPlainObject(key))
{
var config = key;
key = GetFastValue(config, 'key');
url = GetFastValue(config, 'url');
xhrSettings = GetFastValue(config, 'xhrSettings');
extension = GetFastValue(config, 'extension', extension);
}
var fileConfig = {
type: 'script',
cache: false,
extension: extension,
responseType: 'text',
key: key,
url: url,
xhrSettings: xhrSettings
};
File.call(this, loader, fileConfig);
},
/**
* Called automatically by Loader.nextFile.
* This method controls what extra work this File does with its loaded data.
*
* @method Phaser.Loader.FileTypes.CSSFile#onProcess
* @since 3.17.0
*/
onProcess: function ()
{
this.state = CONST.FILE_PROCESSING;
this.data = document.createElement('style');
this.data.defer = false;
this.data.innerHTML = this.xhrLoader.responseText;
document.head.appendChild(this.data);
this.onProcessComplete();
}
});
/**
* Adds a CSS file, or array of CSS files, to the current load queue.
*
* You can call this method from within your Scene's `preload`, along with any other files you wish to load:
*
* ```javascript
* function preload ()
* {
* this.load.css('headers', 'styles/headers.css');
* }
* ```
*
* The file is **not** loaded right away. It is added to a queue ready to be loaded either when the loader starts,
* or if it's already running, when the next free load slot becomes available. This happens automatically if you
* are calling this from within the Scene's `preload` method, or a related callback. Because the file is queued
* it means you cannot use the file immediately after calling this method, but must wait for the file to complete.
* The typical flow for a Phaser Scene is that you load assets in the Scene's `preload` method and then when the
* Scene's `create` method is called you are guaranteed that all of those assets are ready for use and have been
* loaded.
*
* The key must be a unique String and not already in-use by another file in the Loader.
*
* Instead of passing arguments you can pass a configuration object, such as:
*
* ```javascript
* this.load.css({
* key: 'headers',
* url: 'styles/headers.css'
* });
* ```
*
* See the documentation for `Phaser.Types.Loader.FileTypes.CSSFileConfig` for more details.
*
* Once the file has finished loading it will automatically be converted into a style DOM element
* via `document.createElement('style')`. It will have its `defer` property set to false and then the
* resulting element will be appended to `document.head`. The CSS styles are then applied to the current document.
*
* The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
*
* If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
* and no URL is given then the Loader will set the URL to be "alien.css". It will always add `.css` as the extension, although
* this can be overridden if using an object instead of method arguments. If you do not desire this action then provide a URL.
*
* Note: The ability to load this type of file will only be available if the CSS File type has been built into Phaser.
* It is available in the default build but can be excluded from custom builds.
*
* @method Phaser.Loader.LoaderPlugin#css
* @fires Phaser.Loader.LoaderPlugin#ADD
* @since 3.17.0
*
* @param {(string|Phaser.Types.Loader.FileTypes.CSSFileConfig|Phaser.Types.Loader.FileTypes.CSSFileConfig[])} key - The key to use for this file, or a file configuration object, or array of them.
* @param {string} [url] - The absolute or relative URL to load this file from. If undefined or `null` it will be set to `<key>.css`, i.e. if `key` was "alien" then the URL will be "alien.css".
* @param {Phaser.Types.Loader.XHRSettingsObject} [xhrSettings] - An XHR Settings configuration object. Used in replacement of the Loaders default XHR Settings.
*
* @return {this} The Loader instance.
*/
FileTypesManager.register('css', function (key, url, xhrSettings)
{
if (Array.isArray(key))
{
for (var i = 0; i < key.length; i++)
{
// If it's an array it has to be an array of Objects, so we get everything out of the 'key' object
this.addFile(new CSSFile(this, key[i]));
}
}
else
{
this.addFile(new CSSFile(this, key, url, xhrSettings));
}
return this;
});
module.exports = CSSFile;
|
// DO NOT EDIT! This test has been generated by tools/gentest.py.
// OffscreenCanvas test in a worker:size.attributes.idl.set.zero
// Description:Setting width/height IDL attributes to 0
// Note:
importScripts("/resources/testharness.js");
importScripts("/2dcontext/resources/canvas-tests.js");
var t = async_test("Setting width/height IDL attributes to 0");
var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
throw reason;
});
t.step(function() {
var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');
offscreenCanvas.width = 0;
offscreenCanvas.height = 0;
_assertSame(offscreenCanvas.width, 0, "offscreenCanvas.width", "0");
_assertSame(offscreenCanvas.height, 0, "offscreenCanvas.height", "0");
t.done();
});
done();
|
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var resolve = require( 'path' ).resolve;
var tape = require( 'tape' );
var isnanf = require( '@stdlib/math/base/assert/is-nanf' );
var Complex64 = require( '@stdlib/complex/float32' );
var realf = require( '@stdlib/complex/realf' );
var imagf = require( '@stdlib/complex/imagf' );
var tryRequire = require( '@stdlib/utils/try-require' );
// VARIABLES //
var caddf = tryRequire( resolve( __dirname, './../lib/native.js' ) );
var opts = {
'skip': ( caddf instanceof Error )
};
// TESTS //
tape( 'main export is a function', opts, function test( t ) {
t.ok( true, __filename );
t.strictEqual( typeof caddf, 'function', 'main export is a function' );
t.end();
});
tape( 'the function adds two complex numbers', opts, function test( t ) {
var z1;
var z2;
var v;
z1 = new Complex64( 5.0, 3.0 );
z2 = new Complex64( -2.0, 1.0 );
v = caddf( z1, z2 );
t.strictEqual( realf( v ), 3.0, 'returns expected value' );
t.strictEqual( imagf( v ), 4.0, 'returns expected value' );
t.end();
});
tape( 'if a real or imaginary component is `NaN`, the resulting component is `NaN`', opts, function test( t ) {
var z1;
var z2;
var v;
z1 = new Complex64( NaN, 3.0 );
z2 = new Complex64( -2.0, 1.0 );
v = caddf( z1, z2 );
t.strictEqual( isnanf( realf( v ) ), true, 'returns expected value' );
t.strictEqual( imagf( v ), 4.0, 'returns expected value' );
z1 = new Complex64( 5.0, 3.0 );
z2 = new Complex64( NaN, 1.0 );
v = caddf( z1, z2 );
t.strictEqual( isnanf( realf( v ) ), true, 'returns expected value' );
t.strictEqual( imagf( v ), 4.0, 'returns expected value' );
z1 = new Complex64( NaN, 3.0 );
z2 = new Complex64( NaN, 1.0 );
v = caddf( z1, z2 );
t.strictEqual( isnanf( realf( v ) ), true, 'returns expected value' );
t.strictEqual( imagf( v ), 4.0, 'returns expected value' );
z1 = new Complex64( 5.0, NaN );
z2 = new Complex64( -2.0, 1.0 );
v = caddf( z1, z2 );
t.strictEqual( realf( v ), 3.0, 'returns expected value' );
t.strictEqual( isnanf( imagf( v ) ), true, 'returns expected value' );
z1 = new Complex64( 5.0, 3.0 );
z2 = new Complex64( -2.0, NaN );
v = caddf( z1, z2 );
t.strictEqual( realf( v ), 3.0, 'returns expected value' );
t.strictEqual( isnanf( imagf( v ) ), true, 'returns expected value' );
z1 = new Complex64( 5.0, NaN );
z2 = new Complex64( -2.0, NaN );
v = caddf( z1, z2 );
t.strictEqual( realf( v ), 3.0, 'returns expected value' );
t.strictEqual( isnanf( imagf( v ) ), true, 'returns expected value' );
z1 = new Complex64( NaN, NaN );
z2 = new Complex64( NaN, NaN );
v = caddf( z1, z2 );
t.strictEqual( isnanf( realf( v ) ), true, 'returns expected value' );
t.strictEqual( isnanf( imagf( v ) ), true, 'returns expected value' );
t.end();
});
|
// https://www.javacodegeeks.com/2015/02/testing-grunt-plugin-from-grunt.html
module.exports = function (grunt) {
var loader = require("./grunt-hacks.js");
var gLoad = require('./grunt.load.this');
grunt.initConfig({
copy: {
fix: {
files: [{
src: './fixtures/style.min.css',
dest: '../scratch/test/css/style.min.css'
},
{
src: './fixtures/replace1.txt',
dest: '../scratch/test/replace1.txt'
}],
}
},
build_include: {
default: {
options: {
match: 'buildInclude'
},
src: './fixtures/recursive03.txt',
dest: '../scratch/test/recursive03_replaced.txt'
}
}
});
gLoad(grunt);
loader.loadParentNpmTasks(grunt, 'grunt-contrib-copy');
grunt.registerTask('default', ['copy:fix', 'build_include:default']);
};
|
import React from "react";
import Component from "hyper/component";
import spotify from "spotify-node-applescript";
import SvgIcon from "../utils/svg-icon";
class PluginIcon extends Component {
render() {
return (
<SvgIcon>
<g fill="none" fillRule="evenodd">
<g fill="none" fillRule="evenodd">
<g
className="spotify-icon"
transform="translate(1.000000, 1.000000)"
>
<g>
<path
d="m7.49996,1.06347c-3.55479,0 -6.43665,2.88178 -6.43665,6.43657c0,3.55494 2.88186,6.43649 6.43665,6.43649c3.55517,0 6.43672,-2.88155 6.43672,-6.43649c0,-3.55456 -2.88155,-6.43626 -6.4368,-6.43626l0.00008,-0.00031zm2.9518,9.28338c-0.11529,0.18908 -0.36279,0.24903 -0.55187,0.13297c-1.51126,-0.92311 -3.41374,-1.13218 -5.65427,-0.62028c-0.21591,0.04919 -0.43112,-0.08609 -0.48031,-0.30207c-0.04942,-0.21598 0.08532,-0.4312 0.30176,-0.48039c2.45189,-0.5604 4.55507,-0.31898 6.25172,0.71789c0.18908,0.11606 0.24903,0.36279 0.13297,0.55187zm0.78783,-1.75284c-0.14527,0.23635 -0.45425,0.31091 -0.69022,0.16564c-1.73016,-1.06369 -4.36752,-1.37168 -6.41397,-0.75048c-0.2654,0.08017 -0.54572,-0.06941 -0.62627,-0.33435c-0.07994,-0.2654 0.06971,-0.54518 0.33466,-0.62589c2.3376,-0.70928 5.24367,-0.36571 7.23055,0.85524c0.23597,0.14527 0.31052,0.45425 0.16525,0.68991l0,-0.00008zm0.06764,-1.82501c-2.0745,-1.23217 -5.49716,-1.34547 -7.47782,-0.74433c-0.31805,0.09646 -0.6544,-0.08309 -0.75079,-0.40114c-0.09638,-0.31821 0.08301,-0.65433 0.4013,-0.75102c2.27365,-0.69022 6.05334,-0.55686 8.44174,0.86101c0.28669,0.16979 0.38047,0.53926 0.2106,0.82496c-0.1691,0.28608 -0.53957,0.38039 -0.82473,0.21052l-0.00031,0z"
fill="#D8DEE9"
/>
</g>
</g>
</g>
</g>
<style jsx>{`
.spotify-icon {
fill: #d8dee9;
}
`}</style>
</SvgIcon>
);
}
}
export default class Spotify extends Component {
static displayName() {
return "spotify";
}
constructor(props) {
super(props);
this.state = { version: "Not running" };
this.setStatus = this.setStatus.bind(this);
this.handleSpotifyActivation = this.handleSpotifyActivation.bind(this);
}
setStatus() {
spotify.isRunning((err, isRunning) => {
if (!isRunning) {
this.setState({ state: "Not running" });
return;
}
if (err) {
console.log(`Caught exception at setStatus(e): ${err}`);
}
spotify.getState((err, st) => {
if (err) {
console.log(`Caught exception at spotify.getState(e): ${err}`);
}
spotify.getTrack((err, track) => {
if (err) {
console.log(`Caught exception at spotify.getTrack(e): ${err}`);
}
this.setState({
state: `${st.state === "playing" ? "▶" : "❚❚"} ${track.artist} - ${
track.name
}`
});
});
});
});
}
/*
TODO: Make this work on Linux and Win 32/64
*/
handleSpotifyActivation(e) {
e.preventDefault();
console.log("HANDLE CLICKED FOR SPOTIFY");
spotify.isRunning((err, isRunning) => {
if (!isRunning) {
spotify.openSpotify();
}
if (err) {
console.log(`Caught exception at handleSpotifyActivation(e): ${err}`);
}
});
}
componentDidMount() {
this.setStatus();
this.interval = setInterval(() => this.setStatus(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div
className="wrapper"
onClick={this.handleSpotifyActivation.bind(this)}
>
<PluginIcon /> {this.state.state}
<style jsx>{`
.wrapper {
display: flex;
align-items: center;
color: #eceff4;
}
`}</style>
</div>
);
}
}
|
const socket = io();
// document.querySelector("#nmUser").value = prompt("Ingrese su nombre");
Swal.fire("Any fool can use a computer");
(async () => {
const { value: url } = await Swal.fire({
width: 500,
padding: "3em",
color: "#716add",
background: "#fff url(/images/trees.png)",
backdrop: `
rgba(0,0,123,0.4)
url("https://media1.giphy.com/media/IeKlzSDKvYNbtlYPvb/giphy.gif?cid=ecf05e47sl3w2m8jnv6urnovjleeabrg9d1lj2uwaxchp2pl&rid=giphy.gif&ct=s")
top
no-repeat
`,
input: "text",
inputPlaceholder: "Enter your userName",
});
if (url) {
Swal.fire(`userName: ${url}`);
}
document.querySelector("#nmUser").value = url;
})();
socket.on("message_back", (data) => {
console.log(data);
render(data);
socket.emit("message_client", "Hey!!.. i am theClient");
});
// creo una funcion render
const render = (data) => {
let html = data
.map((x) => {
return `
<p> <b>${x.name}:</b> ${x.userMsn} </p>
`;
})
.join("");
document.querySelector("#box").innerHTML = html;
};
// funcion para capturar info del formulario
const addInfo = () => {
let dataObj = {
name: document.querySelector("#nmUser").value,
userMsn: document.querySelector("#msnUser").value,
};
console.log(dataObj);
// envio los datos al back
socket.emit("dataMns", dataObj);
document.querySelector("#msnUser").value = "";
return false;
};
|
const Promise = require('bluebird');
const common = require('../common');
const fs = require('fs-extra');
/**
* @NOTE: Sharp cannot operate on the same image path, that's why we have to use in & out paths.
*
* We currently can't enable compression or having more config options, because of
* https://github.com/lovell/sharp/issues/1360.
*/
const unsafeProcess = (options = {}) => {
return fs.readFile(options.in)
.then((data) => {
return unsafeResizeImage(data, {
width: options.width
});
})
.then((data) => {
return fs.writeFile(options.out, data);
});
};
const unsafeResizeImage = (originalBuffer, {width, height} = {}) => {
const sharp = require('sharp');
return sharp(originalBuffer)
.resize(width, height, {
// CASE: dont make the image bigger than it was
withoutEnlargement: true
})
// CASE: Automatically remove metadata and rotate based on the orientation.
.rotate()
.toBuffer()
.then((resizedBuffer) => {
return resizedBuffer.length < originalBuffer.length ? resizedBuffer : originalBuffer;
});
};
// NOTE: .gif optimization is currently not supported by sharp but will be soon
// as there has been support added in underlying libvips library https://github.com/lovell/sharp/issues/1372
// As for .svg files, sharp only supports conversion to png, and this does not
// play well with animated svg files
const canTransformFileExtension = ext => !['.gif', '.svg', '.svgz'].includes(ext);
const makeSafe = fn => (...args) => {
try {
require('sharp');
} catch (err) {
return Promise.reject(new common.errors.InternalServerError({
message: 'Sharp wasn\'t installed',
code: 'SHARP_INSTALLATION',
err: err
}));
}
return fn(...args).catch((err) => {
throw new common.errors.InternalServerError({
message: 'Unable to manipulate image.',
err: err,
code: 'IMAGE_PROCESSING'
});
});
};
module.exports.canTransformFileExtension = canTransformFileExtension;
module.exports.process = makeSafe(unsafeProcess);
module.exports.resizeImage = makeSafe(unsafeResizeImage);
|
var searchData=
[
['same_5for_5fleft_5fbits',['same_or_left_bits',['../malloc_8c.html#ace4a96b1b78fcc4d93372fb9336f899f',1,'malloc.c']]],
['sample',['Sample',['../classSample.html',1,'']]],
['sample_2ecpp',['Sample.cpp',['../Sample_8cpp.html',1,'']]],
['sample_2eh',['Sample.h',['../Sample_8h.html',1,'']]],
['save',['SAVE',['../namespacebreaker.html#a7f9c13d28244e077264db2723abdc18d',1,'breaker']]],
['sbinptr',['sbinptr',['../malloc_8c.html#ac42f888c90017483ad23708b9a346798',1,'malloc.c']]],
['scale_5fcores',['SCALE_CORES',['../alloc__perf_8c.html#ab1d13afae9b3766563a49a5c4d1ab9d2',1,'alloc_perf.c']]],
['sda',['SDA',['../vine__talk__types_8h.html#ae1360554e303883862a00382e62a6ecdae21c602fb61dc58e4fa361382cb31403',1,'vine_talk_types.h']]],
['seg',['seg',['../structmalloc__state.html#ac3d059568e5fdb458026c9116d593ba7',1,'malloc_state']]],
['segment_5fholds',['segment_holds',['../malloc_8c.html#a3616a6ae475e54f73816dfa69d1483e8',1,'malloc.c']]],
['self',['self',['../structvine__pipe.html#add843125b63b1afec9686fbaa3deb708',1,'vine_pipe']]],
['sem',['sem',['../structasync__semaphore__s.html#a57e5f989454185402d689672f370a749',1,'async_semaphore_s']]],
['semaphore',['semaphore',['../structasync__condition__s.html#a732830f0357a2ac025e7b5e04b2886a1',1,'async_condition_s']]],
['semaphore_5finc_5flazy',['semaphore_inc_lazy',['../tests_2async_8c.html#a916efa4ebe0c2e9c2be5a17bc74bff54',1,'async.c']]],
['server',['Server',['../classServer.html',1,'Server'],['../classServer.html#a5d93c15cf4ac2c794f40bf5ec2684eb4',1,'Server::Server()']]],
['set_5fflag4',['set_flag4',['../malloc_8c.html#ab59038f70c8449bc2efdec7d99e1a372',1,'malloc.c']]],
['set_5ffoot',['set_foot',['../malloc_8c.html#a8429bbf864f878eca1011ec97969535b',1,'malloc.c']]],
['set_5ffree_5fwith_5fpinuse',['set_free_with_pinuse',['../malloc_8c.html#a4533a463f685015d5b56192fc5f42ba7',1,'malloc.c']]],
['set_5finuse',['set_inuse',['../malloc_8c.html#a1e4f613ffb89c72f5686586939b13cf6',1,'malloc.c']]],
['set_5finuse_5fand_5fpinuse',['set_inuse_and_pinuse',['../malloc_8c.html#a6b0498b45088d3b87e6b2daed2f6fa92',1,'malloc.c']]],
['set_5flock',['set_lock',['../malloc_8c.html#aae06e664473337b87ba3d95609fef288',1,'malloc.c']]],
['set_5fsize_5fand_5fpinuse_5fof_5ffree_5fchunk',['set_size_and_pinuse_of_free_chunk',['../malloc_8c.html#a18bad8f70449009a982f57c6e8107d29',1,'malloc.c']]],
['set_5fsize_5fand_5fpinuse_5fof_5finuse_5fchunk',['set_size_and_pinuse_of_inuse_chunk',['../malloc_8c.html#a076ff214648e7d19ddaa7a4d963aae4a',1,'malloc.c']]],
['setargs',['setArgs',['../classVinetalk_1_1VineTask.html#a637605b9159476a6bf2d87514bdecd07',1,'Vinetalk::VineTask']]],
['setid',['setID',['../classSample.html#a1efe89e68f31adeca835d01989c70f97',1,'Sample']]],
['setpointer',['setPointer',['../classVinetalk_1_1VineObject.html#aac6de463f05b1cafbfbf52d36b0617d8',1,'Vinetalk::VineObject']]],
['settask',['setTask',['../classVinetalk_1_1VineTask.html#a214e80b95c1c742d92f299da11526ecd',1,'Vinetalk::VineTask']]],
['setup',['setup',['../alloc__perf_8c.html#a4fc01d736fe50cf5b977f755b675f11d',1,'setup(): alloc_perf.c'],['../tests_2async_8c.html#a4fc01d736fe50cf5b977f755b675f11d',1,'setup(): async.c'],['../tests_2config_8c.html#a4fc01d736fe50cf5b977f755b675f11d',1,'setup(): config.c'],['../tests_2list_8c.html#a4fc01d736fe50cf5b977f755b675f11d',1,'setup(): list.c'],['../mmap_8c.html#a4fc01d736fe50cf5b977f755b675f11d',1,'setup(): mmap.c'],['../tests_2queue_8c.html#a4fc01d736fe50cf5b977f755b675f11d',1,'setup(): queue.c'],['../tracer_8c.html#a4fc01d736fe50cf5b977f755b675f11d',1,'setup(): tracer.c'],['../tests_2vine__object_8c.html#a4fc01d736fe50cf5b977f755b675f11d',1,'setup(): vine_object.c'],['../tests_2vine__talk_8c.html#a4fc01d736fe50cf5b977f755b675f11d',1,'setup(): vine_talk.c']]],
['sflags',['sflags',['../structmalloc__segment.html#a9b646ca2cdec5a027aaab2177712760f',1,'malloc_segment']]],
['sha',['sha',['../structvine__pipe.html#a53a3228d743ac20ce1ea2bf3c25a38c1',1,'vine_pipe']]],
['shm_5ffile',['shm_file',['../src_2arch_2shm_2vine__talk_8c.html#a1efb21672d3d03723a3438c024c7e9b8',1,'vine_talk.c']]],
['shm_5fsize',['shm_size',['../structvine__pipe.html#a28948fedd958f16682e8465a585f5df5',1,'vine_pipe']]],
['should_5ftrim',['should_trim',['../malloc_8c.html#a8fcca0fe7fd7176c642cb7eaca01e3c8',1,'malloc.c']]],
['sig_5fremap',['sig_remap',['../btgen_8c.html#a618086f8b899cb25d68fbda5c425f082',1,'btgen.c']]],
['signum',['signum',['../structSigRemap.html#af063222f46f5e774717f2f0a077302af',1,'SigRemap']]],
['sigremap',['SigRemap',['../structSigRemap.html',1,'']]],
['six_5fsize_5ft_5fsizes',['SIX_SIZE_T_SIZES',['../malloc_8c.html#ae711f3f963dc01f816b155795e4a7729',1,'malloc.c']]],
['size',['size',['../structmalloc__segment.html#a854352f53b148adc24983a58a1866d66',1,'malloc_segment::size()'],['../structvine__data__s.html#a854352f53b148adc24983a58a1866d66',1,'vine_data_s::size()'],['../structallocation.html#a854352f53b148adc24983a58a1866d66',1,'allocation::size()'],['../structMetrics.html#a854352f53b148adc24983a58a1866d66',1,'Metrics::size()']]],
['size_5ft_5fbitsize',['SIZE_T_BITSIZE',['../malloc_8c.html#a9d769150c841cbb7512476c56aaf5617',1,'malloc.c']]],
['size_5ft_5ffour',['SIZE_T_FOUR',['../malloc_8c.html#a9233a87a400d8aaae1b22d1e3cdc42d8',1,'malloc.c']]],
['size_5ft_5fone',['SIZE_T_ONE',['../malloc_8c.html#a1a115588725fa912f1bcaca9f08fb658',1,'malloc.c']]],
['size_5ft_5fsize',['SIZE_T_SIZE',['../malloc_8c.html#a2e3db94c3bfc87e3c7bcbee4973bab02',1,'malloc.c']]],
['size_5ft_5ftwo',['SIZE_T_TWO',['../malloc_8c.html#a7e1ed65ca3ce9fcc21e329a7cea204d1',1,'malloc.c']]],
['size_5ft_5fzero',['SIZE_T_ZERO',['../malloc_8c.html#acd3fa67eabd0de0d56e206fa3a416de9',1,'malloc.c']]],
['sizeof',['SIZEOF',['../producer_8c.html#a968f2840032e16ccde0915dc8d7867fc',1,'producer.c']]],
['small_5findex',['small_index',['../malloc_8c.html#a1f3d4249e522c896509b7999860090ea',1,'malloc.c']]],
['small_5findex2size',['small_index2size',['../malloc_8c.html#a377939ca061c1b170053c2927af26cdc',1,'malloc.c']]],
['smallbin_5fat',['smallbin_at',['../malloc_8c.html#a862c7dc1f319911e1f06b9d99485cc54',1,'malloc.c']]],
['smallbin_5fshift',['SMALLBIN_SHIFT',['../malloc_8c.html#a35c7b74e5fe8c45a869115cc6e154fe9',1,'malloc.c']]],
['smallbin_5fwidth',['SMALLBIN_WIDTH',['../malloc_8c.html#a033008a0cb72328dd6ced48e7f639874',1,'malloc.c']]],
['smallbins',['smallbins',['../structmalloc__state.html#ae965c680228aa17ecacec0a42161a896',1,'malloc_state']]],
['smallmap',['smallmap',['../structmalloc__state.html#ab56163a714e0775cc6fad5ad6fe1cafd',1,'malloc_state']]],
['smallmap_5fis_5fmarked',['smallmap_is_marked',['../malloc_8c.html#a545357ca2a355288874c27ea94eca166',1,'malloc.c']]],
['smblks',['smblks',['../structmallinfo.html#a3e7598cedb4cf3db48ac2dbdaedba8c3',1,'mallinfo']]],
['spawn_5fproducers',['spawn_producers',['../producer_8c.html#a1e34c47687440ed9df54aa8655857821',1,'producer.c']]],
['spawn_5fthreads',['spawn_threads',['../queue__test_8c.html#a5b70807ea224cb7a575fd41150bcf2ab',1,'queue_test.c']]],
['spinlock_2eh',['spinlock.h',['../spinlock_8h.html',1,'']]],
['start',['start',['../structutils__timer__s.html#a87659dd781b771019d5936762c0e3604',1,'utils_timer_s::start()'],['../structallocation.html#a52a8a99bfbb1c17e94e3a9f816d8f5ee',1,'allocation::start()'],['../classCollector.html#a60de64d75454385b23995437f1d72669',1,'Collector::start()']]],
['start_5ftest',['START_TEST',['../alloc__perf_8c.html#ac80ce701f99f0669095cc6a10ecd7fd9',1,'START_TEST(alloc_perf): alloc_perf.c'],['../tests_2async_8c.html#a15502b7bae27d850e57211b5b1dd452d',1,'START_TEST(serial_completion): async.c'],['../tests_2async_8c.html#a7b0e57d15b24924311e4bd4da1d19619',1,'START_TEST(serial_semaphore): async.c'],['../tests_2async_8c.html#a8d175e06a5c28a439fc0b600048d3566',1,'START_TEST(serial_condition): async.c'],['../tests_2config_8c.html#a41c6257f2b6c038c0c2dd00f088eef8f',1,'START_TEST(test_config_get_str): config.c'],['../tests_2config_8c.html#aa59c42da706218849d422077083e518d',1,'START_TEST(test_config_get_str_fail): config.c'],['../tests_2config_8c.html#ab708c0b679bb756ef976d8a518b8bd41',1,'START_TEST(test_config_get_bool): config.c'],['../tests_2config_8c.html#a38cceb0812b9bd40f21acad8a0e3960f',1,'START_TEST(test_config_get_int): config.c'],['../tests_2config_8c.html#a1cdb65b3dd8e00837698fa3849628a04',1,'START_TEST(test_config_no_file): config.c'],['../tests_2config_8c.html#a34464cd3d91c5ce4c1889573c813685c',1,'START_TEST(test_config_path_alloc): config.c'],['../tests_2list_8c.html#adcbd4062ff029b1240b6d397bbc6aad3',1,'START_TEST(test_list_init_destr): list.c'],['../tests_2list_8c.html#a35ae9358f0aabd707d17ee5a484a2ea1',1,'START_TEST(test_list_add_del_to_array): list.c'],['../mmap_8c.html#affa3daddaa7ab352dc6c338691f01ae4',1,'START_TEST(forced): mmap.c'],['../mmap_8c.html#a30a650398d165a70330d2b2bfc54bcee',1,'START_TEST(lax): mmap.c'],['../tests_2queue_8c.html#a6f88ad5d2d7770496528d0e177e06ff6',1,'START_TEST(test_queue_init_destr): queue.c'],['../tests_2queue_8c.html#a45b4023eec21a015c197400644d1382b',1,'START_TEST(test_queue_push_pop): queue.c'],['../tests_2queue_8c.html#a4c5b0cac71f43b589a6d420f26ab0ca7',1,'START_TEST(test_queue_circulation): queue.c'],['../tests_2queue_8c.html#aa934801b0a4763e8b5b0dc44f3ab0d64',1,'START_TEST(test_queue_indices_circulation): queue.c'],['../tests_2queue_8c.html#ac48ccce5a0e0b6cce9293264d3c0f3f7',1,'START_TEST(test_queue_mcsp): queue.c'],['../tracer_8c.html#ab09e4259edb8518dc2a2b79654bf12bd',1,'START_TEST(perf_test): tracer.c'],['../tests_2vine__object_8c.html#a867183d2a1be1ff047021a57e3eeec76',1,'START_TEST(test_vine_object_init_destr): vine_object.c'],['../tests_2vine__object_8c.html#a5e745b27c33910ebf9cf8e4d5455a602',1,'START_TEST(test_vine_object_leak): vine_object.c'],['../tests_2vine__talk_8c.html#a4a71e2891aaad53756968224aaa676f1',1,'START_TEST(test_in_out): vine_talk.c'],['../tests_2vine__talk_8c.html#aaf5fd76f02c13775484993df01c40c5c',1,'START_TEST(test_revision): vine_talk.c'],['../tests_2vine__talk_8c.html#a0f26f3c8168da968d917f7921ab80ab1',1,'START_TEST(test_single_accel): vine_talk.c'],['../tests_2vine__talk_8c.html#a054fd8afe2e7717287b4d064a436f78f',1,'START_TEST(test_single_proc): vine_talk.c'],['../tests_2vine__talk_8c.html#a204d4743034b4f18d6ab357301e141e3',1,'START_TEST(test_alloc_data): vine_talk.c'],['../tests_2vine__talk_8c.html#ac116c6cace74b31dcb825895b714db34',1,'START_TEST(test_task_issue): vine_talk.c'],['../tests_2vine__talk_8c.html#abfd653e520265ef7829aac629e1b2cbe',1,'START_TEST(test_type_strings): vine_talk.c']]],
['stat',['stat',['../namespacebreaker.html#ac9be3ea69ffe4fb1b29dee4ccfaf0ac9',1,'breaker']]],
['state',['State',['../enumVinetalk_1_1VineTask_1_1State.html',1,'Vinetalk::VineTask']]],
['state',['state',['../structvine__accel__s.html#a67e5c237697cb9afaf0b08219b3e412a',1,'vine_accel_s::state()'],['../structvine__task__msg.html#a375f7db50ae12cdc84edc8755a77c09a',1,'vine_task_msg::state()'],['../enumVinetalk_1_1VineTask_1_1State.html#a90be2e66e17e313a0461f8a81032858c',1,'Vinetalk.VineTask.State.State()']]],
['stats',['stats',['../structvine__accel__s.html#a3a8e91486b2db737b07c104b4a00535c',1,'vine_accel_s::stats()'],['../structvine__task__msg.html#a7612661c42b7ba9bc65dff8a1b35b5bc',1,'vine_task_msg::stats()'],['../namespacebreaker.html#ad5d1c05d28c91109422580ea1bf368f4',1,'breaker.stats()']]],
['status',['status',['../classVinetalk_1_1VineTask.html#aec9af8f6bf7cec01712ed0896b45a9a3',1,'Vinetalk.VineTask.status()'],['../classVinetalk_1_1VineTask.html#ab6de1a11fa47cd9ca54d61a4ecee8547',1,'Vinetalk.VineTask.status(boolean sync)']]],
['stop',['stop',['../structutils__timer__s.html#a0e0b9ddde38b77f2b739eeffac21104e',1,'utils_timer_s::stop()'],['../classCollector.html#a8c528baf37154d347366083f0f816846',1,'Collector::stop()']]],
['str',['str',['../structvine__accel__type__map.html#af25d6dc49269fa2003ac7c7fa6f13915',1,'vine_accel_type_map']]],
['struct_5fmallinfo_5fdeclared',['STRUCT_MALLINFO_DECLARED',['../malloc_8c.html#a73031e8be1f35c837c74bee1d205a929',1,'STRUCT_MALLINFO_DECLARED(): malloc.c'],['../malloc_8h.html#a73031e8be1f35c837c74bee1d205a929',1,'STRUCT_MALLINFO_DECLARED(): malloc.h']]],
['suite_5finit',['suite_init',['../alloc__perf_8c.html#a7d6caf24d8599ab2d6fefcdb2649756e',1,'suite_init(): alloc_perf.c'],['../tests_2async_8c.html#a7d6caf24d8599ab2d6fefcdb2649756e',1,'suite_init(): async.c'],['../tests_2config_8c.html#a7d6caf24d8599ab2d6fefcdb2649756e',1,'suite_init(): config.c'],['../tests_2list_8c.html#a7d6caf24d8599ab2d6fefcdb2649756e',1,'suite_init(): list.c'],['../mmap_8c.html#a7d6caf24d8599ab2d6fefcdb2649756e',1,'suite_init(): mmap.c'],['../tests_2queue_8c.html#a7d6caf24d8599ab2d6fefcdb2649756e',1,'suite_init(): queue.c'],['../tracer_8c.html#a7d6caf24d8599ab2d6fefcdb2649756e',1,'suite_init(): tracer.c'],['../tests_2vine__object_8c.html#a7d6caf24d8599ab2d6fefcdb2649756e',1,'suite_init(): vine_object.c'],['../tests_2vine__talk_8c.html#a7d6caf24d8599ab2d6fefcdb2649756e',1,'suite_init(): vine_talk.c']]],
['synchro',['synchro',['../alloc__perf_8c.html#a8225f160aecfab1365666fd07d1af31c',1,'alloc_perf.c']]],
['sys_5falloc_5fpadding',['SYS_ALLOC_PADDING',['../malloc_8c.html#ac40b2081de834d5d7e140d79592cd4df',1,'malloc.c']]],
['system_2ec',['system.c',['../system_8c.html',1,'']]],
['system_2eh',['system.h',['../system_8h.html',1,'']]],
['system_5fcompare_5fptrs',['system_compare_ptrs',['../system_8c.html#a54afb36e6e15022689d1ae7ed9cec1c0',1,'system_compare_ptrs(const void *a, const void *b): system.c'],['../system_8h.html#a54afb36e6e15022689d1ae7ed9cec1c0',1,'system_compare_ptrs(const void *a, const void *b): system.c']]],
['system_5ffile_5fsize',['system_file_size',['../system_8c.html#a86c3bfbf6daaf8172e131aa23dc7393c',1,'system_file_size(const char *file): system.c'],['../system_8h.html#a86c3bfbf6daaf8172e131aa23dc7393c',1,'system_file_size(const char *file): system.c']]],
['system_5fhome_5fpath',['system_home_path',['../system_8c.html#a2070274450e2558c96f80878bc8caa1d',1,'system_home_path(): system.c'],['../system_8h.html#a2070274450e2558c96f80878bc8caa1d',1,'system_home_path(): system.c']]],
['system_5ftotal_5fmemory',['system_total_memory',['../system_8c.html#a54bd28e423e19877e5abcb1fe3d12c03',1,'system_total_memory(): system.c'],['../system_8h.html#a54bd28e423e19877e5abcb1fe3d12c03',1,'system_total_memory(): system.c']]]
];
|
import c from '../utils/constants';
// import sc from './storyConstants';
import intro from './scenes/intro';
import mainMenu from './scenes/mainMenu';
import scene001 from './scenes/scene001';
import scene002 from './scenes/scene002';
import plates from '../plates';
import timing from '../utils/timing';
import hud from '../hud';
import entities from '../entities/entities';
import soundEffects from '../audio/soundEffects';
import music from '../audio/music';
import {
shields,
status,
makeName,
storePlayerProgress,
readPlayerProgress,
hasThePlayerMadeProgress,
alertsAndWarnings,
dialog,
} from '../utils/helpers';
import formations from '../behavior/formations';
import shots from '../shots';
import gameMenus from '../gameMenus';
import initialGameState from '../initialGameState';
import controlSchemes from '../controlSchemes';
const story = {
handlers: {
dispatch: null,
state: null,
stage: null,
playVolume: null,
playVolumeBoundaries: null,
frameZero: null,
hudShouldBeShowing: null,
activeKeyboardLayout: null,
}, // gets its values in App.js
sceneList: [
{
id: 'intro',
sceneObject: intro,
hasTitlePlate: false,
hasEntities: false,
hasGameplay: false,
showStatusBar: false,
},
{
id: 'mainMenu',
sceneObject: mainMenu,
hasTitlePlate: false,
hasEntities: false,
hasGameplay: false,
showStatusBar: false,
},
{
id: '001',
sceneObject: scene001,
hasTitlePlate: true,
hasEntities: true,
hasGameplay: true,
showStatusBar: true,
},
{
id: '002',
sceneObject: scene002,
hasTitlePlate: true,
hasEntities: true,
hasGameplay: true,
showStatusBar: true,
},
],
currentScene: null,
currentSceneBeat: null,
missionFailureWasTriggered: false,
noOfTimesHitEscMessageWasAppended: 0,
escAddendum:
' < Hit [ESC] to see your current objectives',
currentObjectives: {
show: [],
advanceWhen: [],
},
currentStoryEntities: {},
noProgressYetMessage:
"According to your browser's storage, you haven't made any progress in this game yet, please choose 'New game' instead!",
assertClassification(entityId) {
const storyEntity = story.currentStoryEntities[entityId];
if (storyEntity === undefined) {
return '';
} else {
const fullTypeName = storyEntity.type;
if (
fullTypeName.includes('fighter') ||
fullTypeName.includes('fenrir') ||
fullTypeName.includes('valkyrie')
) {
return 'Fighter ';
} else if (fullTypeName.includes('shuttle')) {
return 'Shuttle ';
} else if (fullTypeName.includes('freighter')) {
return 'Freighter ';
} else if (fullTypeName.includes('container')) {
return 'Container ';
}
}
},
advance(playScene = null, playSceneBeat = 0, hurryUp = false) {
// call with playScene = null to auto-advance
// to the next scene
if (c.debug.sequentialEvents)
console.log('advance()', playScene, playSceneBeat);
const currentState = story.handlers.state();
let cleanUpNeeded = false;
const playerId =
c.playerIdPartial + currentState.game.playerShips.currentIdSuffix;
const playerShipType = currentState.game.playerShips.current;
if (story.currentScene === null) {
story.currentScene = story.sceneList[0].id;
} else {
if (playSceneBeat === 0) cleanUpNeeded = true;
if (playScene !== null) {
story.currentScene = playScene;
} else {
let index = story.sceneList.findIndex(
(el) => el.id === story.currentScene
);
index++;
if (story.sceneList[index] !== undefined) {
// more scenes exist
story.currentScene = story.sceneList[index].id;
} else {
// no more scenes, end of the game
if (c.debug.sequentialEvents)
console.log('THIS IS THE END OF THE GAME');
plates.fullMatte();
plates.loadPlate('the_end');
plates.fadeInPlate(25);
timing.toggleEntityMovement(false, 'story.js@advance() 1', 1000);
timing.setTimeout(
() => {
soundEffects.muteUnmuteAllLoops('story.js@advance() 2', true);
},
timing.modes.play,
1000
);
plates.fadeOutPlate(25, 7000);
timing.setTimeout(
() => {
story.advance('mainMenu', 0);
},
timing.modes.play,
8200
);
return;
}
}
}
if (c.debug.sequentialEvents)
console.log('story.currentScene:', story.currentScene);
const currentSceneListObject = story.sceneList.find(
(el) => el.id === story.currentScene
);
const currentSceneObject = currentSceneListObject.sceneObject;
if (playSceneBeat === 0) {
if (currentSceneListObject.hasEntities) {
story.currentStoryEntities = currentSceneObject.entities;
}
story.handlers.playVolume.current = currentSceneObject.playVolume;
story.handlers.playVolume.recalculateSoftBoundaries();
story.handlers.playVolumeBoundaries.reDraw(currentSceneObject.playVolume);
story.missionFailureWasTriggered = false;
if (currentSceneListObject.id !== 'mainMenu') {
const localStoragePlayerProgress = readPlayerProgress();
if (currentSceneListObject.id === 'intro') {
if (localStoragePlayerProgress === null) {
// this player is a first time visitor
if (c.debug.localStorage)
console.log(
'no localStorage string found, populating with the defaults from initialGameState.js'
);
storePlayerProgress(
story.handlers.state,
currentSceneListObject.id
);
} else {
if (c.debug.localStorage)
console.log(
'updating player progress from localStorage:',
localStoragePlayerProgress
);
story.handlers.dispatch({
type: c.actions.UPDATE_PLAYER_PROGRESS_BASED_ON_LOCAL_STORAGE,
localStoragePlayerProgress: localStoragePlayerProgress,
});
}
} else {
const playersBestSceneId = localStoragePlayerProgress.bestSceneId;
const playersBestSceneIndex = story.sceneList.findIndex(
(sc) => sc.id === playersBestSceneId
);
const currentSceneIndex = story.sceneList.findIndex(
(sc2) => sc2.id === currentSceneListObject.id
);
let writeBestSceneId = playersBestSceneId;
if (currentSceneIndex > playersBestSceneIndex)
writeBestSceneId = currentSceneListObject.id;
storePlayerProgress(story.handlers.state, writeBestSceneId);
}
}
}
let currentStateScene = currentState.game.currentScene;
if (currentStateScene !== story.currentScene) {
story.handlers.dispatch({
type: c.actions.SET_CURRENT_SCENE,
newCurrentScene: story.currentScene,
});
}
story.currentSceneBeat = playSceneBeat;
if (c.debug.sequentialEvents)
console.log('story.currentSceneBeat:', story.currentSceneBeat);
const currentSceneBeatObj =
currentSceneObject.storyBeats[story.currentSceneBeat];
if (c.debug.sequentialEvents) console.log(currentSceneObject);
if (cleanUpNeeded) {
story.cleanUp();
}
if (currentSceneListObject.hasTitlePlate && playSceneBeat === 0) {
currentSceneObject.handlers.checkBeatCompletion =
story.checkBeatCompletion;
status.add(
'aqua',
`--- ${currentSceneObject.titlePlate.mainText} ---`,
timing.times.play
);
plates.fullMatte();
plates.loadPlate(
'mission_title',
-1,
currentSceneObject.titlePlate.mainText,
currentSceneObject.titlePlate.wittyText
);
timing.toggleEntityMovement(false, 'story.js@advance() 3');
soundEffects.muteUnmuteAllLoops('story.js@advance() 4', true);
plates.fadeInPlate(25);
plates.fadeOutMatte(50, 4000);
timing.toggleEntityMovement(true, 'story.js@advance() 5', 4000);
timing.setTimeout(
() => {
soundEffects.muteUnmuteAllLoops('story.js@advance() 6', false);
},
timing.modes.play,
4000
);
plates.fadeOutPlate(25, 6000);
}
if (!currentSceneListObject.hasEntities) {
timing.toggleEntityMovement(false, 'story.js@advance() 7');
}
if (currentSceneListObject.showStatusBar) {
document.getElementById('game__status').style.display = 'flex';
} else {
document.getElementById('game__status').style.display = 'none';
}
//register new objectives
if (currentSceneListObject.hasGameplay) {
const objectiveUpdates = currentSceneBeatObj.registerObjectives();
story.updateCurrentObjectives(objectiveUpdates);
}
// set the keyboard layout
story.handlers.activeKeyboardLayout.current =
currentSceneBeatObj.keyboardLayout;
story.handlers.activeKeyboardLayout.currentStoryBeatLayout =
currentSceneBeatObj.keyboardLayout;
// scene object execution
currentSceneBeatObj.execute({ playerId, playerShipType, hurryUp });
if (currentSceneBeatObj.cameraMode === c.cameraModes.gameplay) {
story.handlers.hudShouldBeShowing.actual = true;
timing.setTrigger(
'story-hud-trigger1',
() => {
shots.registerEntityCannons(playerId);
},
timing.modes.play,
1500
);
timing.setTrigger(
'story-hud-trigger2',
() => {
hud.reInitPixiHUD(playerId);
// hud.toggle('story.js@advance() 4', true);
},
timing.modes.play,
6000
);
} else {
story.handlers.hudShouldBeShowing.actual = false;
// hud.toggle('story.js@advance() 4', false);
}
},
restartMission() {
gameMenus.clearButtons();
alertsAndWarnings.clear();
alertsAndWarnings.hide();
dialog.hide();
plates.clearAll();
timing.clearAllScheduledEvents();
status.add('aqua', 'Mission restarted...', timing.times.play);
story.handlers.dispatch({ type: c.actions.RESTART_MISSION });
story.advance(story.currentScene, 0);
story.handlers.frameZero.actual = true;
},
mainMenu(askForConfirmation = true, hurryUp = false) {
function mainMenuProper() {
alertsAndWarnings.clear();
alertsAndWarnings.hide();
dialog.hide();
plates.clearAll();
timing.clearAllScheduledEvents();
if (timing.isPaused()) window.pixiapp.togglePause('dontFadeMatte');
gameMenus.clearButtons();
story.advance('mainMenu', 0, hurryUp);
}
if (askForConfirmation) {
if (
confirm(
'Returning to the main menu will reset your progress on the current mission. Continue anyway?'
)
) {
mainMenuProper();
}
} else {
mainMenuProper();
}
},
replayScene() {
const localStoragePlayerProgress = readPlayerProgress();
let goAhead = false;
if (localStoragePlayerProgress === null) {
goAhead = true;
} else {
if (!hasThePlayerMadeProgress(localStoragePlayerProgress)) {
alert(story.noProgressYetMessage);
} else {
goAhead = true;
}
}
if (goAhead) {
story.handlers.activeKeyboardLayout.current =
controlSchemes.replaySceneMenu.id;
story.removeMainMenuTopPortion();
gameMenus.clearButtons();
gameMenus.showReplaySceneButtonSet(story.sceneList);
}
},
replaySceneActual(sceneId, sceneIndex) {
const localStoragePlayerProgress = readPlayerProgress();
if (c.debug.sequentialEvents)
console.log('story.js@replaySceneActual', sceneId, sceneIndex);
let goAhead = false;
if (localStoragePlayerProgress === null) {
goAhead = true;
} else {
const bestSceneId = localStoragePlayerProgress.bestSceneId;
const bestSceneIndex = story.sceneList.findIndex(
(sc) => sc.id === bestSceneId
);
if (bestSceneIndex < sceneIndex) {
alert("I'm sorry, you haven't unlocked that scene yet.");
} else {
goAhead = true;
}
}
if (c.debug.sequentialEvents) console.log({ goAhead });
if (goAhead) {
music.stopPlaying();
gameMenus.clearButtons();
story.advance(sceneId, 0);
}
},
newGame() {
const localStoragePlayerProgress = readPlayerProgress();
function newGameProper() {
music.stopPlaying();
gameMenus.clearButtons();
story.removeMainMenuTopPortion();
story.advance();
}
if (!hasThePlayerMadeProgress(localStoragePlayerProgress)) {
newGameProper();
} else {
if (
confirm(
'Starting a new game will revert your previous progress. Continue anyway?'
)
) {
story.handlers.dispatch({
type: c.actions.REVERT_PLAYER_PROGRESS_TO_DEFAULTS,
defaultPlayerProgress: initialGameState.game.playerShips,
callbackFn: newGameProper,
});
}
}
},
continueGame() {
const localStoragePlayerProgress = readPlayerProgress();
if (!hasThePlayerMadeProgress(localStoragePlayerProgress)) {
alert(story.noProgressYetMessage);
} else {
music.stopPlaying();
gameMenus.clearButtons();
story.removeMainMenuTopPortion();
story.advance(localStoragePlayerProgress.bestSceneId, 0);
}
},
removeMainMenuTopPortion() {
document
.getElementById('game__main_menu')
.classList.remove('game__main_menu--shown', 'game__main_menu--quickshow');
document
.getElementById('header__title')
.classList.remove('header__title--hidden');
},
init() {
gameMenus.buttonFunctions.restartMission = story.restartMission;
gameMenus.buttonFunctions.mainMenu = story.mainMenu;
gameMenus.buttonFunctions.newGame = story.newGame;
gameMenus.buttonFunctions.continueGame = story.continueGame;
gameMenus.buttonFunctions.replayScene = story.replayScene;
gameMenus.buttonFunctions.replaySceneActual = story.replaySceneActual;
},
updateCurrentObjectives(updates) {
if (c.debug.objectives) console.log('updateCurrentObjectives()', updates);
story.currentObjectives.show = [
...story.currentObjectives.show,
...updates.show,
];
story.currentObjectives.show.forEach((sitem) => {
if (sitem.currentPercentage === undefined) {
sitem.currentPercentage = 0;
sitem.failed = false;
}
});
story.currentObjectives.advanceWhen = updates.advanceWhen;
story.currentObjectives.advanceWhen.forEach((awitem) => {
if (awitem.currentPercentage === undefined) {
awitem.currentPercentage = 0;
awitem.failed = false;
}
});
if (updates.show.length > 0) {
let escAddendum = '';
if (story.noOfTimesHitEscMessageWasAppended < 4) {
escAddendum = story.escAddendum;
story.noOfTimesHitEscMessageWasAppended++;
}
status.add(
'yellow',
'Mission objectives updated.' + escAddendum,
timing.times.play
);
}
story.updateObjectiveDisplay();
},
checkAgainstCurrentObjectives(
entityId,
eventId,
wasPreviouslyInspected = false
) {
if (c.debug.objectives)
console.log(
'checkAgainstCurrentObjectives',
entityId,
eventId,
wasPreviouslyInspected
);
if (typeof eventId !== 'string') {
console.error(
'eventId must be a string, this was received instead:',
eventId
);
}
if (eventId === c.objectiveTypes.destroyed.id) {
story.currentStoryEntities[entityId].wasDespawned = true;
}
let entityGroup = null;
let entitiesInGroup = 0;
const currentStoryEntity = story.currentStoryEntities[entityId];
if (currentStoryEntity !== undefined) {
if (currentStoryEntity.groupId !== undefined) {
entityGroup = currentStoryEntity.groupId;
for (const storyEntityId in story.currentStoryEntities) {
if (story.currentStoryEntities[storyEntityId].groupId === entityGroup)
entitiesInGroup++;
}
}
}
let entityClassification = story.assertClassification(entityId);
let entityInvolvedIn = [];
// look through all objectives in both stores
// to see if the entity is involved
for (const objectiveStore in story.currentObjectives) {
story.currentObjectives[objectiveStore].forEach((obj) => {
if (obj.groupId === undefined) {
if (entityId === obj.entityId) {
entityInvolvedIn.push({
store: objectiveStore,
objectiveObj: obj,
});
}
} else {
if (entityGroup === null) return;
if (entityGroup === obj.groupId) {
entityInvolvedIn.push({
store: objectiveStore,
objectiveObj: obj,
});
}
}
});
}
// walk through the collected objectives and update them
// based on this event
let failState = false;
let meansProgress = false;
let updatedObjectiveMessages = [];
entityInvolvedIn.forEach((el) => {
const objectiveType = el.objectiveObj.type;
let hasUpdated = false;
if (
c.objectiveTypes[objectiveType].failsIfEventIs.includes(eventId) ||
(eventId === c.objectiveTypes.destroyed.id &&
!wasPreviouslyInspected &&
objectiveType === c.objectiveTypes.inspected.id)
) {
// example: the entity should have been disabled,
// but it was destroyed instead
if (
el.objectiveObj.groupId === undefined ||
el.objectiveObj.requiredPercentage === 100
) {
failState = true;
el.objectiveObj.failed = true;
hasUpdated = true;
} else {
// determine if the objective can still be completed
// after this change
let remainingPercentage = 0;
for (const cseid in story.currentStoryEntities) {
if (
story.currentStoryEntities[cseid].groupId === entityGroup &&
!story.currentStoryEntities[cseid].wasDespawned
) {
remainingPercentage += (1 / entitiesInGroup) * 100;
}
}
if (remainingPercentage < el.objectiveObj.requiredPercentage) {
failState = true;
el.objectiveObj.failed = true;
hasUpdated = true;
}
}
} else {
if (eventId === objectiveType) {
meansProgress = true;
hasUpdated = true;
if (el.objectiveObj.groupId === undefined) {
// this objective only involves a single entity
el.objectiveObj.currentPercentage = 100;
} else {
el.objectiveObj.currentPercentage += (1 / entitiesInGroup) * 100;
}
}
}
if (hasUpdated && el.store !== 'advanceWhen') {
const [itemColor, objectiveText] = story.returnObjectiveText(
el.objectiveObj,
meansProgress
);
let escAddendum = '';
if (story.noOfTimesHitEscMessageWasAppended < 4) {
escAddendum = story.escAddendum;
story.noOfTimesHitEscMessageWasAppended++;
}
updatedObjectiveMessages.push({
color: itemColor,
message: 'Objectives: ' + objectiveText + escAddendum,
});
}
});
story.updateObjectiveDisplay();
if (updatedObjectiveMessages.length < 1) {
// this event didnt cause any progress with the objectives
// so we'll print a yellow status message
let printStatus = true;
let statusColor = 'yellow';
let statusMessage = `${entityClassification}[${makeName(entityId)}] ${
c.objectiveTypes[eventId].completed_desc
}`;
if (
(eventId === c.objectiveTypes.inspected.id && !meansProgress) ||
(eventId === c.objectiveTypes.hasDespawned.id && !failState) ||
eventId === c.objectiveTypes.mustHaveArrived.id
) {
printStatus = false;
}
if (printStatus) {
status.add(statusColor, statusMessage, timing.times.play);
}
} else {
updatedObjectiveMessages.forEach((el) => {
let printThisStatus = true;
if (eventId === c.objectiveTypes.hasDespawned.id && !failState) {
printThisStatus = false;
}
if (printThisStatus) {
status.add(el.color, el.message, timing.times.play);
}
});
}
story.checkBeatCompletion();
if (failState && !story.missionFailureWasTriggered) {
story.missionFailureWasTriggered = true;
if (c.debug.objectives)
console.log('MISSION FAILED!', story.currentObjectives);
plates.loadPlate('mission_failed', -1, 'Mission failed');
plates.fadeInPlate(25);
plates.fadeInMatte(50, 1000);
timing.toggleEntityMovement(
false,
'story.js@checkAgainstCurrentObjectives() 1',
3000
);
timing.setTimeout(
() => {
soundEffects.muteUnmuteAllLoops(
'story.js@checkAgainstCurrentObjectives() 2',
true
);
},
timing.modes.play,
3000
);
plates.fadeOutPlate(25, 4000);
timing.setTimeout(
() => {
gameMenus.showMissionFailedButtonSet();
},
timing.modes.play,
5100
);
}
},
checkBeatCompletion() {
let updatedObjectiveMessages = [];
const currentSceneObject = story.sceneList.find(
(el) => el.id === story.currentScene
).sceneObject;
const isTheFinalGameplayBeat =
currentSceneObject.storyBeats[story.currentSceneBeat]
.isTheFinalGameplayBeat;
// if this is the final gameplay beat, all other objectives
// are complete, and the designated entities survived
// then set the mustHaveSurvived objectives to 100%
if (isTheFinalGameplayBeat) {
let allOthersComplete = true;
story.currentObjectives.show.forEach((obj) => {
if (
obj.type !== c.objectiveTypes.mustHaveSurvived.id &&
Math.ceil(obj.currentPercentage) < obj.requiredPercentage
) {
allOthersComplete = false;
}
});
if (allOthersComplete) {
story.currentObjectives.show.forEach((obj2) => {
if (
obj2.type === c.objectiveTypes.mustHaveSurvived.id &&
obj2.failed === false
) {
obj2.currentPercentage = 100;
const [itemColor, objectiveText] = story.returnObjectiveText(
obj2,
true
);
updatedObjectiveMessages.push({
color: itemColor,
message: 'Objectives: ' + objectiveText,
});
}
});
}
}
story.updateObjectiveDisplay();
if (updatedObjectiveMessages.length > 0) {
updatedObjectiveMessages.forEach((el) => {
status.add(el.color, el.message, timing.times.play);
});
}
// if all needed objectives are done, we can advance to the
// next story beat
let allComplete = true;
story.currentObjectives.advanceWhen.forEach((obj) => {
if (
Math.ceil(obj.currentPercentage) < obj.requiredPercentage ||
obj.failed
)
allComplete = false;
});
if (isTheFinalGameplayBeat) {
story.currentObjectives.show.forEach((obj) => {
if (
Math.ceil(obj.currentPercentage) < obj.requiredPercentage ||
obj.failed
)
allComplete = false;
});
if (c.debug.objectives) console.log('isTheFinalGameplayBeat');
}
if (c.debug.objectives)
console.log('allComplete:', allComplete, story.currentObjectives);
if (allComplete) {
if (c.debug.objectives)
console.log(
'ALLCOMPLETE IS TRUE, ADVANCE TO THE NEXT STORY BEAT!',
story.currentObjectives
);
if (story.currentSceneBeat < currentSceneObject.storyBeats.length - 1) {
// there are more beats in this scene
story.advance(story.currentScene, story.currentSceneBeat + 1);
} else {
// advance to the next scene
plates.loadPlate('mission_success', 1000);
plates.fadeInPlate(25, 1000);
timing.toggleEntityMovement(
false,
'story.js@checkBeatCompletion() 1',
2000
);
timing.setTimeout(
() => {
soundEffects.muteUnmuteAllLoops(
'story.js@checkBeatCompletion() 2',
true
);
},
timing.modes.play,
2000
);
plates.fadeInMatte(50, 1000);
plates.fadeOutPlate(50, 5000);
timing.setTimeout(
() => {
story.advance(null, 0);
},
timing.modes.play,
8500
);
}
}
},
entityWasDespawned(entityId) {
if (c.debug.objectives) console.log('entityWasDespawned:', entityId);
if (story.currentStoryEntities[entityId] === undefined) return;
story.currentStoryEntities[entityId].wasDespawned = true;
story.checkAgainstCurrentObjectives(
entityId,
c.objectiveTypes.hasDespawned.id
);
},
updateObjectiveDisplay() {
// console.log('updateObjectiveDisplay() called');
const re = [];
re.push(
"<div class='game__pause-objectives-title'>Current objectives:</div>\n<ul class='game__pause-objectives-list'>"
);
const objectiveLis = story.currentObjectives.show.map((obj) => {
const [itemColor, objectiveText] = story.returnObjectiveText(obj);
return `<li class='game__pause-objective game__pause-objective--${itemColor}'>${objectiveText}</li>`;
});
re.push(objectiveLis.join(''));
re.push('</ul>');
document.getElementById('game__pause-objectives').innerHTML = re.join('');
},
returnObjectiveText(objectiveObj, meansProgress = false) {
let itemColor = 'yellow';
if (meansProgress) itemColor = 'dark_green';
let objectiveText = '';
let completed = false;
if (
objectiveObj.requiredPercentage <=
Math.ceil(objectiveObj.currentPercentage)
) {
itemColor = 'green';
completed = true;
}
if (objectiveObj.failed) itemColor = 'red';
if (objectiveObj.groupId === undefined) {
let entityClassification = story.assertClassification(
objectiveObj.entityId
);
let mainText = c.objectiveTypes[objectiveObj.type].desc;
let parensText = 'incomplete';
if (completed) {
parensText = 'complete';
mainText = c.objectiveTypes[objectiveObj.type].completed_desc;
}
if (objectiveObj.failed) {
parensText = 'failed';
mainText = c.objectiveTypes[objectiveObj.type].desc;
}
objectiveText = `${entityClassification}${makeName(
objectiveObj.entityId
)} ${mainText} (${parensText})`;
} else {
let groupClassification = '';
let firstInGroup = Object.values(story.currentStoryEntities).find(
(en) => en.groupId === objectiveObj.groupId
);
if (firstInGroup !== undefined)
groupClassification = story.assertClassification(firstInGroup.id);
if (groupClassification !== '')
groupClassification = groupClassification.toLowerCase();
let mainText = c.objectiveTypes[objectiveObj.type].desc;
let parensText = Math.ceil(objectiveObj.currentPercentage) + '% complete';
if (completed) {
parensText = 'complete';
mainText = c.objectiveTypes[objectiveObj.type].completed_desc;
}
if (objectiveObj.failed) {
parensText = 'failed';
mainText = c.objectiveTypes[objectiveObj.type].desc;
}
objectiveText = `${
objectiveObj.requiredPercentage
}% of ${groupClassification}group ${
objectiveObj.groupId.charAt(0).toUpperCase() +
objectiveObj.groupId.slice(1)
} ${mainText} (${parensText})`;
}
return [itemColor, objectiveText];
},
cleanUp() {
if (c.debug.objectives) console.log('story.cleanUp() called');
story.currentObjectives = {
show: [],
advanceWhen: [],
};
story.handlers.dispatch({ type: c.actions.CLEANUP });
entities.cleanUp();
shots.cleanUp();
soundEffects.cleanUp();
shields.cleanUp();
formations.cleanUp();
hud.cleanUp();
},
};
export default story;
|
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
importScripts('/__WORKBOX/buildFile/workbox-sw');
importScripts('/infra/testing/comlink/sw-interface.js');
workbox.routing.registerRoute(
new RegExp('/__WORKBOX/uniqueValue'),
workbox.strategies.networkFirst({
cacheName: 'network-first',
})
);
self.addEventListener('install', (event) => {
self.skipWaiting();
event.waitUntil(
caches.open('network-first')
.then((cache) => cache.put('/__WORKBOX/uniqueValue', new Response('Cached')))
);
});
self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim()));
|
const readline = require("readline");
const DELAY_MILISECOND = 1000;
async function readLines(prompt) {
return new Promise(resolve => {
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
rl.question(
'\n'+prompt,
function(answer) {
resolve(answer)
rl.close()
})
});
}
//to avoid the problem of 429 (too many requests in a time frame)
async function delay(t, v) {
return new Promise(function(resolve) {
setTimeout(resolve.bind(null, v), t);
});
}
const wait = async (ms) => {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
function flatDeep(arr, d = 1) {
return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
: arr.slice();
};
module.exports = {
readLines,
delay,
DELAY_MILISECOND,
flatDeep,
wait
};
|
import React, { useEffect, useState } from "react";
import Grid from "@mui/material/Grid";
import { useSelector } from "react-redux";
import DeliverablesSkeleton from "./components/DeliverablesSkeleton";
import { Stack } from "@mui/material";
import Link from "@mui/material/Link";
import { DataStore, Predicates, SortDirection } from "aws-amplify";
import * as models from "../../models/index";
import { dataStoreReadyStatusSelector } from "../../redux/Selectors";
import { convertListDataToObject } from "../../utilities";
import PropTypes from "prop-types";
import EditableDeliverable from "./components/EditableDeliverable";
import AddableDeliverable from "./components/AddableDeliverable";
import _ from "lodash";
import GetError from "../../ErrorComponents/GetError";
const initialDeliverablesSortedState = {
deliverables: [],
defaults: [],
};
function DeliverableGridSelect(props) {
const [deliverablesSorted, setDeliverablesSorted] = useState(
initialDeliverablesSortedState
);
const [state, setState] = useState({});
const [errorState, setErrorState] = useState(null);
const [truncated, setTruncated] = useState(true);
const [availableDeliverables, setAvailableDeliverables] = useState({});
const dataStoreReadyStatus = useSelector(dataStoreReadyStatusSelector);
const [isFetching, setIsFetching] = useState(false);
function convertExistingDeliverablesToState() {
const result = {};
for (const d of props.deliverables) {
const deliverableType = availableDeliverables[d.deliverableType.id];
result[d.deliverableType.id] = {
count: d.count,
id: d.deliverableType.id,
label: deliverableType ? deliverableType.label : "",
createdAt: d.createdAt,
unit: d.unit,
orderInGrid: d.orderInGrid,
icon: deliverableType ? deliverableType.icon : "",
};
}
setState(result);
}
useEffect(convertExistingDeliverablesToState, [
props.deliverables,
availableDeliverables,
]);
function sortDeliverables() {
const result = {
deliverables: [],
defaults: [],
};
for (const i of Object.values(availableDeliverables)) {
const value = state[i.id];
if (value) {
result.deliverables.push(value);
} else {
result.defaults.push(i);
}
}
result.deliverables = result.deliverables.sort(
(a, b) => parseInt(a.orderInGrid) - parseInt(b.orderInGrid)
);
setDeliverablesSorted(result);
}
useEffect(sortDeliverables, [availableDeliverables, state]);
async function getAvailableDeliverables() {
if (!dataStoreReadyStatus) {
setIsFetching(true);
} else {
try {
const availableDeliverablesResult = await DataStore.query(
models.DeliverableType,
Predicates.ALL,
{
sort: (s) => s.createdAt(SortDirection.ASCENDING),
}
);
setAvailableDeliverables(
convertListDataToObject(availableDeliverablesResult)
);
setIsFetching(false);
} catch (e) {
setErrorState(e);
console.log(e);
}
}
}
useEffect(() => getAvailableDeliverables(), []);
function onAddNewDeliverable(deliverable) {
let orderInGrid = 0;
for (const d of Object.values(state)) {
if (d.orderInGrid > orderInGrid);
orderInGrid = parseInt(d.orderInGrid) + 1;
}
setState((prevState) => ({
...prevState,
[deliverable.id]: {
...deliverable,
orderInGrid,
},
}));
const {
createdAt,
updatedAt,
icon,
_lastChangedAt,
_deleted,
_version,
...rest
} = deliverable;
props.onChange({ ...rest, orderInGrid });
}
function onChangeUnit(deliverableId, unit) {
const existing = state[deliverableId];
if (existing) {
setState((prevState) => ({
...prevState,
[deliverableId]: { ...prevState[deliverableId], unit },
}));
}
props.onChange({ id: deliverableId, unit });
}
const onChangeCount = (deliverableId, count) => {
const existing = state[deliverableId];
if (existing) {
setState((prevState) => ({
...prevState,
[deliverableId]: { ...prevState[deliverableId], count },
}));
}
props.onChange({ id: deliverableId, count });
};
function onDelete(deliverableId) {
setState((prevState) => _.omit(prevState, deliverableId));
props.onDelete(deliverableId);
}
useEffect(
() => setTruncated(Object.values(availableDeliverables).length > 5),
[availableDeliverables]
);
if (!!errorState) {
return <GetError />;
} else if (isFetching) {
return <DeliverablesSkeleton />;
} else {
let count = 0;
return (
<Stack
spacing={
deliverablesSorted.deliverables.length > 0 &&
deliverablesSorted.defaults.length > 0
? 5
: 0
}
justifyContent={"flex-start"}
direction={"column"}
>
<Stack spacing={1} direction={"column"}>
{deliverablesSorted.deliverables.map((deliverable) => {
count++;
if (count > 5 && truncated) {
return (
<React.Fragment
key={deliverable.id}
></React.Fragment>
);
} else {
return (
<EditableDeliverable
key={deliverable.id}
onChangeCount={onChangeCount}
onChangeUnit={onChangeUnit}
onDelete={onDelete}
deliverable={deliverable}
/>
);
}
})}
</Stack>
<Stack spacing={1} direction={"column"}>
{deliverablesSorted.defaults.map((deliverableType) => {
count++;
if (count > 5 && truncated) {
return (
<React.Fragment
key={deliverableType.id}
></React.Fragment>
);
} else {
return (
<AddableDeliverable
key={deliverableType.id}
onAdd={onAddNewDeliverable}
deliverableType={deliverableType}
/>
);
}
})}
</Stack>
<Link
href="#"
onClick={(e) => {
setTruncated((prevState) => !prevState);
e.preventDefault();
}}
color="inherit"
>
{truncated ? "More..." : "Less..."}
</Link>
</Stack>
);
}
}
DeliverableGridSelect.propTypes = {
deliverables: PropTypes.arrayOf(PropTypes.object),
onChange: PropTypes.func,
onDelete: PropTypes.func,
};
DeliverableGridSelect.defaultProps = {
deliverables: [],
onChange: () => {},
onDelete: () => {},
};
export default DeliverableGridSelect;
|
require.config({
baseUrl: window.global_website +'assets/weengine/js/app',
paths: {
'jquery': '../lib/jquery-1.11.1.min',
'jquery.ui': '../lib/jquery-ui-1.10.3.min',
'jquery.caret': '../lib/jquery.caret',
'jquery.jplayer': '../../components/jplayer/jquery.jplayer.min',
'jquery.zclip': '../../components/zclip/jquery.zclip.min',
'bootstrap': '../lib/bootstrap.min',
'bootstrap.switch': '../../components/switch/bootstrap-switch.min',
'angular': '../lib/angular.min',
'angular.sanitize': '../lib/angular-sanitize.min',
'underscore': '../lib/underscore-min',
'chart': '../lib/chart.min',
'moment': '../lib/moment',
'filestyle': '../lib/bootstrap-filestyle.min',
'datetimepicker': '../../components/datetimepicker/jquery.datetimepicker',
'daterangepicker': '../../components/daterangepicker/daterangepicker',
'colorpicker': '../../components/colorpicker/spectrum',
'map': 'http://api.map.baidu.com/getscript?v=2.0&ak=F51571495f717ff1194de02366bb8da9&services=&t=20140530104353',
'editor': '../../components/tinymce/tinymce.min',
'kindeditor':'../../components/kindeditor/lang/zh_CN',
'kindeditor.main':'../../components/kindeditor/kindeditor-min',
'css': '../lib/css.min',
'webuploader' : '../../components/webuploader/webuploader.min',
'json2' : '../lib/json2',
'wapeditor' : './wapeditor',
'jquery.wookmark': '../lib/jquery.wookmark.min',
'validator': '../lib/bootstrapValidator.min',
'select2' : '../../components/select2/zh-CN',
'clockpicker': '../../components/clockpicker/clockpicker.min',
'jquery.qrcode': '../lib/jquery.qrcode.min',
'raty': '../lib/raty.min'
},
shim:{
'jquery.ui': {
exports: "$",
deps: ['jquery']
},
'jquery.caret': {
exports: "$",
deps: ['jquery']
},
'jquery.jplayer': {
exports: "$",
deps: ['jquery']
},
'bootstrap': {
exports: "$",
deps: ['jquery']
},
'bootstrap.switch': {
exports: "$",
deps: ['bootstrap', 'css!../../components/switch/bootstrap-switch.min.css']
},
'angular': {
exports: 'angular',
deps: ['jquery']
},
'angular.sanitize': {
exports: 'angular',
deps: ['angular']
},
'emotion': {
deps: ['jquery']
},
'chart': {
exports: 'Chart'
},
'filestyle': {
exports: '$',
deps: ['bootstrap']
},
'daterangepicker': {
exports: '$',
deps: ['bootstrap', 'moment', 'css!../../components/daterangepicker/daterangepicker.css']
},
'datetimepicker' : {
exports : '$',
deps: ['jquery', 'css!../../components/datetimepicker/jquery.datetimepicker.css']
},
'kindeditor': {
deps: ['kindeditor.main', 'css!../../components/kindeditor/themes/default/default.css']
},
'colorpicker': {
exports: '$',
deps: ['css!../../components/colorpicker/spectrum.css']
},
'map': {
exports: 'BMap'
},
'json2': {
exports: 'JSON'
},
'webuploader': {
deps: ['css!../../components/webuploader/webuploader.css', 'css!../../components/webuploader/style.css']
},
'wapeditor' : {
exports : 'angular',
deps: ['angular.sanitize', 'jquery.ui', 'underscore', 'fileUploader', 'json2', 'datetimepicker']
},
'jquery.wookmark': {
exports: "$",
deps: ['jquery']
},
'validator': {
exports: "$",
deps: ['bootstrap']
},
'select2': {
deps: ['css!../../components/select2/select2.min.css', window.global_website +'assets/weengine/components/select2/select2.min.js']
},
'clockpicker': {
exports: "$",
deps: ['css!../../components/clockpicker/clockpicker.min.css', 'bootstrap']
},
'jquery.qrcode': {
exports: "$",
deps: ['jquery']
}
}
});
|
// Reto: https://adventjs.dev/challenges/05
function daysToXmas(date) {
const xmasDate = new Date('Dec 25, 2021');
const diff = xmasDate.getTime() - date.getTime();
const daysToXmas = diff / (1000 * 60 * 60 * 24);
if (Math.floor(daysToXmas) === daysToXmas) return daysToXmas;
return Math.floor(daysToXmas + 1);
}
// ______________________________________________________________________
const date1 = new Date('Dec 1, 2021');
daysToXmas(date1); // 24
const date2 = new Date('Dec 24, 2021 00:00:01');
daysToXmas(date2); // 1
const date3 = new Date('Dec 24, 2021 23:59:59');
daysToXmas(date3); // 1
const date4 = new Date('December 20, 2021 03:24:00');
daysToXmas(date4); // 5
|
/*
copyright (c) 2018 jones
http://www.apache.org/licenses/LICENSE-2.0
开源项目 https://github.com/jones2000/HQChart
jones_2000@163.com
指标基类及定制指标
*/
import {
JSCommonResource_Global_JSChartResource as g_JSChartResource,
} from './umychart.resource.wechat.js'
import { JSCommonComplier } from "./umychart.complier.wechat.js"; //通达信编译器
//日志
import { JSConsole } from "./umychart.console.wechat.js"
import {
JSCommon_ChartData as ChartData, JSCommon_HistoryData as HistoryData,
JSCommon_SingleData as SingleData, JSCommon_MinuteData as MinuteData,
JSCommon_JSCHART_EVENT_ID as JSCHART_EVENT_ID,
} from "./umychart.data.wechat.js";
//图形库
import {
JSCommonChartPaint_IChartPainting as IChartPainting,
JSCommonChartPaint_ChartSingleText as ChartSingleText,
JSCommonChartPaint_ChartDrawIcon as ChartDrawIcon,
JSCommonChartPaint_ChartDrawText as ChartDrawText,
JSCommonChartPaint_ChartDrawNumber as ChartDrawNumber,
JSCommonChartPaint_ChartKLine as ChartKLine,
JSCommonChartPaint_ChartColorKline as ChartColorKline,
JSCommonChartPaint_ChartLine as ChartLine,
JSCommonChartPaint_ChartSubLine as ChartSubLine,
JSCommonChartPaint_ChartPointDot as ChartPointDot,
JSCommonChartPaint_ChartStick as ChartStick,
JSCommonChartPaint_ChartLineStick as ChartLineStick,
JSCommonChartPaint_ChartStickLine as ChartStickLine,
JSCommonChartPaint_ChartOverlayKLine as ChartOverlayKLine,
JSCommonChartPaint_ChartMinuteInfo as ChartMinuteInfo,
JSCommonChartPaint_ChartRectangle as ChartRectangle,
JSCommonChartPaint_ChartMultiText as ChartMultiText,
JSCommonChartPaint_ChartMultiLine as ChartMultiLine,
JSCommonChartPaint_ChartMultiBar as ChartMultiBar,
JSCommonChartPaint_ChartPie as ChartPie,
JSCommonChartPaint_ChartCircle as ChartCircle,
JSCommonChartPaint_ChartChinaMap as ChartChinaMap,
JSCommonChartPaint_ChartRadar as ChartRadar,
JSCommonChartPaint_ChartCorssCursor as ChartCorssCursor,
JSCommonChartPaint_ChartBuySell as ChartBuySell,
JSCommonChartPaint_ChartMACD as ChartMACD,
JSCommonChartPaint_ChartSplashPaint as ChartSplashPaint,
JSCommonChartPaint_ChartBackground as ChartBackground,
JSCommonChartPaint_ChartMinuteVolumBar as ChartMinuteVolumBar,
JSCommonChartPaint_ChartMultiHtmlDom as ChartMultiHtmlDom,
JSCommonChartPaint_ChartLock as ChartLock,
JSCommonChartPaint_ChartVolStick as ChartVolStick,
JSCommonChartPaint_ChartBand as ChartBand,
JSCommonChartPaint_ChartLineMultiData as ChartLineMultiData,
JSCommonChartPaint_ChartStraightLine as ChartStraightLine,
} from "./umychart.chartpaint.wechat.js";
import
{
JSCommonSplit_CoordinateInfo as CoordinateInfo,
JSCommonSplit_IFrameSplitOperator as IFrameSplitOperator,
JSCommonSplit_FrameSplitKLinePriceY as FrameSplitKLinePriceY,
JSCommonSplit_FrameSplitY as FrameSplitY,
JSCommonSplit_FrameSplitKLineX as FrameSplitKLineX,
JSCommonSplit_FrameSplitMinutePriceY as FrameSplitMinutePriceY,
JSCommonSplit_FrameSplitMinuteX as FrameSplitMinuteX,
JSCommonSplit_FrameSplitXData as FrameSplitXData,
JSCommonSplit_SplitData as SplitData,
JSCommonSplit_PriceSplitData as PriceSplitData,
} from './umychart.framesplit.wechat.js'
import
{
JSCommonChartTitle_IChartTitlePainting as IChartTitlePainting,
JSCommonChartTitle_DynamicKLineTitlePainting as DynamicKLineTitlePainting,
JSCommonChartTitle_DynamicMinuteTitlePainting as DynamicMinuteTitlePainting,
JSCommonChartTitle_DynamicChartTitlePainting as DynamicChartTitlePainting,
JSCommonChartTitle_DynamicTitleData as DynamicTitleData,
JSCommonChartTitle_STRING_FORMAT_TYPE as STRING_FORMAT_TYPE,
} from './umychart.charttitle.wechat.js'
//////////////////////////////////////////////////////////
//
// 指标信息
//
function IndexInfo(name, param)
{
this.Name = name; //名字
this.Param = param; //参数
this.LineColor; //线段颜色
this.ReqeustData = null; //数据请求
}
function BaseIndex(name)
{
this.Index; //指标阐述
this.Name = name; //指标名字
this.UpdateUICallback; //数据到达回调
//默认创建都是线段
this.Create = function (hqChart, windowIndex)
{
for (var i in this.Index)
{
if (!this.Index[i].Name) continue;
var maLine = new ChartLine();
maLine.Canvas = hqChart.Canvas;
maLine.Name = this.Name + '-' + i.toString();
maLine.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
maLine.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
maLine.Color = this.Index[i].LineColor;
hqChart.ChartPaint.push(maLine);
}
}
//指标不支持 周期/复权/股票等
this.NotSupport = function (hqChart, windowIndex, message)
{
var paint = hqChart.GetChartPaint(windowIndex);
for (var i in paint)
{
paint[i].Data.Data = []; //清空数据
if (i == 0) paint[i].NotSupportMessage = message;
}
}
//格式化指标名字+参数
//格式:指标名(参数1,参数2,参数3,...)
this.FormatIndexTitle = function ()
{
var title = this.Name;
var param = null;
for (var i in this.Index)
{
var item = this.Index[i];
if (item.Param == null) continue;
if (param) param += ',' + item.Param.toString();
else param = item.Param.toString();
}
if (param) title += '(' + param + ')';
return title;
}
this.InvokeUpdateUICallback = function (paint)
{
if (typeof (this.UpdateUICallback) != 'function') return;
let indexData = new Array();
for (let i in paint)
{
indexData.push({ Name: this.Index[i].Name, Data: paint[i].Data });
}
this.UpdateUICallback(indexData);
}
}
//脚本指标
//name=指标名字 args=参数名字 参数值
function ScriptIndex(name, script, args, option)
{
this.newMethod = BaseIndex; //派生
this.newMethod(name);
delete this.newMethod;
this.Script = script;
this.Arguments = [];
this.OutVar = [];
this.ID; //指标ID
this.FloatPrecision = 2; //小数位数
this.StringFormat;
this.KLineType = null; //K线显示类型
this.InstructionType; //五彩K线, 交易指标
this.YSpecificMaxMin = null; //最大最小值
this.YSplitScale = null; //固定刻度
this.OutName=null; //动态输出指标名字
//指标上锁配置信息
this.IsLocked = false; //是否锁住指标
this.LockCallback = null;
this.LockID = null;
this.LockBG = null; //锁背景色
this.LockTextColor = null;
this.LockText = null;
this.LockFont = null;
this.LockCount = 10;
this.TitleFont=g_JSChartResource.DynamicTitleFont; //标题字体
if (option)
{
if (option.FloatPrecision >= 0) this.FloatPrecision = option.FloatPrecision;
if (option.StringFormat > 0) this.StringFormat = option.StringFormat;
if (option.ID) this.ID = option.ID;
if (option.KLineType) this.KLineType = option.KLineType;
if (option.InstructionType) this.InstructionType = option.InstructionType;
if (option.YSpecificMaxMin) this.YSpecificMaxMin = option.YSpecificMaxMin;
if (option.YSplitScale) this.YSplitScale = option.YSplitScale;
if (option.TitleFont) this.TitleFont=option.TitleFont;
if (option.OutName) this.OutName=option.OutName;
}
if (option && option.Lock)
{
if (option.Lock.IsLocked == true) this.IsLocked = true; //指标上锁
if (option.Lock.Callback) this.LockCallback = option.Lock.Callback; //锁回调
if (option.Lock.ID) this.LockID = option.Lock.ID; //锁ID
if (option.Lock.BG) this.LockBG = option.Lock.BG;
if (option.Lock.TextColor) this.LockTextColor = option.Lock.TextColor;
if (option.Lock.Text) this.LockText = option.Lock.Text;
if (option.Lock.Font) this.LockFont = option.Lock.Font;
if (option.Lock.Count) this.LockCount = option.Lock.Count;
}
if (args) this.Arguments = args;
this.SetLock = function (lockData) {
if (lockData.IsLocked == true) {
this.IsLocked = true; //指标上锁
if (lockData.Callback) this.LockCallback = lockData.Callback; //锁回调
if (lockData.ID) this.LockID = lockData.ID; //锁ID
if (lockData.BG) this.LockBG = lockData.BG;
if (lockData.TextColor) this.LockTextColor = lockData.TextColor;
if (lockData.Text) this.LockText = lockData.Text;
if (lockData.Font) this.LockFont = lockData.Font;
if (lockData.Count) this.LockCount = lockData.Count;
}
else { //清空锁配置信息
this.IsLocked = false; //是否锁住指标
this.LockCallback = null;
this.LockID = null;
this.LockBG = null; //锁背景色
this.LockTextColor = null;
this.LockText = null;
this.LockFont = null;
this.LockCount = 10;
}
}
this.ExecuteScript = function (hqChart, windowIndex, hisData)
{
this.OutVar = [];
let self = this;
let param =
{
HQChart: hqChart,
WindowIndex: windowIndex,
HistoryData: hisData,
Self: this
};
let hqDataType = 0; //默认K线
if (hqChart.ClassName === 'MinuteChartContainer' || hqChart.ClassName==='MinuteChartHScreenContainer')
{
if (hqChart.DayCount>1) hqDataType=HQ_DATA_TYPE.MULTIDAY_MINUTE_ID; //多日分钟
else hqDataType=HQ_DATA_TYPE.MINUTE_ID;
}
else if (hqChart.ClassName==='HistoryMinuteChartContainer')
{
hqDataType=HQ_DATA_TYPE.HISTORY_MINUTE_ID; //历史分钟
}
let option =
{
HQDataType: hqDataType,
Symbol: hqChart.Symbol,
Data: hisData,
SourceData: hqChart.SourceData, //原始数据
Callback: this.RecvResultData, CallbackParam: param,
Async: true,
MaxReqeustDataCount: hqChart.MaxReqeustDataCount,
MaxRequestMinuteDayCount: hqChart.MaxRequestMinuteDayCount,
Arguments: this.Arguments
};
if (hqDataType===HQ_DATA_TYPE.HISTORY_MINUTE_ID) option.TrateDate=hqChart.TradeDate;
if (hqDataType===HQ_DATA_TYPE.MULTIDAY_MINUTE_ID) option.DayCount=hqChart.DayCount;
if (hqChart.NetworkFilter) option.NetworkFilter = hqChart.NetworkFilter;
let code = this.Script;
let run = JSCommonComplier.JSComplier.Execute(code, option, hqChart.ScriptErrorCallback);
}
this.RecvResultData = function (outVar, param)
{
let hqChart = param.HQChart;
let windowIndex = param.WindowIndex;
let hisData = param.HistoryData;
param.Self.OutVar = outVar;
param.Self.BindData(hqChart, windowIndex, hisData);
if (param.Self.IsLocked == false) //不上锁
{
param.HQChart.Frame.SubFrame[windowIndex].Frame.SetLock(null);
}
else //上锁
{
let lockData =
{
IsLocked: true, Callback: param.Self.LockCallback, IndexName: param.Self.Name, ID: param.Self.LockID,
BG: param.Self.LockBG, Text: param.Self.LockText, TextColor: param.Self.LockTextColor, Font: param.Self.LockFont,
Count: param.Self.LockCount
};
param.HQChart.Frame.SubFrame[windowIndex].Frame.SetLock(lockData);
}
param.HQChart.UpdataDataoffset(); //更新数据偏移
param.HQChart.UpdateFrameMaxMin(); //调整坐标最大 最小值
param.HQChart.Draw();
var event = hqChart.GetIndexEvent(); //指标计算完成回调
if (event)
{
var self = param.Self;
var data = {
OutVar: self.OutVar, WindowIndex: windowIndex, Name: self.Name, Arguments: self.Arguments, HistoryData: hisData,
Stock: { Symbol: hqChart.Symbol, Name: hqChart.Name }
};
event.Callback(event, data, self);
}
}
this.CreateLine = function (hqChart, windowIndex, varItem, id)
{
let line = new ChartLine();
line.Canvas = hqChart.Canvas;
line.DrawType = 1; //无效数不画
line.Name = varItem.Name;
line.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
line.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
if (varItem.Color) line.Color = this.GetColor(varItem.Color);
else line.Color = this.GetDefaultColor(id);
if (varItem.IsShow==false) line.IsShow=false;
if (varItem.LineWidth)
{
let width = parseInt(varItem.LineWidth.replace("LINETHICK", ""));
if (!isNaN(width) && width > 0) line.LineWidth = width;
}
if (varItem.IsDotLine) line.IsDotLine = true; //虚线
if (varItem.IsShow == false) line.IsShow = false;
let titleIndex = windowIndex + 1;
line.Data.Data = varItem.Data;
if (varItem.IsShowTitle===false) //NOTEXT 不绘制标题
{
}
else if (IFrameSplitOperator.IsString(varItem.Name) && varItem.Name.indexOf("NOTEXT")==0) //标题中包含NOTEXT不绘制标题
{
}
else
{
hqChart.TitlePaint[titleIndex].Data[id] = new DynamicTitleData(line.Data, (varItem.NoneName==true? null: varItem.Name) , line.Color);
}
hqChart.ChartPaint.push(line);
}
this.CreateOverlayLine = function (hqChart, windowIndex, varItem, id)
{
let line = new ChartSubLine();
line.Canvas = hqChart.Canvas;
line.DrawType = 1; //无效数不画
line.Name = varItem.Name;
line.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
line.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
if (varItem.Color) line.Color = this.GetColor(varItem.Color);
else line.Color = this.GetDefaultColor(id);
if (varItem.LineWidth) {
let width = parseInt(varItem.LineWidth.replace("LINETHICK", ""));
if (!isNaN(width) && width > 0) line.LineWidth = width;
}
if (varItem.IsDotLine) line.IsDotLine = true; //虚线
if (varItem.IsShow == false) line.IsShow = false;
let titleIndex = windowIndex + 1;
line.Data.Data = varItem.Data;
hqChart.TitlePaint[titleIndex].Data[id] = new DynamicTitleData(line.Data, varItem.Name, line.Color);
hqChart.ChartPaint.push(line);
}
//创建柱子
this.CreateBar = function (hqChart, windowIndex, varItem, id)
{
let bar = new ChartStickLine();
bar.Canvas = hqChart.Canvas;
if (varItem.Draw.Width > 0) bar.LineWidth = varItem.Draw.Width;
else bar.LineWidth=1;
bar.Name = varItem.Name;
bar.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
bar.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
if (varItem.Color) bar.Color = this.GetColor(varItem.Color);
else bar.Color = this.GetDefaultColor(id);
let titleIndex = windowIndex + 1;
bar.Data.Data = varItem.Draw.DrawData;
bar.BarType = varItem.Draw.Type;
//hqChart.TitlePaint[titleIndex].Data[id]=new DynamicTitleData(bar.Data,varItem.Name,bar.Color);
hqChart.ChartPaint.push(bar);
}
//DRAWTEXT
this.CreateDrawTextV2=function(hqChart, windowIndex, varItem, id)
{
var chartText = new ChartDrawText();
chartText.Canvas = hqChart.Canvas;
chartText.TextAlign='left';
chartText.Name = varItem.Name;
chartText.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chartText.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
chartText.ReloadResource();
if (varItem.Color) chartText.Color = this.GetColor(varItem.Color);
else chartText.Color = this.GetDefaultColor(id);
if (varItem.Draw.DrawData) chartText.Data.Data = varItem.Draw.DrawData;
chartText.Text = varItem.Draw.Text;
if (varItem.Draw.YOffset > 0) chartText.YOffset = varItem.Draw.YOffset;
if (varItem.Draw.TextAlign) chartText.TextAlign = varItem.Draw.TextAlign;
//指定输出位置
if (varItem.Draw.FixedPosition==="TOP") chartText.FixedPosition=1;
else if (varItem.Draw.FixedPosition==="BOTTOM") chartText.FixedPosition=2;
if (varItem.DrawVAlign>=0)
{
if (varItem.DrawVAlign==0) chartText.Direction=1;
else if (varItem.DrawVAlign==1) chartText.Direction=0;
else if (varItem.DrawVAlign==2) chartText.Direction=2;
}
if (varItem.DrawAlign>=0)
{
if (varItem.DrawAlign==0) chartText.TextAlign="left";
else if (varItem.DrawAlign==1) chartText.TextAlign="center";
else if (varItem.DrawAlign==2) chartText.TextAlign='right';
}
if (varItem.DrawFontSize>0) chartText.FixedFontSize=varItem.DrawFontSize;
if (varItem.Background) chartText.TextBG=varItem.Background;
if (varItem.VerticalLine) chartText.VerticalLine=varItem.VerticalLine;
//var titleIndex = windowIndex + 1;
//hqChart.TitlePaint[titleIndex].Data[id]=new DynamicTitleData(bar.Data,varItem.Name,bar.Color);
hqChart.ChartPaint.push(chartText);
}
//DRAWNUMBER
this.CreateDrawNumber=function(hqChart,windowIndex,varItem,id)
{
var chartText=new ChartDrawNumber();
chartText.Canvas=hqChart.Canvas;
chartText.Name=varItem.Name;
chartText.ChartBorder=hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chartText.ChartFrame=hqChart.Frame.SubFrame[windowIndex].Frame;
chartText.ReloadResource();
if (varItem.Color) chartText.Color=this.GetColor(varItem.Color);
else chartText.Color=this.GetDefaultColor(id);
if (varItem.IsDrawCenter===true) chartText.TextAlign='center';
if (varItem.IsDrawAbove===true) chartText.TextBaseline='bottom'
if (varItem.IsDrawBelow===true) chartText.TextBaseline='top';
chartText.Data.Data=varItem.Draw.DrawData.Value;
chartText.Text=varItem.Draw.DrawData.Text;
if (varItem.Draw.Direction>0) chartText.Direction=varItem.Draw.Direction;
if (varItem.Draw.YOffset>0) chartText.YOffset=varItem.Draw.YOffset;
if (varItem.Draw.TextAlign) chartText.TextAlign=varItem.Draw.TextAlign;
//指定输出位置
if (varItem.Draw.FixedPosition==="TOP") chartText.FixedPosition=1;
else if (varItem.Draw.FixedPosition==="BOTTOM") chartText.FixedPosition=2;
if (varItem.DrawVAlign>=0)
{
if (varItem.DrawVAlign==0) chartText.TextBaseline='top';
else if (varItem.DrawVAlign==1) chartText.TextBaseline='middle';
else if (varItem.DrawVAlign==2) chartText.TextBaseline='bottom';
}
if (varItem.DrawAlign>=0)
{
if (varItem.DrawAlign==0) chartText.TextAlign="left";
else if (varItem.DrawAlign==1) chartText.TextAlign="center";
else if (varItem.DrawAlign==2) chartText.TextAlign='right';
}
if (varItem.DrawFontSize>0) chartText.FixedFontSize=varItem.DrawFontSize;
if (varItem.Background) chartText.TextBG=varItem.Background;
if (varItem.VerticalLine) chartText.VerticalLine=varItem.VerticalLine;
//let titleIndex=windowIndex+1;
//hqChart.TitlePaint[titleIndex].Data[id]=new DynamicTitleData(bar.Data,varItem.Name,bar.Color);
hqChart.ChartPaint.push(chartText);
}
//创建文本
this.CreateText = function (hqChart, windowIndex, varItem, id)
{
let chartText = new ChartSingleText();
chartText.Canvas = hqChart.Canvas;
chartText.TextAlign='left';
chartText.Name = varItem.Name;
chartText.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chartText.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
chartText.ReloadResource();
if (varItem.Color) chartText.Color = this.GetColor(varItem.Color);
else chartText.Color = this.GetDefaultColor(id);
let titleIndex = windowIndex + 1;
if (varItem.Draw.Position) chartText.Position=varItem.Draw.Position; //赋值坐标
if (varItem.Draw.DrawData) chartText.Data.Data = varItem.Draw.DrawData;
chartText.Text = varItem.Draw.Text;
if (varItem.Draw.Direction > 0) chartText.Direction = varItem.Draw.Direction;
if (varItem.Draw.YOffset > 0) chartText.YOffset = varItem.Draw.YOffset;
if (varItem.Draw.TextAlign) chartText.TextAlign = varItem.Draw.TextAlign;
if (varItem.DrawVAlign>=0)
{
if (varItem.DrawVAlign==0) chartText.Direction=1;
else if (varItem.DrawVAlign==1) chartText.Direction=0;
else if (varItem.DrawVAlign==2) chartText.Direction=2;
}
if (varItem.DrawAlign>=0)
{
if (varItem.DrawAlign==0) chartText.TextAlign="left";
else if (varItem.DrawAlign==1) chartText.TextAlign="center";
else if (varItem.DrawAlign==2) chartText.TextAlign='right';
}
if (varItem.DrawFontSize>0) chartText.FixedFontSize=varItem.DrawFontSize;
if (varItem.Background) chartText.TextBG=varItem.Background;
//hqChart.TitlePaint[titleIndex].Data[id]=new DynamicTitleData(bar.Data,varItem.Name,bar.Color);
hqChart.ChartPaint.push(chartText);
}
//COLORSTICK
this.CreateMACD = function (hqChart, windowIndex, varItem, id)
{
let chartMACD = new ChartMACD();
chartMACD.Canvas = hqChart.Canvas;
chartMACD.Name = varItem.Name;
chartMACD.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chartMACD.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
if (varItem.LineWidth)
{
var width=parseInt(varItem.LineWidth.replace("LINETHICK",""));
if (!isNaN(width) && width>0) chartMACD.LineWidth=width;
}
let titleIndex = windowIndex + 1;
chartMACD.Data.Data = varItem.Data;
var clrTitle=this.GetDefaultColor(id);
if (varItem.Color) clrTitle= this.GetColor(varItem.Color);
hqChart.TitlePaint[titleIndex].Data[id] = new DynamicTitleData(chartMACD.Data, varItem.Name, clrTitle);
hqChart.ChartPaint.push(chartMACD);
}
this.CreatePointDot = function (hqChart, windowIndex, varItem, id) {
let pointDot = new ChartPointDot();
pointDot.Canvas = hqChart.Canvas;
pointDot.Name = varItem.Name;
pointDot.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
pointDot.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
if (varItem.Color) pointDot.Color = this.GetColor(varItem.Color);
else pointDot.Color = this.GetDefaultColor(id);
if (varItem.Radius) pointDot.Radius = varItem.Radius;
if (varItem.LineWidth) {
let width = parseInt(varItem.LineWidth.replace("LINETHICK", ""));
if (!isNaN(width) && width > 0) pointDot.Radius = width;
}
let titleIndex = windowIndex + 1;
pointDot.Data.Data = varItem.Data;
hqChart.TitlePaint[titleIndex].Data[id] = new DynamicTitleData(pointDot.Data, varItem.Name, pointDot.Color);
hqChart.ChartPaint.push(pointDot);
}
this.CreateStick = function (hqChart, windowIndex, varItem, id) {
let chart = new ChartStick();
chart.Canvas = hqChart.Canvas;
chart.Name = varItem.Name;
chart.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chart.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
if (varItem.Color) chart.Color = this.GetColor(varItem.Color);
else chart.Color = this.GetDefaultColor(id);
if (varItem.LineWidth) {
let width = parseInt(varItem.LineWidth.replace("LINETHICK", ""));
if (!isNaN(width) && width > 0) chart.LineWidth = width;
}
let titleIndex = windowIndex + 1;
chart.Data.Data = varItem.Data;
hqChart.TitlePaint[titleIndex].Data[id] = new DynamicTitleData(chart.Data, varItem.Name, chart.Color);
hqChart.ChartPaint.push(chart);
}
this.CreateLineStick = function (hqChart, windowIndex, varItem, id) {
let chart = new ChartLineStick();
chart.Canvas = hqChart.Canvas;
chart.Name = varItem.Name;
chart.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chart.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
if (varItem.Color) chart.Color = this.GetColor(varItem.Color);
else chart.Color = this.GetDefaultColor(id);
if (varItem.LineWidth) {
let width = parseInt(varItem.LineWidth.replace("LINETHICK", ""));
if (!isNaN(width) && width > 0) chart.LineWidth = width;
}
let titleIndex = windowIndex + 1;
chart.Data.Data = varItem.Data;
hqChart.TitlePaint[titleIndex].Data[id] = new DynamicTitleData(chart.Data, varItem.Name, chart.Color);
hqChart.ChartPaint.push(chart);
}
this.CreateStraightLine = function (hqChart, windowIndex, varItem, id) {
let line = new ChartLine();
line.DrawType = 1;
line.Canvas = hqChart.Canvas;
line.Name = varItem.Name;
line.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
line.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
if (varItem.Color) line.Color = this.GetColor(varItem.Color);
else line.Color = this.GetDefaultColor(id);
if (varItem.LineWidth) {
let width = parseInt(varItem.LineWidth.replace("LINETHICK", ""));
if (!isNaN(width) && width > 0) line.LineWidth = width;
}
let titleIndex = windowIndex + 1;
line.Data.Data = varItem.Draw.DrawData;
//hqChart.TitlePaint[titleIndex].Data[id]=new DynamicTitleData(line.Data,varItem.Name,line.Color);
hqChart.ChartPaint.push(line);
}
this.CreateVolStick = function (hqChart, windowIndex, varItem, id, hisData) {
let chart = new ChartVolStick();
chart.Canvas = hqChart.Canvas;
chart.Name = varItem.Name;
chart.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chart.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
chart.KLineDrawType = hqChart.KLineDrawType; //设置K线显示类型
if (varItem.Color) chart.Color = this.GetColor(varItem.Color);
else chart.Color = this.GetDefaultColor(id);
let titleIndex = windowIndex + 1;
chart.Data.Data = varItem.Data;
chart.HistoryData = hisData;
hqChart.TitlePaint[titleIndex].Data[id] = new DynamicTitleData(chart.Data, varItem.Name, chart.Color);
hqChart.ChartPaint.push(chart);
}
this.CreateBand = function (hqChart, windowIndex, varItem, id) {
let chart = new ChartBand();
chart.Canvas = hqChart.Canvas;
chart.Name = varItem.Name;
chart.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chart.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
chart.FirstColor = varItem.Draw.Color[0];
chart.SecondColor = varItem.Draw.Color[1];
chart.Data.Data = varItem.Draw.DrawData;
hqChart.ChartPaint.push(chart);
}
this.CreatePolyLine = function (hqChart, windowIndex, varItem, id) {
let line = new ChartLine();
line.Canvas = hqChart.Canvas;
line.Name = varItem.Name;
line.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
line.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
if (varItem.Color) line.Color = this.GetColor(varItem.Color);
else line.Color = this.GetDefaultColor(id);
if (varItem.LineWidth) {
let width = parseInt(varItem.LineWidth.replace("LINETHICK", ""));
if (!isNaN(width) && width > 0) line.LineWidth = width;
}
let titleIndex = windowIndex + 1;
line.Data.Data = varItem.Draw.DrawData;
//hqChart.TitlePaint[titleIndex].Data[id] = new DynamicTitleData(line.Data, ' ', line.Color); //给一个空的标题
hqChart.ChartPaint.push(line);
}
//创建K线图
this.CreateKLine = function (hqChart, windowIndex, varItem, id)
{
let chart = new ChartKLine();
chart.Canvas = hqChart.Canvas;
chart.Name = varItem.Name;
chart.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chart.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
chart.Data.Data = varItem.Draw.DrawData;
chart.IsShowMaxMinPrice = false;
if (varItem.Color) //如果设置了颜色,使用外面设置的颜色
chart.UnchagneColor = chart.DownColor = chart.UpColor = this.GetColor(varItem.Color);
hqChart.ChartPaint.push(chart);
}
this.CreateDrawColorKLine=function(hqChart,windowIndex,varItem,i)
{
let chart=new ChartColorKline();
chart.Canvas=hqChart.Canvas;
chart.Name=varItem.Name;
chart.DrawName="DRAWCOLORKLINE";
chart.ChartBorder=hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chart.ChartFrame=hqChart.Frame.SubFrame[windowIndex].Frame;
chart.Data.Data=varItem.Draw.DrawData;
if (IFrameSplitOperator.IsBool(varItem.Draw.IsEmptyBar)) chart.IsEmptyBar=varItem.Draw.IsEmptyBar;
if (varItem.Draw.Color) chart.Color=varItem.Draw.Color;
hqChart.ChartPaint.push(chart);
}
this.CreateNumberText = function (hqChart, windowIndex, varItem, id) {
let chartText = new ChartSingleText();
chartText.Canvas = hqChart.Canvas;
chartText.Name = varItem.Name;
chartText.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chartText.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
chartText.ReloadResource();
chartText.TextAlign="center";
if (varItem.Color) chartText.Color = this.GetColor(varItem.Color);
else chartText.Color = this.GetDefaultColor(id);
if (varItem.IsDrawAbove) chartText.Direction=1;
else chartText.Direction=2;
let titleIndex = windowIndex + 1;
chartText.Data.Data = varItem.Draw.DrawData.Value;
chartText.Text = varItem.Draw.DrawData.Text;
//hqChart.TitlePaint[titleIndex].Data[id]=new DynamicTitleData(bar.Data,varItem.Name,bar.Color);
hqChart.ChartPaint.push(chartText);
}
this.CreateDrawIcon=function(hqChart, windowIndex, varItem, id, drawCallback)
{
var chart = new ChartDrawIcon();
chart.Canvas = hqChart.Canvas;
chart.TextAlign = 'center';
chart.Identify=id;
chart.DrawCallback=drawCallback;
chart.Name = varItem.Name;
chart.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chart.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
chart.Data.Data = varItem.Draw.DrawData;
chart.IconID=varItem.Draw.IconID;
if (varItem.Color) chart.Color = this.GetColor(varItem.Color);
else chart.Color = 'rgb(0,0,0)';
if (varItem.DrawVAlign>=0)
{
if (varItem.DrawVAlign==0) chart.TextBaseline="top";
else if (varItem.DrawVAlign==1) chart.TextBaseline="middle";
else if (varItem.DrawVAlign==2) chart.TextBaseline="bottom";
}
if (varItem.DrawAlign>=0)
{
if (varItem.DrawAlign==0) chart.TextAlign="left";
else if (varItem.DrawAlign==1) chart.TextAlign="center";
else if (varItem.DrawAlign==2) chart.TextAlign='right';
}
if (varItem.DrawFontSize>0) chart.FixedIconSize=varItem.DrawFontSize;
hqChart.ChartPaint.push(chart);
}
//创建图标
this.CreateIcon = function (hqChart, windowIndex, varItem, id)
{
var event=hqChart.GetEventCallback(JSCHART_EVENT_ID.ON_BIND_DRAWICON);
if (event && event.Callback)
{
var sendData={ FrameID:windowIndex, ID:id, Data:varItem, Callback:null };
event.Callback(event, sendData,this);
if (sendData.Callback)
{
this.CreateDrawIcon(hqChart, windowIndex, varItem, id, sendData.Callback);
return;
}
}
let chartText = new ChartSingleText();
chartText.Canvas = hqChart.Canvas;
chartText.TextAlign = 'center';
chartText.Name = varItem.Name;
chartText.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chartText.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
let titleIndex = windowIndex + 1;
chartText.Data.Data = varItem.Draw.DrawData;
chartText.Text = varItem.Draw.Icon.Symbol;
if (varItem.Color) chartText.Color = this.GetColor(varItem.Color);
else if (varItem.Draw.Icon.Color) chartText.Color = varItem.Draw.Icon.Color;
else chartText.Color = 'rgb(0,0,0)';
if (varItem.DrawVAlign>=0)
{
if (varItem.DrawVAlign==0) chartText.Direction=1;
else if (varItem.DrawVAlign==1) chartText.Direction=0;
else if (varItem.DrawVAlign==2) chartText.Direction=2;
}
if (varItem.DrawAlign>=0)
{
if (varItem.DrawAlign==0) chartText.TextAlign="left";
else if (varItem.DrawAlign==1) chartText.TextAlign="center";
else if (varItem.DrawAlign==2) chartText.TextAlign='right';
}
if (varItem.DrawFontSize>0) chartText.FixedFontSize=varItem.DrawFontSize;
//hqChart.TitlePaint[titleIndex].Data[id]=new DynamicTitleData(bar.Data,varItem.Name,bar.Color);
hqChart.ChartPaint.push(chartText);
}
this.CreateRectangle = function (hqChart, windowIndex, varItem, i)
{
let chart = new ChartRectangle();
chart.Canvas = hqChart.Canvas;
chart.Name = varItem.Name;
chart.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chart.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
chart.Color = [varItem.Draw.DrawData.Color];
chart.Rect = varItem.Draw.DrawData.Rect;
if (varItem.Color) chart.BorderColor = this.GetColor(varItem.Color);
hqChart.ChartPaint.push(chart);
}
this.CreateBackgroud=function(hqChart,windowIndex,varItem,id)
{
let chart=new ChartBackground();
chart.Canvas=hqChart.Canvas;
chart.Name=varItem.Name;
chart.ChartBorder=hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chart.ChartFrame=hqChart.Frame.SubFrame[windowIndex].Frame;
if (varItem.Draw && varItem.Draw.DrawData)
{
var drawData=varItem.Draw.DrawData;
chart.Color=drawData.Color;
chart.ColorAngle=drawData.Angle;
if (drawData.Data) chart.Data.Data=drawData.Data;
}
hqChart.ChartPaint.push(chart);
}
this.CreateMultiText = function (hqChart, windowIndex, varItem, i)
{
let chart = new ChartMultiText();
chart.Canvas = hqChart.Canvas;
chart.Name = varItem.Name;
chart.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chart.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
chart.Data = hqChart.ChartPaint[0].Data;//绑定K线
chart.Texts = varItem.Draw.DrawData;
hqChart.ChartPaint.push(chart);
}
this.CreateMulitHtmlDom=function(hqChart,windowIndex,varItem,i)
{
let chart=new ChartMultiHtmlDom();
chart.Canvas=hqChart.Canvas;
chart.Name=varItem.Name;
chart.ChartBorder=hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chart.ChartFrame=hqChart.Frame.SubFrame[windowIndex].Frame;
chart.Data=hqChart.ChartPaint[0].Data;//绑定K线
chart.Texts=varItem.Draw.DrawData;
chart.DrawCallback= varItem.Draw.Callback;
hqChart.ChartPaint.push(chart);
}
this.CreateMultiLine = function (hqChart, windowIndex, varItem, i)
{
let chart = new ChartMultiLine();
chart.Canvas = hqChart.Canvas;
chart.Name = varItem.Name;
chart.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chart.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
chart.Data = hqChart.ChartPaint[0].Data;//绑定K线
chart.Lines = varItem.Draw.DrawData;
if (varItem.Draw.LineDash) chart.LineDash=varItem.Draw.LineDash;
if (IFrameSplitOperator.IsNumber(varItem.Draw.LineWidth)) chart.LineWidth=varItem.Draw.LineWidth;
hqChart.ChartPaint.push(chart);
}
this.CreateMultiBar = function (hqChart, windowIndex, varItem, i)
{
let chart = new ChartMultiBar();
chart.Canvas = hqChart.Canvas;
chart.Name = varItem.Name;
chart.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chart.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
chart.Data = hqChart.ChartPaint[0].Data;//绑定K线
chart.Bars = varItem.Draw.DrawData;
hqChart.ChartPaint.push(chart);
}
//创建K线背景
this.CreateSelfKLine = function (hqChart, windowIndex, hisData)
{
let chart = new ChartKLine();
chart.Canvas = hqChart.Canvas;
chart.Name = "Self Kline"
chart.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
chart.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
chart.Data = hisData
chart.IsShowMaxMinPrice = false;
chart.IsShowKTooltip = false;
chart.DrawType = this.KLineType;
hqChart.ChartPaint.push(chart);
}
this.BindInstructionData = function (hqChart, windowIndex, hisData) //绑定指示指标
{
if (this.OutVar == null || this.OutVar.length < 0) return;
if (this.InstructionType == 2)
{
let varItem = this.OutVar[this.OutVar.length - 1]; //取最后一组数据作为指示数据
hqChart.SetInstructionData(this.InstructionType, { Data: varItem.Data }); //设置指示数据
return true;
}
else if (this.InstructionType == 1) //交易系统
{
var buyData, sellData;
for (var i in this.OutVar)
{
let item = this.OutVar[i];
if (item.Name == 'ENTERLONG') buyData = item.Data;
else if (item.Name == 'EXITLONG') sellData = item.Data;
}
hqChart.SetInstructionData(this.InstructionType, { Buy: buyData, Sell: sellData }); //设置指示数据
return true;
}
}
this.BindData = function (hqChart, windowIndex, hisData)
{
if (windowIndex == 0 && this.InstructionType)
{
this.BindInstructionData(hqChart, windowIndex, hisData);
return;
}
//清空指标图形
hqChart.DeleteIndexPaint(windowIndex);
if (windowIndex == 0) hqChart.ShowKLine(true);
if (this.OutVar == null || this.OutVar.length < 0) return;
//叠加一个K线背景
if (this.KLineType != null)
{
if (this.KLineType === 0 || this.KLineType === 1 || this.KLineType === 2) this.CreateSelfKLine(hqChart, windowIndex, hisData);
else if (this.KLineType === -1 && windowIndex == 0) hqChart.ShowKLine(false);
}
if (windowIndex >= 1 && hqChart.Frame)
{
hqChart.Frame.SubFrame[windowIndex].Frame.YSplitOperator.FloatPrecision = this.FloatPrecision;
if (this.YSpecificMaxMin) hqChart.Frame.SubFrame[windowIndex].Frame.YSpecificMaxMin = this.YSpecificMaxMin; //最大最小值
if (this.YSplitScale) hqChart.Frame.SubFrame[windowIndex].Frame.YSplitScale = this.YSplitScale; //固定刻度
}
for (var i=0 ;i<this.OutVar.length;++i )
{
let item = this.OutVar[i];
if (item.IsExData === true) continue; //扩展数据不显示图形
if (item.Type==1000 || item.Type==1001) continue; //数据集合, 字符串
if (item.Type == 0)
{
if (item.IsOverlayLine) this.CreateOverlayLine(hqChart, windowIndex, item, i);
else this.CreateLine(hqChart, windowIndex, item, i);
}
else if (item.Type == 1)
{
switch (item.Draw.DrawType)
{
case 'STICKLINE':
this.CreateBar(hqChart, windowIndex, item, i);
break;
case 'DRAWTEXT':
this.CreateDrawTextV2(hqChart, windowIndex, item, i);
break;
case 'SUPERDRAWTEXT':
case 'DRAWTEXT_FIX':
this.CreateText(hqChart, windowIndex, item, i);
break;
case 'DRAWLINE':
this.CreateStraightLine(hqChart, windowIndex, item, i);
break;
case 'DRAWBAND':
this.CreateBand(hqChart, windowIndex, item, i);
break;
case 'DRAWKLINE':
case "DRAWKLINE1":
this.CreateKLine(hqChart, windowIndex, item, i);
break;
case "DRAWCOLORKLINE":
this.CreateDrawColorKLine(hqChart,windowIndex,item,i);
break;
case 'DRAWKLINE_IF':
this.CreateKLine(hqChart, windowIndex, item, i);
break;
case 'POLYLINE':
this.CreatePolyLine(hqChart, windowIndex, item, i);
break;
case 'DRAWNUMBER':
this.CreateDrawNumber(hqChart, windowIndex, item, i);
break;
case 'DRAWICON':
this.CreateIcon(hqChart, windowIndex, item, i);
break;
case "ICON":
this.CreateIcon(hqChart,windowIndex,item,i);
break;
case 'DRAWRECTREL':
this.CreateRectangle(hqChart, windowIndex, item, i);
break;
case 'DRAWGBK':
case "DRAWGBK2":
this.CreateBackgroud(hqChart,windowIndex,item,i);
break;
//第3方指标定制
case 'MULTI_TEXT':
this.CreateMultiText(hqChart, windowIndex, item, i);
break;
case "MULTI_HTMLDOM":
this.CreateMulitHtmlDom(hqChart,windowIndex,item,i);
break;
case 'MULTI_LINE':
this.CreateMultiLine(hqChart, windowIndex, item, i);
break;
case 'MULTI_BAR':
this.CreateMultiBar(hqChart, windowIndex, item, i);
break;
case "KLINE_BG":
this.CreateBackgroud(hqChart,windowIndex,item,i);
break;
}
}
else if (item.Type == 2)
{
this.CreateMACD(hqChart, windowIndex, item, i);
}
else if (item.Type == 3)
{
this.CreatePointDot(hqChart, windowIndex, item, i);
}
else if (item.Type == 4)
{
this.CreateLineStick(hqChart, windowIndex, item, i);
}
else if (item.Type == 5)
{
this.CreateStick(hqChart, windowIndex, item, i);
}
else if (item.Type == 6)
{
this.CreateVolStick(hqChart, windowIndex, item, i, hisData);
}
var titlePaint = hqChart.TitlePaint[windowIndex + 1];
if (titlePaint && titlePaint.Data && i < titlePaint.Data.length) //设置标题数值 小数位数和格式
{
if (this.StringFormat > 0) titlePaint.Data[i].StringFormat = this.StringFormat;
if (this.FloatPrecision >= 0) titlePaint.Data[i].FloatPrecision = this.FloatPrecision;
if (this.OutName && this.OutName.length>0 && this.Arguments && this.Arguments.length>0)
{
titlePaint.SetDynamicOutName(this.OutName,this.Arguments);
}
}
}
let titleIndex = windowIndex + 1;
hqChart.TitlePaint[titleIndex].Title = this.Name;
let indexParam = '';
for (let i in this.Arguments)
{
let item = this.Arguments[i];
if (indexParam.length > 0) indexParam += ',';
indexParam += item.Value.toString();
}
if (indexParam.length > 0) hqChart.TitlePaint[titleIndex].Title = this.Name + '(' + indexParam + ')';
if (this.TitleFont) hqChart.TitlePaint[titleIndex].Font=this.TitleFont;
if (hqChart.UpdateUICallback) hqChart.UpdateUICallback('ScriptIndex', this.OutVar,
{ WindowIndex: windowIndex, Name: this.Name, Arguments: this.Arguments, HistoryData: hisData }); //通知上层回调
return true;
}
this.GetDefaultColor = function (id) //给一个默认的颜色
{
let COLOR_ARRAY = g_JSChartResource.ColorArray;
let number = parseInt(id);
return COLOR_ARRAY[number % (COLOR_ARRAY.length - 1)];
}
this.GetColor = function (colorName) //获取颜色
{
if (colorName.indexOf("RGB(")==0) return colorName.toLowerCase();
if (colorName.indexOf('rgb(')==0)return colorName;
if (colorName.indexOf("RGBA(")==0) return colorName.toLowerCase();
if (colorName.indexOf("rgba(")==0) return colorName;
var color=JSCommonComplier.JSComplier.ColorVarToRGB(colorName);
if (color) return color;
return 'rgb(30,144,255)';
/*
let COLOR_MAP = new Map([
['COLORBLACK', 'rgb(0,0,0)'],
['COLORBLUE', 'rgb(18,95,216)'],
['COLORGREEN', 'rgb(25,158,0)'],
['COLORCYAN', 'rgb(0,255,198)'],
['COLORRED', 'rgb(238,21,21)'],
['COLORMAGENTA', 'rgb(255,0,222)'],
['COLORBROWN', 'rgb(149,94,15)'],
['COLORLIGRAY', 'rgb(218,218,218)'], //画淡灰色
['COLORGRAY', 'rgb(133,133,133)'], //画深灰色
['COLORLIBLUE', 'rgb(94,204,255)'], //淡蓝色
['COLORLIGREEN', 'rgb(183,255,190)'], //淡绿色
['COLORLICYAN', 'rgb(154,255,242)'], //淡青色
['COLORLIRED', 'rgb(255,172,172)'], //淡红色
['COLORLIMAGENTA', 'rgb(255,145,241)'], //淡洋红色
['COLORWHITE', 'rgb(255,255,255)'], //白色
['COLORYELLOW', 'rgb(255,198,0)']
]);
if (COLOR_MAP.has(colorName)) return COLOR_MAP.get(colorName);
//COLOR 自定义色
//格式为COLOR+“RRGGBB”:RR、GG、BB表示红色、绿色和蓝色的分量,每种颜色的取值范围是00-FF,采用了16进制。
//例如:MA5:MA(CLOSE,5),COLOR00FFFF 表示纯红色与纯绿色的混合色:COLOR808000表示淡蓝色和淡绿色的混合色。
if (colorName.indexOf('COLOR') == 0) return '#' + colorName.substr(5);
return 'rgb(30,144,255)';
*/
}
}
var HQ_DATA_TYPE =
{
KLINE_ID: 0, //K线
MINUTE_ID: 2, //当日走势图
HISTORY_MINUTE_ID: 3,//历史分钟走势图
MULTIDAY_MINUTE_ID: 4,//多日走势图
};
function APIScriptIndex(name, script, args, option) //后台执行指标
{
this.newMethod = ScriptIndex; //派生
this.newMethod(name, script, args, option);
delete this.newMethod;
this.ApiUrl; //指标执行api地址
this.HQDataType;
if (option.API)
{
if (option.API.Url) this.ApiUrl = option.API.Url;
if (option.API.Name) this.Name = this.ID = option.API.Name;
if (option.API.ID) this.ID = option.API.ID;
}
this.ExecuteScript = function (hqChart, windowIndex, hisData)
{
JSConsole.Chart.Log('[APIScriptIndex::ExecuteScript] name, Arguments ', this.Name, this.Arguments);
//数据类型
let hqDataType = HQ_DATA_TYPE.KLINE_ID; //默认K线
var dateRange=null;
if (hqChart.ClassName === 'MinuteChartContainer' || hqChart.ClassName === 'MinuteChartHScreenContainer')
{
if (hqChart.DayCount > 1) hqDataType = HQ_DATA_TYPE.MULTIDAY_MINUTE_ID; //多日分钟
else hqDataType = HQ_DATA_TYPE.MINUTE_ID; //分钟数据
dateRange=hisData.GetDateRange();
}
else if (hqChart.ClassName === 'HistoryMinuteChartContainer')
{
hqDataType = HQ_DATA_TYPE.HISTORY_MINUTE_ID; //历史分钟
}
else
{
dateRange=hisData.GetDateRange();
}
var args = [];
if (this.Arguments)
{
for (var i in this.Arguments)
{
var item = this.Arguments[i];
args.push({ name: item.Name, value: item.Value });
}
}
var requestCount;
if (hqChart.GetRequestDataCount) requestCount= hqChart.GetRequestDataCount();
var self = this;
var postData =
{
indexname: this.ID, symbol: hqChart.Symbol, script: this.Script, args: args,
period: hqChart.Period, right: hqChart.Right, hqdatatype: hqDataType
};
if (dateRange) postData.DateRange=dateRange;
if (requestCount)
{
postData.maxdatacount=requestCount.MaxRequestDataCount;
postData.maxminutedaycount=requestCount.MaxRequestMinuteDayCount;
}
if (hqDataType == HQ_DATA_TYPE.MULTIDAY_MINUTE_ID || hqDataType == HQ_DATA_TYPE.MINUTE_ID) postData.daycount = hqChart.DayCount;
this.HQDataType = hqDataType;
if (hqChart.NetworkFilter)
{
var obj =
{
Name: 'APIScriptIndex::ExecuteScript', //类名::
Explain: '指标计算',
Request: { Url: self.ApiUrl, Type: 'POST', Data: postData },
Self: this,
HQChart: hqChart,
PreventDefault: false
};
hqChart.NetworkFilter(obj, function (data)
{
self.RecvAPIData(data, hqChart, windowIndex, hisData);
});
if (obj.PreventDefault == true) return; //已被上层替换,不调用默认的网络请求
}
wx.request({
url: self.ApiUrl,
data: postData,
method: 'POST',
dataType: "json",
async: true,
success: function (recvData)
{
self.RecvAPIData(recvData, hqChart, windowIndex, hisData);
},
error: function (request)
{
self.RecvError(request);
}
});
}
this.RecvAPIData = function (recvData, hqChart, windowIndex, hisData)
{
var data=recvData.data;
JSConsole.Chart.Log('[APIScriptIndex::RecvAPIData] recv data ', this.Name, data);
if (data.code != 0) return;
if (data.outdata && data.outdata.name) this.Name = data.outdata.name;
if (data.outdata.args) //外部修改显示参数
{
this.Arguments = [];
for (var i in data.outdata.args)
{
var item = data.outdata.args[i];
this.Arguments.push({ Name: item.name, Value: item.value });
}
}
if (this.HQDataType == HQ_DATA_TYPE.KLINE_ID)
{
this.OutVar = this.FittingData(data.outdata, hqChart);
JSConsole.Chart.Log('[APIScriptIndex::RecvAPIData] conver to OutVar ', this.OutVar);
}
else
{
this.OutVar = this.FittingMinuteData(data.outdata, hqChart); //走势图数据
}
this.BindData(hqChart, windowIndex, hisData);
if (this.IsLocked == false) //不上锁
{
hqChart.Frame.SubFrame[windowIndex].Frame.SetLock(null);
}
else //上锁
{
let lockData =
{
IsLocked: true, Callback: this.LockCallback, IndexName: this.Name, ID: this.LockID,
BG: this.LockBG, Text: this.LockText, TextColor: this.LockTextColor, Font: this.LockFont, Count: this.LockCount, MinWidth: this.LockMinWidth
};
hqChart.Frame.SubFrame[windowIndex].Frame.SetLock(lockData);
}
hqChart.UpdataDataoffset(); //更新数据偏移
hqChart.UpdateFrameMaxMin(); //调整坐标最大 最小值
hqChart.Draw();
if (hqChart.GetIndexEvent)
{
var event = hqChart.GetIndexEvent(); //指标计算完成回调
if (event)
{
var data =
{
OutVar: this.OutVar, WindowIndex: windowIndex, Name: this.Name, Arguments: this.Arguments, HistoryData: hisData,
Stock: { Symbol: hqChart.Symbol, Name: hqChart.Name }
};
event.Callback(event, data, this);
}
}
}
this.FittingData = function (jsonData, hqChart)
{
var outVar = jsonData.outvar;
var date = jsonData.date;
var time = jsonData.time;
var kdata = hqChart.ChartPaint[0].Data;
//把数据拟合到kdata上
var result = [];
for (var i in outVar)
{
var item = outVar[i];
var indexData = [];
var outVarItem = { Name: item.name, Type: item.type };
if (item.color) outVarItem.Color = item.color;
if (item.data)
{
outVarItem.Data = this.FittingArray(item.data, date, time, hqChart);
if (item.color) outVarItem.Color = item.color;
if (item.linewidth >= 1) outVarItem.LineWidth = item.linewidth;
if (item.isshow == false) outVarItem.IsShow = false;
if (item.isexdata == true) outVarItem.IsExData = true;
result.push(outVarItem);
}
else if (item.Draw)
{
var draw = item.Draw;
var drawItem = {};
if (draw.DrawType == 'DRAWICON') //图标
{
drawItem.Icon = draw.Icon;
//小程序不支持svg, 只能转文字
if (IFrameSplitOperator.IsNumber(draw.IconType))
drawItem.Icon=JSCommonComplier.g_JSComplierResource.GetDrawTextIcon(draw.IconType);
drawItem.Name = draw.Name;
drawItem.DrawType = draw.DrawType;
drawItem.DrawData = this.FittingArray(draw.DrawData, date, time, hqChart);
outVarItem.Draw = drawItem;
result.push(outVarItem);
}
else if (draw.DrawType == 'DRAWTEXT') //文本
{
drawItem.Text = draw.Text;
drawItem.Name = draw.Name;
drawItem.DrawType = draw.DrawType;
drawItem.DrawData = this.FittingArray(draw.DrawData, date, time, hqChart);
outVarItem.Draw = drawItem;
result.push(outVarItem);
}
else if (draw.DrawType == 'STICKLINE') //柱子
{
drawItem.Name = draw.Name;
drawItem.Type = draw.Type;
drawItem.Width = draw.Width;
drawItem.DrawType = draw.DrawType;
drawItem.DrawData = this.FittingArray(draw.DrawData, date, time, hqChart, 1);
outVarItem.Draw = drawItem;
result.push(outVarItem);
}
else if (draw.DrawType == 'MULTI_LINE')
{
drawItem.Text = draw.Text;
drawItem.Name = draw.Name;
drawItem.DrawType = draw.DrawType;
drawItem.DrawData = this.FittingMultiLine(draw.DrawData, date, time, hqChart);
outVarItem.Draw = drawItem;
if (draw.LineDash) drawItem.LineDash=draw.LineDash;
//if (draw.Arrow) drawItem.Arrow=draw.Arrow;
if (IFrameSplitOperator.IsNumber(draw.LineWidth)) drawItem.LineWidth=draw.LineWidth;
result.push(outVarItem);
}
else if (draw.DrawType == 'MULTI_BAR')
{
drawItem.Text = draw.Text;
drawItem.Name = draw.Name;
drawItem.DrawType = draw.DrawType;
drawItem.DrawData = this.FittingMultiLine(draw.DrawData, date, time, hqChart);
outVarItem.Draw = drawItem;
result.push(outVarItem);
}
else if (draw.DrawType == 'MULTI_TEXT')
{
drawItem.Text = draw.Text;
drawItem.Name = draw.Name;
drawItem.DrawType = draw.DrawType;
drawItem.DrawData = this.FittingMultiText(draw.DrawData, date, time, hqChart);
this.GetKLineData(drawItem.DrawData, hqChart);
outVarItem.Draw = drawItem;
result.push(outVarItem);
}
else if (draw.DrawType=="MULTI_HTMLDOM") //外部自己创建dom
{
drawItem.Text=draw.Text;
drawItem.Name=draw.Name;
drawItem.DrawType=draw.DrawType;
drawItem.Callback=draw.Callback;
drawItem.DrawData=this.FittingMultiText(draw.DrawData,date,time,hqChart);
this.GetKLineData(drawItem.DrawData, hqChart);
outVarItem.Draw=drawItem;
result.push(outVarItem);
}
else if (draw.DrawType=="KLINE_BG")
{
drawItem.Name=draw.Name;
drawItem.DrawType=draw.DrawType;
drawItem.DrawData={ Color:draw.Color, Angle:draw.Angle };
drawItem.DrawData.Data=this.FittingKLineBG(draw.DrawData, hqChart);
outVarItem.Draw=drawItem;
outVarItem.Name=draw.DrawType;
result.push(outVarItem);
}
}
}
return result;
}
// h, high, low l.
this.GetKLineData=function(data,hqChart)
{
if (!data) return;
if (!Array.isArray(data)) return;
var kData=hqChart.ChartPaint[0].Data; //K线
for(var i in data)
{
var item=data[i];
if (!IFrameSplitOperator.IsString(item.Value)) continue;
if(!IFrameSplitOperator.IsNumber(item.Index)) continue;
if (item.Index<0 || item.Index>=kData.Data.length) continue;
var valueName=item.Value.toUpperCase();
var kItem=kData.Data[item.Index];
switch(valueName)
{
case "HIGH":
case "H":
item.Value=kItem.High;
break;
case "L":
case "LOW":
item.Value=kItem.Low;
break;
}
}
}
this.FittingKLineBG=function(data, hqChart)
{
var kData=hqChart.ChartPaint[0].Data; //K线
var result=[];
if (ChartData.IsDayPeriod(hqChart.Period,true)) //日线
{
var bFill=false;
for(var i=0,j=0;i<kData.Data.length;)
{
result[i]=0;
var kItem=kData.Data[i];
if (j>=data.length)
{
++i;
continue;
}
var dataItem=data[j];
if (dataItem.Date<kItem.Date)
{
++j;
}
else if (dataItem.Date>kItem.Date)
{
++i;
}
else
{
bFill=true;
result[i]=1;
++j;
++i;
}
}
if (bFill) return result;
}
else if (ChartData.IsMinutePeriod(hqChart.Period,true)) //分钟线
{
var bFill=false;
for(var i=0,j=0;i<kData.Data.length;)
{
result[i]=0;
var kItem=kData.Data[i];
if (j>=data.length)
{
++i;
continue;
}
var dataItem=data[j];
if (dataItem.Date<kItem.Date || (dataItem.Date==kItem.Date && dataItem.Time<kItem.Time))
{
++j;
}
else if (dataItem.Date>kItem.Date || (dataItem.Date==kItem.Date && dataItem.Time>kItem.Time))
{
++i;
}
else
{
bFill=true;
result[i]=1;
++j;
++i;
}
}
if (bFill) return result;
}
return null;
}
this.FittingArray = function (sourceData, date, time, hqChart, arrayType) //arrayType 0=单值数组 1=结构体
{
var kdata = hqChart.ChartPaint[0].Data; //K线
var arySingleData = [];
for (var i in sourceData)
{
var value = sourceData[i];
var indexItem = new SingleData(); //单列指标数据
indexItem.Date = date[i];
if (time && i < time.length) indexItem.Time = time[i];
indexItem.Value = value;
arySingleData.push(indexItem);
}
var aryFittingData;
if (ChartData.IsDayPeriod(hqChart.Period,true))
aryFittingData = kdata.GetFittingData(arySingleData); //数据和主图K线拟合
else
aryFittingData = kdata.GetMinuteFittingData(arySingleData); //数据和主图K线拟合
var bindData = new ChartData();
bindData.Data = aryFittingData;
var result;
if (arrayType == 1) result = bindData.GetObject();
else result = bindData.GetValue();
return result;
}
this.FittingMultiLine = function (sourceData, date, time, hqChart)
{
var kdata = hqChart.ChartPaint[0].Data; //K线
if (ChartData.IsDayPeriod(hqChart.Period, true)) //日线
{
var aryPoint = [];
for (var i in sourceData)
{
var item = sourceData[i];
for (var j in item.Point)
{
var point = item.Point[j];
aryPoint.push(point);
}
}
aryPoint.sort(function (a, b) { return a.Date - b.Date; });
kdata.GetDateIndex(aryPoint);
return sourceData;
}
else if (ChartData.IsMinutePeriod(hqChart.Period, true)) //分钟线
{
var aryPoint = [];
for (var i in sourceData)
{
var item = sourceData[i];
for (var j in item.Point)
{
var point = item.Point[j];
aryPoint.push(point);
}
}
aryPoint.sort(function (a, b) {
if (a.Date == b.Date) return a.Time - b.Time;
return a.Date - b.Date;
});
kdata.GetDateTimeIndex(aryPoint);
return sourceData;
}
return null;
}
this.FittingMultiText = function (sourceData, date, time, hqChart)
{
var kdata = hqChart.ChartPaint[0].Data; //K线
if (ChartData.IsDayPeriod(hqChart.Period, true)) //日线
{
sourceData.sort(function (a, b) { return a.Date - b.Date; });
kdata.GetDateIndex(sourceData);
return sourceData;
}
else if (ChartData.IsMinutePeriod(hqChart.Period, true)) //分钟线
{
sourceData.sort(function (a, b) {
if (a.Date == b.Date) return a.Time - b.Time;
return a.Date - b.Date;
}
);
kdata.GetDateTimeIndex(sourceData);
return sourceData;
}
return null;
}
this.FittingMinuteData=function(jsonData, hqChart)
{
var outVar=jsonData.outvar;
var date=jsonData.date;
var time=jsonData.time;
var result=[];
for(var i in outVar)
{
var item=outVar[i];
var outVarItem={Name:item.name,Type:item.type}
if (item.data)
{
outVarItem.Data=this.FittingMinuteArray(item.data,date,time,hqChart);
if (item.color) outVarItem.Color=item.color;
if (item.linewidth>=1) outVarItem.LineWidth=item.linewidth;
if (item.isshow==false) outVarItem.IsShow = false;
if (item.isexdata==true) outVarItem.IsExData = true;
result.push(outVarItem);
}
else if (item.Draw)
{
var draw=item.Draw;
var drawItem={};
if (draw.DrawType=='DRAWICON') //图标
{
drawItem.Icon=draw.Icon;
drawItem.Name=draw.Name;
drawItem.DrawType=draw.DrawType;
drawItem.DrawData=this.FittingMinuteArray(draw.DrawData,date,time,hqChart);
outVarItem.Draw=drawItem;
result.push(outVarItem);
}
else if (draw.DrawType=='DRAWTEXT') //文本
{
drawItem.Text=draw.Text;
drawItem.Name=draw.Name;
drawItem.DrawType=draw.DrawType;
drawItem.DrawData=this.FittingMinuteArray(draw.DrawData,date,time,hqChart);
outVarItem.Draw=drawItem;
result.push(outVarItem);
}
else if (draw.DrawType=='STICKLINE') //柱子
{
drawItem.Name=draw.Name;
drawItem.Type=draw.Type;
drawItem.Width=draw.Width;
drawItem.DrawType=draw.DrawType;
drawItem.DrawData=this.FittingMinuteArray(draw.DrawData,date,time,hqChart,1);
outVarItem.Draw=drawItem;
result.push(outVarItem);
}
else if (draw.DrawType=='MULTI_LINE')
{
drawItem.Text=draw.Text;
drawItem.Name=draw.Name;
drawItem.DrawType=draw.DrawType;
drawItem.DrawData=this.FittingMultiLine(draw.DrawData,date,time,hqChart);
for(var k in drawItem.DrawData)
{
this.GetKLineData(drawItem.DrawData[k].Point, hqChart);
}
outVarItem.Draw=drawItem;
if (draw.LineDash) drawItem.LineDash=draw.LineDash;
if (draw.Arrow) drawItem.Arrow=draw.Arrow;
result.push(outVarItem);
}
else if (draw.DrawType=='MULTI_TEXT')
{
drawItem.Text=draw.Text;
drawItem.Name=draw.Name;
drawItem.DrawType=draw.DrawType;
drawItem.DrawData=this.FittingMultiText(draw.DrawData,date,time,hqChart);
this.GetKLineData(drawItem.DrawData, hqChart);
outVarItem.Draw=drawItem;
result.push(outVarItem);
}
else if (draw.DrawType=='MULTI_SVGICON')
{
drawItem.Text=draw.Text;
drawItem.Name=draw.Name;
drawItem.DrawType=draw.DrawType;
drawItem.DrawData={ Icon:this.FittingMultiText(draw.DrawData.Icon,date,time,hqChart), Family:draw.DrawData.Family };
this.GetKLineData(drawItem.DrawData.Icon, hqChart);
outVarItem.Draw=drawItem;
result.push(outVarItem);
}
else if (draw.DrawType=="MULTI_HTMLDOM") //外部自己创建dom
{
drawItem.Text=draw.Text;
drawItem.Name=draw.Name;
drawItem.DrawType=draw.DrawType;
drawItem.Callback=draw.Callback;
drawItem.DrawData=this.FittingMultiText(draw.DrawData,date,time,hqChart);
this.GetKLineData(drawItem.DrawData, hqChart);
outVarItem.Draw=drawItem;
result.push(outVarItem);
}
}
}
return result;
}
this.FittingMinuteArray=function(sourceData,date,time,hqChart)
{
var minutedata=hqChart.SourceData;; //分钟线
var arySingleData=[];
for(var i in sourceData)
{
var value=sourceData[i];
var indexItem=new SingleData(); //单列指标数据
indexItem.Date=date[i];
if (time && i<time.length) indexItem.Time=time[i];
indexItem.Value=value;
arySingleData.push(indexItem);
}
var aryFittingData=minutedata.GetMinuteFittingData(arySingleData); //数据和主图K线拟合
var bindData=new ChartData();
bindData.Data=aryFittingData;
var result=bindData.GetValue();
return result;
}
}
//市场多空
function MarketLongShortIndex()
{
this.newMethod = BaseIndex; //派生
this.newMethod('市场多空');
delete this.newMethod;
this.Index = new Array(
new IndexInfo("多空指标", null),
new IndexInfo("多头区域", null),
new IndexInfo("空头区域", null)
);
this.Index[0].LineColor = g_JSChartResource.Index.LineColor[0];
this.Index[1].LineColor = g_JSChartResource.UpBarColor;
this.Index[2].LineColor = g_JSChartResource.DownBarColor;
this.LongShortData; //多空数据
this.Create = function (hqChart, windowIndex) {
for (var i in this.Index) {
var paint = null;
if (i == 0)
paint = new ChartLine();
else
paint = new ChartStraightLine();
paint.Color = this.Index[i].LineColor;
paint.Canvas = hqChart.Canvas;
paint.Name = this.Name + "-" + i.toString();
paint.ChartBorder = hqChart.Frame.SubFrame[windowIndex].Frame.ChartBorder;
paint.ChartFrame = hqChart.Frame.SubFrame[windowIndex].Frame;
hqChart.ChartPaint.push(paint);
}
}
//请求数据
this.RequestData = function (hqChart, windowIndex, hisData) {
var self = this;
var param =
{
HQChart: hqChart,
WindowIndex: windowIndex,
HistoryData: hisData
};
this.LongShortData = [];
if (param.HQChart.Period > 0) //周期数据
{
this.NotSupport(param.HQChart, param.WindowIndex, "不支持周期切换");
param.HQChart.Draw();
return false;
}
//请求数据
wx.request({
url: g_JSChartResource.Index.MarketLongShortApiUrl,
data:
{
},
method: 'POST',
dataType: "json",
async: true,
success: function (recvData) {
self.RecvData(recvData, param);
}
});
return true;
}
this.RecvData = function (recvData, param) {
if (recvData.data.data.length <= 0) return;
var aryData = new Array();
for (var i in recvData.data.data) {
var item = recvData.data.data[i];
var indexData = new SingleData();
indexData.Date = item[0];
indexData.Value = item[1];
aryData.push(indexData);
}
var aryFittingData = param.HistoryData.GetFittingData(aryData);
var bindData = new ChartData();
bindData.Data = aryFittingData;
bindData.Period = param.HQChart.Period; //周期
bindData.Right = param.HQChart.Right; //复权
this.LongShortData = bindData.GetValue();
this.BindData(param.HQChart, param.WindowIndex, param.HistoryData);
param.HQChart.UpdataDataoffset(); //更新数据偏移
param.HQChart.UpdateFrameMaxMin(); //调整坐标最大 最小值
param.HQChart.Draw();
}
this.BindData = function (hqChart, windowIndex, hisData) {
var paint = hqChart.GetChartPaint(windowIndex);
if (paint.length != this.Index.length) return false;
//paint[0].Data.Data=SWLData;
paint[0].Data.Data = this.LongShortData;
paint[0].NotSupportMessage = null;
paint[1].Data.Data[0] = 8;
paint[2].Data.Data[0] = 1;
//指定[0,9]
hqChart.Frame.SubFrame[windowIndex].Frame.YSpecificMaxMin = { Max: 9, Min: 0, Count: 3 };
var titleIndex = windowIndex + 1;
for (var i in paint) {
hqChart.TitlePaint[titleIndex].Data[i] = new DynamicTitleData(paint[i].Data, this.Index[i].Name, this.Index[i].LineColor);
if (i > 0) hqChart.TitlePaint[titleIndex].Data[i].DataType = "StraightLine";
}
hqChart.TitlePaint[titleIndex].Title = this.FormatIndexTitle();
if (hqChart.UpdateUICallback) hqChart.UpdateUICallback('MarketLongShortIndex', paint, { WindowIndex: windowIndex, HistoryData: hisData }); //通知上层回调
return true;
}
}
module.exports =
{
JSCommonIndex:
{
IndexInfo: IndexInfo,
BaseIndex: BaseIndex,
ScriptIndex:ScriptIndex,
APIScriptIndex:APIScriptIndex,
},
//单个类导出
JSCommonIndex_IndexInfo: IndexInfo,
JSCommonIndex_BaseIndex: BaseIndex,
JSCommonIndex_ScriptIndex:ScriptIndex,
JSCommonIndex_APIScriptIndex:APIScriptIndex,
};
|
/*
* Copyright (c) 2020 aureliancnx
*
* MIT LICENSE
*
* This project is part of aureliancnx.
* See https://github.com/aureliancnx/Bubulle-Norminette for further info.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE. */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.moment=t()}(this,function(){"use strict";var e,i;function c(){return e.apply(null,arguments)}function o(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function u(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function r(e){return void 0===e}function l(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function a(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function d(e,t){for(var n=[],s=0;s<e.length;++s)n.push(t(e[s],s));return n}function f(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function h(e,t){for(var n in t)f(t,n)&&(e[n]=t[n]);return f(t,"toString")&&(e.toString=t.toString),f(t,"valueOf")&&(e.valueOf=t.valueOf),e}function m(e,t,n,s){return Ot(e,t,n,s,!0).utc()}function _(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf}function y(e){if(null==e._isValid){var t=_(e),n=i.call(t.parsedDateParts,function(e){return null!=e}),s=!isNaN(e._d.getTime())&&t.overflow<0&&!t.empty&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&n);if(e._strict&&(s=s&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour),null!=Object.isFrozen&&Object.isFrozen(e))return s;e._isValid=s}return e._isValid}function g(e){var t=m(NaN);return null!=e?h(_(t),e):_(t).userInvalidated=!0,t}i=Array.prototype.some?Array.prototype.some:function(e){for(var t=Object(this),n=t.length>>>0,s=0;s<n;s++)if(s in t&&e.call(this,t[s],s,t))return!0;return!1};var p=c.momentProperties=[];function v(e,t){var n,s,i;if(r(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),r(t._i)||(e._i=t._i),r(t._f)||(e._f=t._f),r(t._l)||(e._l=t._l),r(t._strict)||(e._strict=t._strict),r(t._tzm)||(e._tzm=t._tzm),r(t._isUTC)||(e._isUTC=t._isUTC),r(t._offset)||(e._offset=t._offset),r(t._pf)||(e._pf=_(t)),r(t._locale)||(e._locale=t._locale),0<p.length)for(n=0;n<p.length;n++)r(i=t[s=p[n]])||(e[s]=i);return e}var t=!1;function w(e){v(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===t&&(t=!0,c.updateOffset(this),t=!1)}function M(e){return e instanceof w||null!=e&&null!=e._isAMomentObject}function k(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function S(e){var t=+e,n=0;return 0!=t&&isFinite(t)&&(n=k(t)),n}function D(e,t,n){for(var s=Math.min(e.length,t.length),i=Math.abs(e.length-t.length),r=0,a=0;a<s;a++)(n&&e[a]!==t[a]||!n&&S(e[a])!==S(t[a]))&&r++;return r+i}function Y(e){!1===c.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function n(i,r){var a=!0;return h(function(){if(null!=c.deprecationHandler&&c.deprecationHandler(null,i),a){for(var e,t=[],n=0;n<arguments.length;n++){if(e="","object"==typeof arguments[n]){for(var s in e+="\n["+n+"] ",arguments[0])e+=s+": "+arguments[0][s]+", ";e=e.slice(0,-2)}else e=arguments[n];t.push(e)}Y(i+"\nArguments: "+Array.prototype.slice.call(t).join("")+"\n"+(new Error).stack),a=!1}return r.apply(this,arguments)},r)}var s,O={};function x(e,t){null!=c.deprecationHandler&&c.deprecationHandler(e,t),O[e]||(Y(t),O[e]=!0)}function T(e){return e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function b(e,t){var n,s=h({},e);for(n in t)f(t,n)&&(u(e[n])&&u(t[n])?(s[n]={},h(s[n],e[n]),h(s[n],t[n])):null!=t[n]?s[n]=t[n]:delete s[n]);for(n in e)f(e,n)&&!f(t,n)&&u(e[n])&&(s[n]=h({},s[n]));return s}function P(e){null!=e&&this.set(e)}c.suppressDeprecationWarnings=!1,c.deprecationHandler=null,s=Object.keys?Object.keys:function(e){var t,n=[];for(t in e)f(e,t)&&n.push(t);return n};var W={};function R(e,t){var n=e.toLowerCase();W[n]=W[n+"s"]=W[t]=e}function C(e){return"string"==typeof e?W[e]||W[e.toLowerCase()]:void 0}function F(e){var t,n,s={};for(n in e)f(e,n)&&(t=C(n))&&(s[t]=e[n]);return s}var U={};function N(e,t){U[e]=t}function H(e,t,n){var s=""+Math.abs(e),i=t-s.length;return(0<=e?n?"+":"":"-")+Math.pow(10,Math.max(0,i)).toString().substr(1)+s}var L=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,G=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,V={},j={};function I(e,t,n,s){var i="string"==typeof s?function(){return this[s]()}:s;e&&(j[e]=i),t&&(j[t[0]]=function(){return H(i.apply(this,arguments),t[1],t[2])}),n&&(j[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function E(e,t){return e.isValid()?(t=A(t,e.localeData()),V[t]=V[t]||function(s){for(var e,i=s.match(L),t=0,r=i.length;t<r;t++)j[i[t]]?i[t]=j[i[t]]:i[t]=(e=i[t]).match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"");return function(e){for(var t="",n=0;n<r;n++)t+=T(i[n])?i[n].call(e,s):i[n];return t}}(t),V[t](e)):e.localeData().invalidDate()}function A(e,t){var n=5;function s(e){return t.longDateFormat(e)||e}for(G.lastIndex=0;0<=n&&G.test(e);)e=e.replace(G,s),G.lastIndex=0,--n;return e}var z=/\d/,Z=/\d\d/,$=/\d{3}/,q=/\d{4}/,J=/[+-]?\d{6}/,B=/\d\d?/,Q=/\d\d\d\d?/,X=/\d\d\d\d\d\d?/,K=/\d{1,3}/,ee=/\d{1,4}/,te=/[+-]?\d{1,6}/,ne=/\d+/,se=/[+-]?\d+/,ie=/Z|[+-]\d\d:?\d\d/gi,re=/Z|[+-]\d\d(?::?\d\d)?/gi,ae=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,oe={};function ue(e,n,s){oe[e]=T(n)?n:function(e,t){return e&&s?s:n}}function le(e,t){return f(oe,e)?oe[e](t._strict,t._locale):new RegExp(de(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,s,i){return t||n||s||i})))}function de(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var he={};function ce(e,n){var t,s=n;for("string"==typeof e&&(e=[e]),l(n)&&(s=function(e,t){t[n]=S(e)}),t=0;t<e.length;t++)he[e[t]]=s}function fe(e,i){ce(e,function(e,t,n,s){n._w=n._w||{},i(e,n._w,n,s)})}var me=0,_e=1,ye=2,ge=3,pe=4,ve=5,we=6,Me=7,ke=8;function Se(e){return De(e)?366:365}function De(e){return e%4==0&&e%100!=0||e%400==0}I("Y",0,0,function(){var e=this.year();return e<=9999?""+e:"+"+e}),I(0,["YY",2],0,function(){return this.year()%100}),I(0,["YYYY",4],0,"year"),I(0,["YYYYY",5],0,"year"),I(0,["YYYYYY",6,!0],0,"year"),R("year","y"),N("year",1),ue("Y",se),ue("YY",B,Z),ue("YYYY",ee,q),ue("YYYYY",te,J),ue("YYYYYY",te,J),ce(["YYYYY","YYYYYY"],me),ce("YYYY",function(e,t){t[me]=2===e.length?c.parseTwoDigitYear(e):S(e)}),ce("YY",function(e,t){t[me]=c.parseTwoDigitYear(e)}),ce("Y",function(e,t){t[me]=parseInt(e,10)}),c.parseTwoDigitYear=function(e){return S(e)+(68<S(e)?1900:2e3)};var Ye,Oe=xe("FullYear",!0);function xe(t,n){return function(e){return null!=e?(be(this,t,e),c.updateOffset(this,n),this):Te(this,t)}}function Te(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function be(e,t,n){e.isValid()&&!isNaN(n)&&("FullYear"===t&&De(e.year())?e._d["set"+(e._isUTC?"UTC":"")+t](n,e.month(),Pe(n,e.month())):e._d["set"+(e._isUTC?"UTC":"")+t](n))}function Pe(e,t){if(isNaN(e)||isNaN(t))return NaN;var n,s=(t%(n=12)+n)%n;return e+=(t-s)/12,1==s?De(e)?29:28:31-s%7%2}Ye=Array.prototype.indexOf?Array.prototype.indexOf:function(e){for(var t=0;t<this.length;++t)if(this[t]===e)return t;return-1},I("M",["MM",2],"Mo",function(){return this.month()+1}),I("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)}),I("MMMM",0,0,function(e){return this.localeData().months(this,e)}),R("month","M"),N("month",8),ue("M",B),ue("MM",B,Z),ue("MMM",function(e,t){return t.monthsShortRegex(e)}),ue("MMMM",function(e,t){return t.monthsRegex(e)}),ce(["M","MM"],function(e,t){t[_e]=S(e)-1}),ce(["MMM","MMMM"],function(e,t,n,s){var i=n._locale.monthsParse(e,s,n._strict);null!=i?t[_e]=i:_(n).invalidMonth=e});var We=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Re="January_February_March_April_May_June_July_August_September_October_November_December".split("_");var Ce="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_");function Fe(e,t){var n;if(!e.isValid())return e;if("string"==typeof t)if(/^\d+$/.test(t))t=S(t);else if(!l(t=e.localeData().monthsParse(t)))return e;return n=Math.min(e.date(),Pe(e.year(),t)),e._d["set"+(e._isUTC?"UTC":"")+"Month"](t,n),e}function Ue(e){return null!=e?(Fe(this,e),c.updateOffset(this,!0),this):Te(this,"Month")}var Ne=ae;var He=ae;function Le(){function e(e,t){return t.length-e.length}for(var t,n=[],s=[],i=[],r=0;r<12;r++)t=m([2e3,r]),n.push(this.monthsShort(t,"")),s.push(this.months(t,"")),i.push(this.months(t,"")),i.push(this.monthsShort(t,""));for(n.sort(e),s.sort(e),i.sort(e),r=0;r<12;r++)n[r]=de(n[r]),s[r]=de(s[r]);for(r=0;r<24;r++)i[r]=de(i[r]);this._monthsRegex=new RegExp("^("+i.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+s.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+n.join("|")+")","i")}function Ge(e){var t=new Date(Date.UTC.apply(null,arguments));return e<100&&0<=e&&isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e),t}function Ve(e,t,n){var s=7+t-n;return s-(7+Ge(e,0,s).getUTCDay()-t)%7-1}function je(e,t,n,s,i){var r,a=1+7*(t-1)+(7+n-s)%7+Ve(e,s,i),o=a<=0?Se(r=e-1)+a:a>Se(e)?(r=e+1,a-Se(e)):(r=e,a);return{year:r,dayOfYear:o}}function Ie(e,t,n){var s,i,r=Ve(e.year(),t,n),a=Math.floor((e.dayOfYear()-r-1)/7)+1;return a<1?s=a+Ee(i=e.year()-1,t,n):a>Ee(e.year(),t,n)?(s=a-Ee(e.year(),t,n),i=e.year()+1):(i=e.year(),s=a),{week:s,year:i}}function Ee(e,t,n){var s=Ve(e,t,n),i=Ve(e+1,t,n);return(Se(e)-s+i)/7}I("w",["ww",2],"wo","week"),I("W",["WW",2],"Wo","isoWeek"),R("week","w"),R("isoWeek","W"),N("week",5),N("isoWeek",5),ue("w",B),ue("ww",B,Z),ue("W",B),ue("WW",B,Z),fe(["w","ww","W","WW"],function(e,t,n,s){t[s.substr(0,1)]=S(e)});I("d",0,"do","day"),I("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),I("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),I("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),I("e",0,0,"weekday"),I("E",0,0,"isoWeekday"),R("day","d"),R("weekday","e"),R("isoWeekday","E"),N("day",11),N("weekday",11),N("isoWeekday",11),ue("d",B),ue("e",B),ue("E",B),ue("dd",function(e,t){return t.weekdaysMinRegex(e)}),ue("ddd",function(e,t){return t.weekdaysShortRegex(e)}),ue("dddd",function(e,t){return t.weekdaysRegex(e)}),fe(["dd","ddd","dddd"],function(e,t,n,s){var i=n._locale.weekdaysParse(e,s,n._strict);null!=i?t.d=i:_(n).invalidWeekday=e}),fe(["d","e","E"],function(e,t,n,s){t[s]=S(e)});var Ae="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_");var ze="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_");var Ze="Su_Mo_Tu_We_Th_Fr_Sa".split("_");var $e=ae;var qe=ae;var Je=ae;function Be(){function e(e,t){return t.length-e.length}for(var t,n,s,i,r=[],a=[],o=[],u=[],l=0;l<7;l++)t=m([2e3,1]).day(l),n=this.weekdaysMin(t,""),s=this.weekdaysShort(t,""),i=this.weekdays(t,""),r.push(n),a.push(s),o.push(i),u.push(n),u.push(s),u.push(i);for(r.sort(e),a.sort(e),o.sort(e),u.sort(e),l=0;l<7;l++)a[l]=de(a[l]),o[l]=de(o[l]),u[l]=de(u[l]);this._weekdaysRegex=new RegExp("^("+u.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+o.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+r.join("|")+")","i")}function Qe(){return this.hours()%12||12}function Xe(e,t){I(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function Ke(e,t){return t._meridiemParse}I("H",["HH",2],0,"hour"),I("h",["hh",2],0,Qe),I("k",["kk",2],0,function(){return this.hours()||24}),I("hmm",0,0,function(){return""+Qe.apply(this)+H(this.minutes(),2)}),I("hmmss",0,0,function(){return""+Qe.apply(this)+H(this.minutes(),2)+H(this.seconds(),2)}),I("Hmm",0,0,function(){return""+this.hours()+H(this.minutes(),2)}),I("Hmmss",0,0,function(){return""+this.hours()+H(this.minutes(),2)+H(this.seconds(),2)}),Xe("a",!0),Xe("A",!1),R("hour","h"),N("hour",13),ue("a",Ke),ue("A",Ke),ue("H",B),ue("h",B),ue("k",B),ue("HH",B,Z),ue("hh",B,Z),ue("kk",B,Z),ue("hmm",Q),ue("hmmss",X),ue("Hmm",Q),ue("Hmmss",X),ce(["H","HH"],ge),ce(["k","kk"],function(e,t,n){var s=S(e);t[ge]=24===s?0:s}),ce(["a","A"],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),ce(["h","hh"],function(e,t,n){t[ge]=S(e),_(n).bigHour=!0}),ce("hmm",function(e,t,n){var s=e.length-2;t[ge]=S(e.substr(0,s)),t[pe]=S(e.substr(s)),_(n).bigHour=!0}),ce("hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[ge]=S(e.substr(0,s)),t[pe]=S(e.substr(s,2)),t[ve]=S(e.substr(i)),_(n).bigHour=!0}),ce("Hmm",function(e,t,n){var s=e.length-2;t[ge]=S(e.substr(0,s)),t[pe]=S(e.substr(s))}),ce("Hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[ge]=S(e.substr(0,s)),t[pe]=S(e.substr(s,2)),t[ve]=S(e.substr(i))});var et,tt=xe("Hours",!0),nt={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:Re,monthsShort:Ce,week:{dow:0,doy:6},weekdays:Ae,weekdaysMin:Ze,weekdaysShort:ze,meridiemParse:/[ap]\.?m?\.?/i},st={},it={};function rt(e){return e?e.toLowerCase().replace("_","-"):e}function at(e){var t=null;if(!st[e]&&"undefined"!=typeof module&&module&&module.exports)try{t=et._abbr;require("./locale/"+e),ot(t)}catch(e){}return st[e]}function ot(e,t){var n;return e&&(n=r(t)?lt(e):ut(e,t))&&(et=n),et._abbr}function ut(e,t){if(null===t)return delete st[e],null;var n=nt;if(t.abbr=e,null!=st[e])x("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),n=st[e]._config;else if(null!=t.parentLocale){if(null==st[t.parentLocale])return it[t.parentLocale]||(it[t.parentLocale]=[]),it[t.parentLocale].push({name:e,config:t}),null;n=st[t.parentLocale]._config}return st[e]=new P(b(n,t)),it[e]&&it[e].forEach(function(e){ut(e.name,e.config)}),ot(e),st[e]}function lt(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return et;if(!o(e)){if(t=at(e))return t;e=[e]}return function(e){for(var t,n,s,i,r=0;r<e.length;){for(t=(i=rt(e[r]).split("-")).length,n=(n=rt(e[r+1]))?n.split("-"):null;0<t;){if(s=at(i.slice(0,t).join("-")))return s;if(n&&n.length>=t&&D(i,n,!0)>=t-1)break;t--}r++}return null}(e)}function dt(e){var t,n=e._a;return n&&-2===_(e).overflow&&(t=n[_e]<0||11<n[_e]?_e:n[ye]<1||n[ye]>Pe(n[me],n[_e])?ye:n[ge]<0||24<n[ge]||24===n[ge]&&(0!==n[pe]||0!==n[ve]||0!==n[we])?ge:n[pe]<0||59<n[pe]?pe:n[ve]<0||59<n[ve]?ve:n[we]<0||999<n[we]?we:-1,_(e)._overflowDayOfYear&&(t<me||ye<t)&&(t=ye),_(e)._overflowWeeks&&-1===t&&(t=Me),_(e)._overflowWeekday&&-1===t&&(t=ke),_(e).overflow=t),e}function ht(e,t,n){return null!=e?e:null!=t?t:n}function ct(e){var t,n,s,i,r,a,o=[];if(!e._d){for(r=e,a=new Date(c.now()),s=r._useUTC?[a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate()]:[a.getFullYear(),a.getMonth(),a.getDate()],e._w&&null==e._a[ye]&&null==e._a[_e]&&function(e){var t,n,s,i,r,a,o,u;{var l;null!=(t=e._w).GG||null!=t.W||null!=t.E?(r=1,a=4,n=ht(t.GG,e._a[me],Ie(xt(),1,4).year),s=ht(t.W,1),((i=ht(t.E,1))<1||7<i)&&(u=!0)):(r=e._locale._week.dow,a=e._locale._week.doy,l=Ie(xt(),r,a),n=ht(t.gg,e._a[me],l.year),s=ht(t.w,l.week),null!=t.d?((i=t.d)<0||6<i)&&(u=!0):null!=t.e?(i=t.e+r,(t.e<0||6<t.e)&&(u=!0)):i=r)}s<1||s>Ee(n,r,a)?_(e)._overflowWeeks=!0:null!=u?_(e)._overflowWeekday=!0:(o=je(n,s,i,r,a),e._a[me]=o.year,e._dayOfYear=o.dayOfYear)}(e),null!=e._dayOfYear&&(i=ht(e._a[me],s[me]),(e._dayOfYear>Se(i)||0===e._dayOfYear)&&(_(e)._overflowDayOfYear=!0),n=Ge(i,0,e._dayOfYear),e._a[_e]=n.getUTCMonth(),e._a[ye]=n.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=o[t]=s[t];for(;t<7;t++)e._a[t]=o[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[ge]&&0===e._a[pe]&&0===e._a[ve]&&0===e._a[we]&&(e._nextDay=!0,e._a[ge]=0),e._d=(e._useUTC?Ge:function(e,t,n,s,i,r,a){var o=new Date(e,t,n,s,i,r,a);return e<100&&0<=e&&isFinite(o.getFullYear())&&o.setFullYear(e),o}).apply(null,o),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[ge]=24),e._w&&void 0!==e._w.d&&e._w.d!==e._d.getDay()&&(_(e).weekdayMismatch=!0)}}var ft=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,mt=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,_t=/Z|[+-]\d\d(?::?\d\d)?/,yt=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/]],gt=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],pt=/^\/?Date\((\-?\d+)/i;function vt(e){var t,n,s,i,r,a,o=e._i,u=ft.exec(o)||mt.exec(o);if(u){for(_(e).iso=!0,t=0,n=yt.length;t<n;t++)if(yt[t][1].exec(u[1])){i=yt[t][0],s=!1!==yt[t][2];break}if(null==i)return void(e._isValid=!1);if(u[3]){for(t=0,n=gt.length;t<n;t++)if(gt[t][1].exec(u[3])){r=(u[2]||" ")+gt[t][0];break}if(null==r)return void(e._isValid=!1)}if(!s&&null!=r)return void(e._isValid=!1);if(u[4]){if(!_t.exec(u[4]))return void(e._isValid=!1);a="Z"}e._f=i+(r||"")+(a||""),Dt(e)}else e._isValid=!1}var wt=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;function Mt(e,t,n,s,i,r){var a=[function(e){var t=parseInt(e,10);{if(t<=49)return 2e3+t;if(t<=999)return 1900+t}return t}(e),Ce.indexOf(t),parseInt(n,10),parseInt(s,10),parseInt(i,10)];return r&&a.push(parseInt(r,10)),a}var kt={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function St(e){var t,n,s,i=wt.exec(e._i.replace(/\([^)]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim());if(i){var r=Mt(i[4],i[3],i[2],i[5],i[6],i[7]);if(t=i[1],n=r,s=e,t&&ze.indexOf(t)!==new Date(n[0],n[1],n[2]).getDay()&&(_(s).weekdayMismatch=!0,!void(s._isValid=!1)))return;e._a=r,e._tzm=function(e,t,n){if(e)return kt[e];if(t)return 0;var s=parseInt(n,10),i=s%100;return 60*((s-i)/100)+i}(i[8],i[9],i[10]),e._d=Ge.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),_(e).rfc2822=!0}else e._isValid=!1}function Dt(e){if(e._f!==c.ISO_8601)if(e._f!==c.RFC_2822){e._a=[],_(e).empty=!0;for(var t,n,s,i,r,a,o=""+e._i,u=o.length,l=0,d=A(e._f,e._locale).match(L)||[],h=0;h<d.length;h++)n=d[h],(t=(o.match(le(n,e))||[])[0])&&(0<(s=o.substr(0,o.indexOf(t))).length&&_(e).unusedInput.push(s),o=o.slice(o.indexOf(t)+t.length),l+=t.length),j[n]?(t?_(e).empty=!1:_(e).unusedTokens.push(n),i=n,a=e,null!=(r=t)&&f(he,i)&&he[i](r,a._a,a,i)):e._strict&&!t&&_(e).unusedTokens.push(n);_(e).charsLeftOver=u-l,0<o.length&&_(e).unusedInput.push(o),e._a[ge]<=12&&!0===_(e).bigHour&&0<e._a[ge]&&(_(e).bigHour=void 0),_(e).parsedDateParts=e._a.slice(0),_(e).meridiem=e._meridiem,e._a[ge]=function(e,t,n){var s;if(null==n)return t;return null!=e.meridiemHour?e.meridiemHour(t,n):(null!=e.isPM&&((s=e.isPM(n))&&t<12&&(t+=12),s||12!==t||(t=0)),t)}(e._locale,e._a[ge],e._meridiem),ct(e),dt(e)}else St(e);else vt(e)}function Yt(e){var t,n,s=e._i,i=e._f;return e._locale=e._locale||lt(e._l),null===s||void 0===i&&""===s?g({nullInput:!0}):("string"==typeof s&&(e._i=s=e._locale.preparse(s)),M(s)?new w(dt(s)):(a(s)?e._d=s:o(i)?function(e){var t,n,s,i,r;if(0===e._f.length)return _(e).invalidFormat=!0,e._d=new Date(NaN);for(i=0;i<e._f.length;i++)r=0,t=v({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[i],Dt(t),y(t)&&(r+=_(t).charsLeftOver,r+=10*_(t).unusedTokens.length,_(t).score=r,(null==s||r<s)&&(s=r,n=t));h(e,n||t)}(e):i?Dt(e):r(n=(t=e)._i)?t._d=new Date(c.now()):a(n)?t._d=new Date(n.valueOf()):"string"==typeof n?function(e){var t=pt.exec(e._i);null===t?(vt(e),!1===e._isValid&&(delete e._isValid,St(e),!1===e._isValid&&(delete e._isValid,c.createFromInputFallback(e)))):e._d=new Date(+t[1])}(t):o(n)?(t._a=d(n.slice(0),function(e){return parseInt(e,10)}),ct(t)):u(n)?function(e){var t;e._d||(t=F(e._i),e._a=d([t.year,t.month,t.day||t.date,t.hour,t.minute,t.second,t.millisecond],function(e){return e&&parseInt(e,10)}),ct(e))}(t):l(n)?t._d=new Date(n):c.createFromInputFallback(t),y(e)||(e._d=null),e))}function Ot(e,t,n,s,i){var r,a={};return!0!==n&&!1!==n||(s=n,n=void 0),(u(e)&&function(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;var t;for(t in e)if(e.hasOwnProperty(t))return;return 1}(e)||o(e)&&0===e.length)&&(e=void 0),a._isAMomentObject=!0,a._useUTC=a._isUTC=i,a._l=n,a._i=e,a._f=t,a._strict=s,(r=new w(dt(Yt(a))))._nextDay&&(r.add(1,"d"),r._nextDay=void 0),r}function xt(e,t,n,s){return Ot(e,t,n,s,!1)}c.createFromInputFallback=n("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))}),c.ISO_8601=function(){},c.RFC_2822=function(){};var Tt=n("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=xt.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:g()}),bt=n("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=xt.apply(null,arguments);return this.isValid()&&e.isValid()?this<e?this:e:g()});function Pt(e,t){var n,s;if(1===t.length&&o(t[0])&&(t=t[0]),!t.length)return xt();for(n=t[0],s=1;s<t.length;++s)t[s].isValid()&&!t[s][e](n)||(n=t[s]);return n}var Wt=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Rt(e){var t=F(e),n=t.year||0,s=t.quarter||0,i=t.month||0,r=t.week||0,a=t.day||0,o=t.hour||0,u=t.minute||0,l=t.second||0,d=t.millisecond||0;this._isValid=function(e){for(var t in e)if(-1===Ye.call(Wt,t)||null!=e[t]&&isNaN(e[t]))return!1;for(var n=!1,s=0;s<Wt.length;++s)if(e[Wt[s]]){if(n)return!1;parseFloat(e[Wt[s]])!==S(e[Wt[s]])&&(n=!0)}return!0}(t),this._milliseconds=+d+1e3*l+6e4*u+1e3*o*60*60,this._days=+a+7*r,this._months=+i+3*s+12*n,this._data={},this._locale=lt(),this._bubble()}function Ct(e){return e instanceof Rt}function Ft(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function Ut(e,n){I(e,0,0,function(){var e=this.utcOffset(),t="+";return e<0&&(e=-e,t="-"),t+H(~~(e/60),2)+n+H(~~e%60,2)})}Ut("Z",":"),Ut("ZZ",""),ue("Z",re),ue("ZZ",re),ce(["Z","ZZ"],function(e,t,n){n._useUTC=!0,n._tzm=Ht(re,e)});var Nt=/([\+\-]|\d\d)/gi;function Ht(e,t){var n=(t||"").match(e);if(null===n)return null;var s=((n[n.length-1]||[])+"").match(Nt)||["-",0,0],i=60*s[1]+S(s[2]);return 0===i?0:"+"===s[0]?i:-i}function Lt(e,t){var n,s;return t._isUTC?(n=t.clone(),s=(M(e)||a(e)?e.valueOf():xt(e).valueOf())-n.valueOf(),n._d.setTime(n._d.valueOf()+s),c.updateOffset(n,!1),n):xt(e).local()}function Gt(e){return 15*-Math.round(e._d.getTimezoneOffset()/15)}function Vt(){return!!this.isValid()&&(this._isUTC&&0===this._offset)}c.updateOffset=function(){};var jt=/^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/,It=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function Et(e,t){var n,s,i,r=e,a=null;return Ct(e)?r={ms:e._milliseconds,d:e._days,M:e._months}:l(e)?(r={},t?r[t]=e:r.milliseconds=e):(a=jt.exec(e))?(n="-"===a[1]?-1:1,r={y:0,d:S(a[ye])*n,h:S(a[ge])*n,m:S(a[pe])*n,s:S(a[ve])*n,ms:S(Ft(1e3*a[we]))*n}):(a=It.exec(e))?(n="-"===a[1]?-1:(a[1],1),r={y:At(a[2],n),M:At(a[3],n),w:At(a[4],n),d:At(a[5],n),h:At(a[6],n),m:At(a[7],n),s:At(a[8],n)}):null==r?r={}:"object"==typeof r&&("from"in r||"to"in r)&&(i=function(e,t){var n;if(!e.isValid()||!t.isValid())return{milliseconds:0,months:0};t=Lt(t,e),e.isBefore(t)?n=zt(e,t):((n=zt(t,e)).milliseconds=-n.milliseconds,n.months=-n.months);return n}(xt(r.from),xt(r.to)),(r={}).ms=i.milliseconds,r.M=i.months),s=new Rt(r),Ct(e)&&f(e,"_locale")&&(s._locale=e._locale),s}function At(e,t){var n=e&&parseFloat(e.replace(",","."));return(isNaN(n)?0:n)*t}function zt(e,t){var n={milliseconds:0,months:0};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=t-e.clone().add(n.months,"M"),n}function Zt(s,i){return function(e,t){var n;return null===t||isNaN(+t)||(x(i,"moment()."+i+"(period, number) is deprecated. Please use moment()."+i+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),n=e,e=t,t=n),$t(this,Et(e="string"==typeof e?+e:e,t),s),this}}function $t(e,t,n,s){var i=t._milliseconds,r=Ft(t._days),a=Ft(t._months);e.isValid()&&(s=null==s||s,a&&Fe(e,Te(e,"Month")+a*n),r&&be(e,"Date",Te(e,"Date")+r*n),i&&e._d.setTime(e._d.valueOf()+i*n),s&&c.updateOffset(e,r||a))}Et.fn=Rt.prototype,Et.invalid=function(){return Et(NaN)};var qt=Zt(1,"add"),Jt=Zt(-1,"subtract");function Bt(e,t){var n=12*(t.year()-e.year())+(t.month()-e.month()),s=e.clone().add(n,"months"),i=t-s<0?(t-s)/(s-e.clone().add(n-1,"months")):(t-s)/(e.clone().add(1+n,"months")-s);return-(n+i)||0}function Qt(e){var t;return void 0===e?this._locale._abbr:(null!=(t=lt(e))&&(this._locale=t),this)}c.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",c.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var Xt=n("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return void 0===e?this.localeData():this.locale(e)});function Kt(){return this._locale}function en(e,t){I(0,[e,e.length],0,t)}function tn(e,t,n,s,i){var r;return null==e?Ie(this,s,i).year:((r=Ee(e,s,i))<t&&(t=r),function(e,t,n,s,i){var r=je(e,t,n,s,i),a=Ge(r.year,0,r.dayOfYear);return this.year(a.getUTCFullYear()),this.month(a.getUTCMonth()),this.date(a.getUTCDate()),this}.call(this,e,t,n,s,i))}I(0,["gg",2],0,function(){return this.weekYear()%100}),I(0,["GG",2],0,function(){return this.isoWeekYear()%100}),en("gggg","weekYear"),en("ggggg","weekYear"),en("GGGG","isoWeekYear"),en("GGGGG","isoWeekYear"),R("weekYear","gg"),R("isoWeekYear","GG"),N("weekYear",1),N("isoWeekYear",1),ue("G",se),ue("g",se),ue("GG",B,Z),ue("gg",B,Z),ue("GGGG",ee,q),ue("gggg",ee,q),ue("GGGGG",te,J),ue("ggggg",te,J),fe(["gggg","ggggg","GGGG","GGGGG"],function(e,t,n,s){t[s.substr(0,2)]=S(e)}),fe(["gg","GG"],function(e,t,n,s){t[s]=c.parseTwoDigitYear(e)}),I("Q",0,"Qo","quarter"),R("quarter","Q"),N("quarter",7),ue("Q",z),ce("Q",function(e,t){t[_e]=3*(S(e)-1)}),I("D",["DD",2],"Do","date"),R("date","D"),N("date",9),ue("D",B),ue("DD",B,Z),ue("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),ce(["D","DD"],ye),ce("Do",function(e,t){t[ye]=S(e.match(B)[0])});var nn=xe("Date",!0);I("DDD",["DDDD",3],"DDDo","dayOfYear"),R("dayOfYear","DDD"),N("dayOfYear",4),ue("DDD",K),ue("DDDD",$),ce(["DDD","DDDD"],function(e,t,n){n._dayOfYear=S(e)}),I("m",["mm",2],0,"minute"),R("minute","m"),N("minute",14),ue("m",B),ue("mm",B,Z),ce(["m","mm"],pe);var sn=xe("Minutes",!1);I("s",["ss",2],0,"second"),R("second","s"),N("second",15),ue("s",B),ue("ss",B,Z),ce(["s","ss"],ve);var rn,an=xe("Seconds",!1);for(I("S",0,0,function(){return~~(this.millisecond()/100)}),I(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),I(0,["SSS",3],0,"millisecond"),I(0,["SSSS",4],0,function(){return 10*this.millisecond()}),I(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),I(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),I(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),I(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),I(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),R("millisecond","ms"),N("millisecond",16),ue("S",K,z),ue("SS",K,Z),ue("SSS",K,$),rn="SSSS";rn.length<=9;rn+="S")ue(rn,ne);function on(e,t){t[we]=S(1e3*("0."+e))}for(rn="S";rn.length<=9;rn+="S")ce(rn,on);var un=xe("Milliseconds",!1);I("z",0,0,"zoneAbbr"),I("zz",0,0,"zoneName");var ln=w.prototype;function dn(e){return e}ln.add=qt,ln.calendar=function(e,t){var n=e||xt(),s=Lt(n,this).startOf("day"),i=c.calendarFormat(this,s)||"sameElse",r=t&&(T(t[i])?t[i].call(this,n):t[i]);return this.format(r||this.localeData().calendar(i,this,xt(n)))},ln.clone=function(){return new w(this)},ln.diff=function(e,t,n){var s,i,r;if(!this.isValid())return NaN;if(!(s=Lt(e,this)).isValid())return NaN;switch(i=6e4*(s.utcOffset()-this.utcOffset()),t=C(t)){case"year":r=Bt(this,s)/12;break;case"month":r=Bt(this,s);break;case"quarter":r=Bt(this,s)/3;break;case"second":r=(this-s)/1e3;break;case"minute":r=(this-s)/6e4;break;case"hour":r=(this-s)/36e5;break;case"day":r=(this-s-i)/864e5;break;case"week":r=(this-s-i)/6048e5;break;default:r=this-s}return n?r:k(r)},ln.endOf=function(e){return void 0===(e=C(e))||"millisecond"===e?this:("date"===e&&(e="day"),this.startOf(e).add(1,"isoWeek"===e?"week":e).subtract(1,"ms"))},ln.format=function(e){e=e||(this.isUtc()?c.defaultFormatUtc:c.defaultFormat);var t=E(this,e);return this.localeData().postformat(t)},ln.from=function(e,t){return this.isValid()&&(M(e)&&e.isValid()||xt(e).isValid())?Et({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},ln.fromNow=function(e){return this.from(xt(),e)},ln.to=function(e,t){return this.isValid()&&(M(e)&&e.isValid()||xt(e).isValid())?Et({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},ln.toNow=function(e){return this.to(xt(),e)},ln.get=function(e){return T(this[e=C(e)])?this[e]():this},ln.invalidAt=function(){return _(this).overflow},ln.isAfter=function(e,t){var n=M(e)?e:xt(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=C(r(t)?"millisecond":t))?this.valueOf()>n.valueOf():n.valueOf()<this.clone().startOf(t).valueOf())},ln.isBefore=function(e,t){var n=M(e)?e:xt(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=C(r(t)?"millisecond":t))?this.valueOf()<n.valueOf():this.clone().endOf(t).valueOf()<n.valueOf())},ln.isBetween=function(e,t,n,s){return("("===(s=s||"()")[0]?this.isAfter(e,n):!this.isBefore(e,n))&&(")"===s[1]?this.isBefore(t,n):!this.isAfter(t,n))},ln.isSame=function(e,t){var n,s=M(e)?e:xt(e);return!(!this.isValid()||!s.isValid())&&("millisecond"===(t=C(t||"millisecond"))?this.valueOf()===s.valueOf():(n=s.valueOf(),this.clone().startOf(t).valueOf()<=n&&n<=this.clone().endOf(t).valueOf()))},ln.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},ln.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},ln.isValid=function(){return y(this)},ln.lang=Xt,ln.locale=Qt,ln.localeData=Kt,ln.max=bt,ln.min=Tt,ln.parsingFlags=function(){return h({},_(this))},ln.set=function(e,t){if("object"==typeof e)for(var n=function(e){var t=[];for(var n in e)t.push({unit:n,priority:U[n]});return t.sort(function(e,t){return e.priority-t.priority}),t}(e=F(e)),s=0;s<n.length;s++)this[n[s].unit](e[n[s].unit]);else if(T(this[e=C(e)]))return this[e](t);return this},ln.startOf=function(e){switch(e=C(e)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":case"date":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===e&&this.weekday(0),"isoWeek"===e&&this.isoWeekday(1),"quarter"===e&&this.month(3*Math.floor(this.month()/3)),this},ln.subtract=Jt,ln.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]},ln.toObject=function(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}},ln.toDate=function(){return new Date(this.valueOf())},ln.toISOString=function(){if(!this.isValid())return null;var e=this.clone().utc();return e.year()<0||9999<e.year()?E(e,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]"):T(Date.prototype.toISOString)?this.toDate().toISOString():E(e,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")},ln.inspect=function(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e="moment",t="";this.isLocal()||(e=0===this.utcOffset()?"moment.utc":"moment.parseZone",t="Z");var n="["+e+'("]',s=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",i=t+'[")]';return this.format(n+s+"-MM-DD[T]HH:mm:ss.SSS"+i)},ln.toJSON=function(){return this.isValid()?this.toISOString():null},ln.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},ln.unix=function(){return Math.floor(this.valueOf()/1e3)},ln.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},ln.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},ln.year=Oe,ln.isLeapYear=function(){return De(this.year())},ln.weekYear=function(e){return tn.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)},ln.isoWeekYear=function(e){return tn.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},ln.quarter=ln.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},ln.month=Ue,ln.daysInMonth=function(){return Pe(this.year(),this.month())},ln.week=ln.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},ln.isoWeek=ln.isoWeeks=function(e){var t=Ie(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},ln.weeksInYear=function(){var e=this.localeData()._week;return Ee(this.year(),e.dow,e.doy)},ln.isoWeeksInYear=function(){return Ee(this.year(),1,4)},ln.date=nn,ln.day=ln.days=function(e){if(!this.isValid())return null!=e?this:NaN;var t,n,s=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=e?(t=e,n=this.localeData(),e="string"!=typeof t?t:isNaN(t)?"number"==typeof(t=n.weekdaysParse(t))?t:null:parseInt(t,10),this.add(e-s,"d")):s},ln.weekday=function(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")},ln.isoWeekday=function(e){if(!this.isValid())return null!=e?this:NaN;if(null==e)return this.day()||7;var t,n,s=(t=e,n=this.localeData(),"string"==typeof t?n.weekdaysParse(t)%7||7:isNaN(t)?null:t);return this.day(this.day()%7?s:s-7)},ln.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},ln.hour=ln.hours=tt,ln.minute=ln.minutes=sn,ln.second=ln.seconds=an,ln.millisecond=ln.milliseconds=un,ln.utcOffset=function(e,t,n){var s,i=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null==e)return this._isUTC?i:Gt(this);if("string"==typeof e){if(null===(e=Ht(re,e)))return this}else Math.abs(e)<16&&!n&&(e*=60);return!this._isUTC&&t&&(s=Gt(this)),this._offset=e,this._isUTC=!0,null!=s&&this.add(s,"m"),i!==e&&(!t||this._changeInProgress?$t(this,Et(e-i,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,c.updateOffset(this,!0),this._changeInProgress=null)),this},ln.utc=function(e){return this.utcOffset(0,e)},ln.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Gt(this),"m")),this},ln.parseZone=function(){var e;return null!=this._tzm?this.utcOffset(this._tzm,!1,!0):"string"==typeof this._i&&(null!=(e=Ht(ie,this._i))?this.utcOffset(e):this.utcOffset(0,!0)),this},ln.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?xt(e).utcOffset():0,(this.utcOffset()-e)%60==0)},ln.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},ln.isLocal=function(){return!!this.isValid()&&!this._isUTC},ln.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},ln.isUtc=Vt,ln.isUTC=Vt,ln.zoneAbbr=function(){return this._isUTC?"UTC":""},ln.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},ln.dates=n("dates accessor is deprecated. Use date instead.",nn),ln.months=n("months accessor is deprecated. Use month instead",Ue),ln.years=n("years accessor is deprecated. Use year instead",Oe),ln.zone=n("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",function(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()}),ln.isDSTShifted=n("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",function(){if(!r(this._isDSTShifted))return this._isDSTShifted;var e,t={};return v(t,this),(t=Yt(t))._a?(e=(t._isUTC?m:xt)(t._a),this._isDSTShifted=this.isValid()&&0<D(t._a,e.toArray())):this._isDSTShifted=!1,this._isDSTShifted});var hn=P.prototype;function cn(e,t,n,s){var i=lt(),r=m().set(s,t);return i[n](r,e)}function fn(e,t,n){if(l(e)&&(t=e,e=void 0),e=e||"",null!=t)return cn(e,t,n,"month");for(var s=[],i=0;i<12;i++)s[i]=cn(e,i,n,"month");return s}function mn(e,t,n,s){t=("boolean"==typeof e?l(t)&&(n=t,t=void 0):(t=e,e=!1,l(n=t)&&(n=t,t=void 0)),t||"");var i=lt(),r=e?i._week.dow:0;if(null!=n)return cn(t,(n+r)%7,s,"day");for(var a=[],o=0;o<7;o++)a[o]=cn(t,(o+r)%7,s,"day");return a}hn.calendar=function(e,t,n){var s=this._calendar[e]||this._calendar.sameElse;return T(s)?s.call(t,n):s},hn.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.replace(/MMMM|MM|DD|dddd/g,function(e){return e.slice(1)}),this._longDateFormat[e])},hn.invalidDate=function(){return this._invalidDate},hn.ordinal=function(e){return this._ordinal.replace("%d",e)},hn.preparse=dn,hn.postformat=dn,hn.relativeTime=function(e,t,n,s){var i=this._relativeTime[n];return T(i)?i(e,t,n,s):i.replace(/%d/i,e)},hn.pastFuture=function(e,t){var n=this._relativeTime[0<e?"future":"past"];return T(n)?n(t):n.replace(/%s/i,t)},hn.set=function(e){var t,n;for(n in e)T(t=e[n])?this[n]=t:this["_"+n]=t;this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},hn.months=function(e,t){return e?o(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||We).test(t)?"format":"standalone"][e.month()]:o(this._months)?this._months:this._months.standalone},hn.monthsShort=function(e,t){return e?o(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[We.test(t)?"format":"standalone"][e.month()]:o(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},hn.monthsParse=function(e,t,n){var s,i,r;if(this._monthsParseExact)return function(e,t,n){var s,i,r,a=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],s=0;s<12;++s)r=m([2e3,s]),this._shortMonthsParse[s]=this.monthsShort(r,"").toLocaleLowerCase(),this._longMonthsParse[s]=this.months(r,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=Ye.call(this._shortMonthsParse,a))?i:null:-1!==(i=Ye.call(this._longMonthsParse,a))?i:null:"MMM"===t?-1!==(i=Ye.call(this._shortMonthsParse,a))||-1!==(i=Ye.call(this._longMonthsParse,a))?i:null:-1!==(i=Ye.call(this._longMonthsParse,a))||-1!==(i=Ye.call(this._shortMonthsParse,a))?i:null}.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),s=0;s<12;s++){if(i=m([2e3,s]),n&&!this._longMonthsParse[s]&&(this._longMonthsParse[s]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[s]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[s]||(r="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[s]=new RegExp(r.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[s].test(e))return s;if(n&&"MMM"===t&&this._shortMonthsParse[s].test(e))return s;if(!n&&this._monthsParse[s].test(e))return s}},hn.monthsRegex=function(e){return this._monthsParseExact?(f(this,"_monthsRegex")||Le.call(this),e?this._monthsStrictRegex:this._monthsRegex):(f(this,"_monthsRegex")||(this._monthsRegex=He),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},hn.monthsShortRegex=function(e){return this._monthsParseExact?(f(this,"_monthsRegex")||Le.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(f(this,"_monthsShortRegex")||(this._monthsShortRegex=Ne),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},hn.week=function(e){return Ie(e,this._week.dow,this._week.doy).week},hn.firstDayOfYear=function(){return this._week.doy},hn.firstDayOfWeek=function(){return this._week.dow},hn.weekdays=function(e,t){return e?o(this._weekdays)?this._weekdays[e.day()]:this._weekdays[this._weekdays.isFormat.test(t)?"format":"standalone"][e.day()]:o(this._weekdays)?this._weekdays:this._weekdays.standalone},hn.weekdaysMin=function(e){return e?this._weekdaysMin[e.day()]:this._weekdaysMin},hn.weekdaysShort=function(e){return e?this._weekdaysShort[e.day()]:this._weekdaysShort},hn.weekdaysParse=function(e,t,n){var s,i,r;if(this._weekdaysParseExact)return function(e,t,n){var s,i,r,a=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],s=0;s<7;++s)r=m([2e3,1]).day(s),this._minWeekdaysParse[s]=this.weekdaysMin(r,"").toLocaleLowerCase(),this._shortWeekdaysParse[s]=this.weekdaysShort(r,"").toLocaleLowerCase(),this._weekdaysParse[s]=this.weekdays(r,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=Ye.call(this._weekdaysParse,a))?i:null:"ddd"===t?-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:null:-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:"dddd"===t?-1!==(i=Ye.call(this._weekdaysParse,a))||-1!==(i=Ye.call(this._shortWeekdaysParse,a))||-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:"ddd"===t?-1!==(i=Ye.call(this._shortWeekdaysParse,a))||-1!==(i=Ye.call(this._weekdaysParse,a))||-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:-1!==(i=Ye.call(this._minWeekdaysParse,a))||-1!==(i=Ye.call(this._weekdaysParse,a))||-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:null}.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),s=0;s<7;s++){if(i=m([2e3,1]).day(s),n&&!this._fullWeekdaysParse[s]&&(this._fullWeekdaysParse[s]=new RegExp("^"+this.weekdays(i,"").replace(".",".?")+"$","i"),this._shortWeekdaysParse[s]=new RegExp("^"+this.weekdaysShort(i,"").replace(".",".?")+"$","i"),this._minWeekdaysParse[s]=new RegExp("^"+this.weekdaysMin(i,"").replace(".",".?")+"$","i")),this._weekdaysParse[s]||(r="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[s]=new RegExp(r.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[s].test(e))return s;if(n&&"ddd"===t&&this._shortWeekdaysParse[s].test(e))return s;if(n&&"dd"===t&&this._minWeekdaysParse[s].test(e))return s;if(!n&&this._weekdaysParse[s].test(e))return s}},hn.weekdaysRegex=function(e){return this._weekdaysParseExact?(f(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(f(this,"_weekdaysRegex")||(this._weekdaysRegex=$e),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},hn.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(f(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(f(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=qe),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},hn.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(f(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(f(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=Je),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},hn.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},hn.meridiem=function(e,t,n){return 11<e?n?"pm":"PM":n?"am":"AM"},ot("en",{dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===S(e%100/10)?"th":1==t?"st":2==t?"nd":3==t?"rd":"th")}}),c.lang=n("moment.lang is deprecated. Use moment.locale instead.",ot),c.langData=n("moment.langData is deprecated. Use moment.localeData instead.",lt);var _n=Math.abs;function yn(e,t,n,s){var i=Et(t,n);return e._milliseconds+=s*i._milliseconds,e._days+=s*i._days,e._months+=s*i._months,e._bubble()}function gn(e){return e<0?Math.floor(e):Math.ceil(e)}function pn(e){return 4800*e/146097}function vn(e){return 146097*e/4800}function wn(e){return function(){return this.as(e)}}var Mn=wn("ms"),kn=wn("s"),Sn=wn("m"),Dn=wn("h"),Yn=wn("d"),On=wn("w"),xn=wn("M"),Tn=wn("y");function bn(e){return function(){return this.isValid()?this._data[e]:NaN}}var Pn=bn("milliseconds"),Wn=bn("seconds"),Rn=bn("minutes"),Cn=bn("hours"),Fn=bn("days"),Un=bn("months"),Nn=bn("years");var Hn=Math.round,Ln={ss:44,s:45,m:45,h:22,d:26,M:11};function Gn(e,t,n){var s=Et(e).abs(),i=Hn(s.as("s")),r=Hn(s.as("m")),a=Hn(s.as("h")),o=Hn(s.as("d")),u=Hn(s.as("M")),l=Hn(s.as("y")),d=(i<=Ln.ss?["s",i]:i<Ln.s&&["ss",i])||r<=1&&["m"]||r<Ln.m&&["mm",r]||a<=1&&["h"]||a<Ln.h&&["hh",a]||o<=1&&["d"]||o<Ln.d&&["dd",o]||u<=1&&["M"]||u<Ln.M&&["MM",u]||l<=1&&["y"]||["yy",l];return d[2]=t,d[3]=0<+e,d[4]=n,function(e,t,n,s,i){return i.relativeTime(t||1,!!n,e,s)}.apply(null,d)}var Vn=Math.abs;function jn(e){return(0<e)-(e<0)||+e}function In(){if(!this.isValid())return this.localeData().invalidDate();var e=Vn(this._milliseconds)/1e3,t=Vn(this._days),n=Vn(this._months),s=k(e/60),i=k(s/60);e%=60,s%=60;var r=k(n/12),a=n%=12,o=t,u=i,l=s,d=e?e.toFixed(3).replace(/\.?0+$/,""):"",h=this.asSeconds();if(!h)return"P0D";var c=h<0?"-":"",f=jn(this._months)!==jn(h)?"-":"",m=jn(this._days)!==jn(h)?"-":"",_=jn(this._milliseconds)!==jn(h)?"-":"";return c+"P"+(r?f+r+"Y":"")+(a?f+a+"M":"")+(o?m+o+"D":"")+(u||l||d?"T":"")+(u?_+u+"H":"")+(l?_+l+"M":"")+(d?_+d+"S":"")}var En=Rt.prototype;return En.isValid=function(){return this._isValid},En.abs=function(){var e=this._data;return this._milliseconds=_n(this._milliseconds),this._days=_n(this._days),this._months=_n(this._months),e.milliseconds=_n(e.milliseconds),e.seconds=_n(e.seconds),e.minutes=_n(e.minutes),e.hours=_n(e.hours),e.months=_n(e.months),e.years=_n(e.years),this},En.add=function(e,t){return yn(this,e,t,1)},En.subtract=function(e,t){return yn(this,e,t,-1)},En.as=function(e){if(!this.isValid())return NaN;var t,n,s=this._milliseconds;if("month"===(e=C(e))||"year"===e)return t=this._days+s/864e5,n=this._months+pn(t),"month"===e?n:n/12;switch(t=this._days+Math.round(vn(this._months)),e){case"week":return t/7+s/6048e5;case"day":return t+s/864e5;case"hour":return 24*t+s/36e5;case"minute":return 1440*t+s/6e4;case"second":return 86400*t+s/1e3;case"millisecond":return Math.floor(864e5*t)+s;default:throw new Error("Unknown unit "+e)}},En.asMilliseconds=Mn,En.asSeconds=kn,En.asMinutes=Sn,En.asHours=Dn,En.asDays=Yn,En.asWeeks=On,En.asMonths=xn,En.asYears=Tn,En.valueOf=function(){return this.isValid()?this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*S(this._months/12):NaN},En._bubble=function(){var e,t,n,s,i,r=this._milliseconds,a=this._days,o=this._months,u=this._data;return 0<=r&&0<=a&&0<=o||r<=0&&a<=0&&o<=0||(r+=864e5*gn(vn(o)+a),o=a=0),u.milliseconds=r%1e3,e=k(r/1e3),u.seconds=e%60,t=k(e/60),u.minutes=t%60,n=k(t/60),u.hours=n%24,a+=k(n/24),o+=i=k(pn(a)),a-=gn(vn(i)),s=k(o/12),o%=12,u.days=a,u.months=o,u.years=s,this},En.clone=function(){return Et(this)},En.get=function(e){return e=C(e),this.isValid()?this[e+"s"]():NaN},En.milliseconds=Pn,En.seconds=Wn,En.minutes=Rn,En.hours=Cn,En.days=Fn,En.weeks=function(){return k(this.days()/7)},En.months=Un,En.years=Nn,En.humanize=function(e){if(!this.isValid())return this.localeData().invalidDate();var t=this.localeData(),n=Gn(this,!e,t);return e&&(n=t.pastFuture(+this,n)),t.postformat(n)},En.toISOString=In,En.toString=In,En.toJSON=In,En.locale=Qt,En.localeData=Kt,En.toIsoString=n("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",In),En.lang=Xt,I("X",0,0,"unix"),I("x",0,0,"valueOf"),ue("x",se),ue("X",/[+-]?\d+(\.\d{1,3})?/),ce("X",function(e,t,n){n._d=new Date(1e3*parseFloat(e,10))}),ce("x",function(e,t,n){n._d=new Date(S(e))}),c.version="2.19.1",e=xt,c.fn=ln,c.min=function(){return Pt("isBefore",[].slice.call(arguments,0))},c.max=function(){return Pt("isAfter",[].slice.call(arguments,0))},c.now=function(){return Date.now?Date.now():+new Date},c.utc=m,c.unix=function(e){return xt(1e3*e)},c.months=function(e,t){return fn(e,t,"months")},c.isDate=a,c.locale=ot,c.invalid=g,c.duration=Et,c.isMoment=M,c.weekdays=function(e,t,n){return mn(e,t,n,"weekdays")},c.parseZone=function(){return xt.apply(null,arguments).parseZone()},c.localeData=lt,c.isDuration=Ct,c.monthsShort=function(e,t){return fn(e,t,"monthsShort")},c.weekdaysMin=function(e,t,n){return mn(e,t,n,"weekdaysMin")},c.defineLocale=ut,c.updateLocale=function(e,t){var n,s;return null!=t?(s=nt,null!=st[e]&&(s=st[e]._config),(n=new P(t=b(s,t))).parentLocale=st[e],st[e]=n,ot(e)):null!=st[e]&&(null!=st[e].parentLocale?st[e]=st[e].parentLocale:null!=st[e]&&delete st[e]),st[e]},c.locales=function(){return s(st)},c.weekdaysShort=function(e,t,n){return mn(e,t,n,"weekdaysShort")},c.normalizeUnits=C,c.relativeTimeRounding=function(e){return void 0===e?Hn:"function"==typeof e&&(Hn=e,!0)},c.relativeTimeThreshold=function(e,t){return void 0!==Ln[e]&&(void 0===t?Ln[e]:(Ln[e]=t,"s"===e&&(Ln.ss=t-1),!0))},c.calendarFormat=function(e,t){var n=e.diff(t,"days",!0);return n<-6?"sameElse":n<-1?"lastWeek":n<0?"lastDay":n<1?"sameDay":n<2?"nextDay":n<7?"nextWeek":"sameElse"},c.prototype=ln,c});
|
var requireDir = require('require-dir'),
_ = require('underscore')._,
async = require("async"),
libGroups = require("./languages/libGroups"),
fs = require('graceful-fs');
var db = require("./database.js");
var fs = require('fs');
var Log = require("log");
//var log = new Log('info',fs.createWriteStream('relex.log'));
var log = {info:function(){}}
log.info('Loading parsersLib');
var parsersLib = module.exports = {
pluginsList: new Array(),
priorities: new Array(),
runCount:0,
"sourceCount":0,
processList: function(cbProcessList){
var pluginsList = requireDir("../parsers");
pluginsList = _.where(pluginsList,{"active": true});
var priorityList = _.uniq(_.sortBy(_.pluck(pluginsList, 'priority')),true);
//fs.writeFile("priority.json", JSON.stringify(_.sortBy(pluginsList,'priority'),null,4), function(err) {});
var counter = 0;
async.mapSeries(priorityList, function(currentPriority,cbPriorities){
log.info('## Priority start:'+currentPriority);
async.each(_.where(pluginsList,{"priority": currentPriority}), function(currentPlugin,cbPlugins){
// log.info('Current Plugin running',currentPlugin.name);
//relationsclass.db
db.findNodes(currentPlugin.filter,function(nodesList){
log.info('"@@ Parser executing',currentPlugin.name);
if(!_.isUndefined(nodesList) && nodesList.length > 0){
async.each(nodesList, function(node,cbNodeUpdt){
currentPlugin.parser(node,function(err,newNode){
parsersLib.errorHandler(err);
// log.info('Parser parsing node',"["+Math.round(process.memoryUsage().rss / (1024 * 1024))+"mb used] =>"+node.name);
if(newNode !== null){
db.nodeUpdate(newNode,function(err,nodeAdded){
setImmediate(cbNodeUpdt());
});
}
else{
setImmediate(cbNodeUpdt());
}
});
},function(err){
//log.info('Plugin finished executing',currentPlugin.name);
//setTimeout(function(){ cbPlugins(); }, 100);
setImmediate(cbPlugins());
});
}else{
log.info('No nodes to parse for ',currentPlugin.name);
cbPlugins();
}
});
}, function(err) {
log.info('## Priority done:'+currentPriority);
parsersLib.errorHandler(err);
cbPriorities();
});
},function(err) {
parsersLib.errorHandler(err);
log.info('## All Plugin executed');
cbProcessList(err);
});
},
errorHandler: function(err){
if(err){
err.file = "parsersLib.js";
err.func = func;
console.log("Error",err);
}
}
};
|
function _defineProperty(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var o=0;o<t.length;o++){var i=t[o];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function _createClass(e,t,o){return t&&_defineProperties(e.prototype,t),o&&_defineProperties(e,o),e}(window.webpackJsonp=window.webpackJsonp||[]).push([[60],{VgKV:function(e,t,o){"use strict";o.r(t),o.d(t,"ion_popover",(function(){return f}));var i=o("c1op"),r=(o("AfW+"),o("aiEM"),o("+4pY")),n=(o("kBU6"),o("pori")),a=o("Dl6n"),s=o("m9yc"),p=o("K6rM"),c=function(e,t){var o="top",i="left",n=e.querySelector(".popover-content"),a=n.getBoundingClientRect(),s=a.width,p=a.height,c=e.ownerDocument.defaultView.innerWidth,d=e.ownerDocument.defaultView.innerHeight,u=t&&t.target&&t.target.getBoundingClientRect(),h=null!=u&&"top"in u?u.top:d/2-p/2,f=null!=u&&"left"in u?u.left:c/2,m=u&&u.width||0,v=u&&u.height||0,b=e.querySelector(".popover-arrow"),g=b.getBoundingClientRect(),w=g.width,y=g.height;null==u&&(b.style.display="none");var x={top:h+v,left:f+m/2-w/2},j={top:h+v+(y-1),left:f+m/2-s/2},O=!1,k=!1;j.left<l+25?(O=!0,j.left=l):s+l+j.left+25>c&&(k=!0,j.left=c-s-l,i="right"),h+v+p>d&&h-p>0?(x.top=h-(y+1),j.top=h-p-(y-1),e.className=e.className+" popover-bottom",o="bottom"):h+v+p>d&&(n.style.bottom=l+"%"),b.style.top=x.top+"px",b.style.left=x.left+"px",n.style.top=j.top+"px",n.style.left=j.left+"px",O&&(n.style.left="calc(".concat(j.left,"px + var(--ion-safe-area-left, 0px))")),k&&(n.style.left="calc(".concat(j.left,"px - var(--ion-safe-area-right, 0px))")),n.style.transformOrigin=o+" "+i;var D=Object(r.a)(),P=Object(r.a)(),E=Object(r.a)();return P.addElement(e.querySelector("ion-backdrop")).fromTo("opacity",.01,.08),E.addElement(e.querySelector(".popover-wrapper")).fromTo("opacity",.01,1),D.addElement(e).easing("ease").duration(100).addAnimation([P,E])},l=5,d=function(e){var t=Object(r.a)(),o=Object(r.a)(),i=Object(r.a)();return o.addElement(e.querySelector("ion-backdrop")).fromTo("opacity",.08,0),i.addElement(e.querySelector(".popover-wrapper")).fromTo("opacity",.99,0),t.addElement(e).easing("ease").duration(500).addAnimation([o,i])},u=function(e,t){var o=e.ownerDocument,i="rtl"===o.dir,n="top",a=i?"right":"left",s=e.querySelector(".popover-content"),p=s.getBoundingClientRect(),c=p.width,l=p.height,d=o.defaultView.innerWidth,u=o.defaultView.innerHeight,h=t&&t.target&&t.target.getBoundingClientRect(),f=null!=h&&"bottom"in h?h.bottom:u/2-l/2,m=h&&h.height||0,v={top:f,left:null!=h&&"left"in h?i?h.left-c+h.width:h.left:d/2-c/2};v.left<12?(v.left=12,a="left"):c+12+v.left>d&&(v.left=d-c-12,a="right"),f+m+l>u&&f-l>0?(v.top=f-l-m,e.className=e.className+" popover-bottom",n="bottom"):f+m+l>u&&(s.style.bottom="12px");var b=Object(r.a)(),g=Object(r.a)(),w=Object(r.a)(),y=Object(r.a)(),x=Object(r.a)();return g.addElement(e.querySelector("ion-backdrop")).fromTo("opacity",.01,.32),w.addElement(e.querySelector(".popover-wrapper")).fromTo("opacity",.01,1),y.addElement(s).beforeStyles({top:"".concat(v.top,"px"),left:"".concat(v.left,"px"),"transform-origin":"".concat(n," ").concat(a)}).fromTo("transform","scale(0.001)","scale(1)"),x.addElement(e.querySelector(".popover-viewport")).fromTo("opacity",.01,1),b.addElement(e).easing("cubic-bezier(0.36,0.66,0.04,1)").duration(300).addAnimation([g,w,y,x])},h=function(e){var t=Object(r.a)(),o=Object(r.a)(),i=Object(r.a)();return o.addElement(e.querySelector("ion-backdrop")).fromTo("opacity",.32,0),i.addElement(e.querySelector(".popover-wrapper")).fromTo("opacity",.99,0),t.addElement(e).easing("ease").duration(500).addAnimation([o,i])},f=function(){function e(t){var o=this;_classCallCheck(this,e),Object(i.l)(this,t),this.presented=!1,this.mode=Object(i.d)(this),this.keyboardClose=!0,this.backdropDismiss=!0,this.showBackdrop=!0,this.translucent=!1,this.animated=!0,this.onDismiss=function(e){e.stopPropagation(),e.preventDefault(),o.dismiss()},this.onBackdropTap=function(){o.dismiss(void 0,n.a)},this.onLifecycle=function(e){var t=o.usersElement,i=m[e.type];if(t&&i){var r=new CustomEvent(i,{bubbles:!1,cancelable:!1,detail:e.detail});t.dispatchEvent(r)}},Object(n.e)(this.el),this.didPresent=Object(i.e)(this,"ionPopoverDidPresent",7),this.willPresent=Object(i.e)(this,"ionPopoverWillPresent",7),this.willDismiss=Object(i.e)(this,"ionPopoverWillDismiss",7),this.didDismiss=Object(i.e)(this,"ionPopoverDidDismiss",7)}return _createClass(e,[{key:"present",value:function(){var e,t;return regeneratorRuntime.async((function(o){for(;;)switch(o.prev=o.next){case 0:if(!this.presented){o.next=2;break}return o.abrupt("return");case 2:if(e=this.el.querySelector(".popover-content")){o.next=5;break}throw new Error("container is undefined");case 5:return t=Object.assign(Object.assign({},this.componentProps),{popover:this.el}),o.next=8,regeneratorRuntime.awrap(Object(s.a)(this.delegate,e,this.component,["popover-viewport",this.el["s-sc"]],t));case 8:return this.usersElement=o.sent,o.next=11,regeneratorRuntime.awrap(Object(p.a)(this.usersElement));case 11:return o.abrupt("return",Object(n.f)(this,"popoverEnter",c,u,this.event));case 12:case"end":return o.stop()}}),null,this)}},{key:"dismiss",value:function(e,t){var o;return regeneratorRuntime.async((function(i){for(;;)switch(i.prev=i.next){case 0:return i.next=2,regeneratorRuntime.awrap(Object(n.g)(this,e,t,"popoverLeave",d,h,this.event));case 2:if(o=i.sent,i.t0=o,!i.t0){i.next=7;break}return i.next=7,regeneratorRuntime.awrap(Object(s.b)(this.delegate,this.usersElement));case 7:return i.abrupt("return",o);case 8:case"end":return i.stop()}}),null,this)}},{key:"onDidDismiss",value:function(){return Object(n.h)(this.el,"ionPopoverDidDismiss")}},{key:"onWillDismiss",value:function(){return Object(n.h)(this.el,"ionPopoverWillDismiss")}},{key:"render",value:function(){var e,t=Object(i.d)(this),o=this.onLifecycle;return Object(i.i)(i.a,{"aria-modal":"true","no-router":!0,style:{zIndex:"".concat(2e4+this.overlayIndex)},class:Object.assign(Object.assign({},Object(a.b)(this.cssClass)),(e={},_defineProperty(e,t,!0),_defineProperty(e,"popover-translucent",this.translucent),e)),onIonPopoverDidPresent:o,onIonPopoverWillPresent:o,onIonPopoverWillDismiss:o,onIonPopoverDidDismiss:o,onIonDismiss:this.onDismiss,onIonBackdropTap:this.onBackdropTap},Object(i.i)("ion-backdrop",{tappable:this.backdropDismiss,visible:this.showBackdrop}),Object(i.i)("div",{class:"popover-wrapper"},Object(i.i)("div",{class:"popover-arrow"}),Object(i.i)("div",{class:"popover-content"})))}},{key:"el",get:function(){return Object(i.f)(this)}}],[{key:"style",get:function(){return".sc-ion-popover-md-h{--background:var(--ion-background-color,#fff);--min-width:0;--min-height:0;--max-width:auto;--height:auto;left:0;right:0;top:0;bottom:0;display:-ms-flexbox;display:flex;position:fixed;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;color:var(--ion-text-color,#000);z-index:1001}.overlay-hidden.sc-ion-popover-md-h{display:none}.popover-wrapper.sc-ion-popover-md{opacity:0;z-index:10}.popover-content.sc-ion-popover-md{display:-ms-flexbox;display:flex;position:absolute;-ms-flex-direction:column;flex-direction:column;width:var(--width);min-width:var(--min-width);max-width:var(--max-width);height:var(--height);min-height:var(--min-height);max-height:var(--max-height);background:var(--background);-webkit-box-shadow:var(--box-shadow);box-shadow:var(--box-shadow);overflow:auto;z-index:10}.popover-viewport.sc-ion-popover-md{--ion-safe-area-top:0px;--ion-safe-area-right:0px;--ion-safe-area-bottom:0px;--ion-safe-area-left:0px}.sc-ion-popover-md-h{--width:250px;--max-height:90%;--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)}.popover-content.sc-ion-popover-md{border-radius:4px;-webkit-transform-origin:left top;transform-origin:left top}[dir=rtl].sc-ion-popover-md-h .popover-content.sc-ion-popover-md, [dir=rtl] .sc-ion-popover-md-h .popover-content.sc-ion-popover-md, [dir=rtl].sc-ion-popover-md .popover-content.sc-ion-popover-md{-webkit-transform-origin:right top;transform-origin:right top}.popover-viewport.sc-ion-popover-md{-webkit-transition-delay:.1s;transition-delay:.1s}"}}]),e}(),m={ionPopoverDidPresent:"ionViewDidEnter",ionPopoverWillPresent:"ionViewWillEnter",ionPopoverWillDismiss:"ionViewWillLeave",ionPopoverDidDismiss:"ionViewDidLeave"}}}]);
|
// Copyright (C) 2007-2019, GoodData(R) Corporation. All rights reserved.
import React, { Component } from 'react';
import '@gooddata/react-components/styles/css/main.css';
import GrossProfitInMonth from '../grossProfitInMonth';
import GrossProfitAllMonths from '../grossProfitAllMonths';
class App extends Component {
render() {
return (
<div className="App">
<GrossProfitInMonth/>
<GrossProfitAllMonths/>
</div>
);
}
}
export default App;
|
import { Template } from 'meteor/templating';
Template.registerHelper('isDefined', value => value !== undefined);
|
"use strict";
define(['NccModal', 'Utils', 'TransactionType', 'handlebars', 'typeahead'], function(NccModal, Utils, TransactionType, Handlebars) {
return NccModal.extend({
});
});
|
require('./bind-for');
var diff = require('./lib/diff');
var lib = require('./lib/index');
var wrapArray = require('./lib/array').wrapArray;
// Singleton state definition.
var State = {
initialState: {},
nonBindedStateKeys: [],
handlers: {},
computeState: [function () { /* no-op */ }]
};
var STATE_UPDATE_EVENT = 'stateupdate';
var TYPE_OBJECT = 'object';
var WHITESPACE_REGEX = /s+/;
AFRAME.registerState = function (definition) {
const computeState = State.computeState;
if (definition.computeState) {
computeState.push(definition.computeState);
}
AFRAME.utils.extendDeep(State, definition);
State.computeState = computeState;
}
AFRAME.registerSystem('state', {
init: function () {
var key;
this.arrays = [];
this.dirtyArrays = [];
this.diff = {};
this.state = AFRAME.utils.clone(State.initialState);
this.subscriptions = [];
this.initEventHandlers();
// Wrap array to detect dirty.
for (key in this.state) {
if (this.state[key] && this.state[key].constructor === Array) {
this.arrays.push(key);
this.state[key].__dirty = true;
wrapArray(this.state[key]);
}
}
this.lastState = AFRAME.utils.clone(this.state);
this.eventDetail = {
lastState: this.lastState,
state: this.state
};
this.el.addEventListener('loaded', () => {
var i;
// Initial compute.
for (i = 0; i < State.computeState.length; i++) {
State.computeState[i](this.state, '@@INIT');
}
// Initial dispatch.
for (i = 0; i < this.subscriptions.length; i++) {
this.subscriptions[i].onStateUpdate(this.state);
}
});
},
/**
* Dispatch action.
*/
dispatch: (function () {
const toUpdate = [];
return function (actionName, payload) {
var dirtyArrays;
var i;
var key;
var subscription;
// Modify state.
State.handlers[actionName](this.state, payload);
// Post-compute.
for (i = 0; i < State.computeState.length; i++) {
State.computeState[i](this.state, actionName, payload);
}
// Get a diff to optimize bind updates.
for (key in this.diff) { delete this.diff[key]; }
diff(this.lastState, this.state, this.diff, State.nonBindedStateKeys);
this.dirtyArrays.length = 0;
for (i = 0; i < this.arrays.length; i++) {
if (this.state[this.arrays[i]].__dirty) {
this.dirtyArrays.push(this.arrays[i]);
}
}
// Notify subscriptions / binders.
let currentUpdateCount = 0;
for (i = 0; i < this.subscriptions.length; i++) {
if (this.subscriptions[i].name === 'bind-for') {
// For arrays and bind-for, check __dirty flag on array rather than the diff.
if (!this.state[this.subscriptions[i].keysToWatch[0]].__dirty) { continue; }
} else {
if (!this.shouldUpdate(this.subscriptions[i].keysToWatch, this.diff,
this.dirtyArrays)) { continue; }
}
// Keep track to only update subscriptions once.
if (toUpdate.indexOf(this.subscriptions[i]) === -1) {
toUpdate.push(this.subscriptions[i]);
currentUpdateCount++;
}
}
// Unset array dirty.
for (key in this.state) {
if (this.state[key] && this.state[key].constructor === Array) {
this.state[key].__dirty = false;
}
}
// Store last state.
this.copyState(this.lastState, this.state);
// Update subscriptions.
for (i = 0; i < currentUpdateCount; i++) {
let subscriber = toUpdate.pop();
subscriber.onStateUpdate();
}
// Emit.
this.eventDetail.action = actionName;
this.eventDetail.payload = payload;
this.el.emit(STATE_UPDATE_EVENT, this.eventDetail);
};
})(),
/**
* Store last state through a deep extend, but not for arrays.
*/
copyState: function (lastState, state, isRecursive) {
var key;
for (key in state) {
// Don't copy pieces of state keys that are non-binded or untracked.
if (!isRecursive && State.nonBindedStateKeys.indexOf(key) !== -1) { continue; }
// Nested state.
if (state[key] && state[key].constructor === Object) {
if (!(key in lastState)) {
// Clone object if destination does not exist.
lastState[key] = AFRAME.utils.clone(state[key]);
continue;
}
// Recursively copy state.
this.copyState(lastState[key], state[key], true);
continue;
}
// Copy by value.
lastState[key] = state[key];
}
},
subscribe: function (component) {
this.subscriptions.push(component);
},
unsubscribe: function (component) {
var i = this.subscriptions.indexOf(component);
if (i > -1)
this.subscriptions.splice(i, 1);
},
/**
* Check if state changes were relevant to this binding. If not, don't call.
*/
shouldUpdate: function (keysToWatch, diff, dirtyArrays) {
for (let i = 0; i < keysToWatch.length; i++) {
if (keysToWatch[i] in diff || dirtyArrays.indexOf(keysToWatch[i]) !== -1) {
return true;
}
}
return false;
},
/**
* Proxy events to action dispatches so components can just bubble actions up as events.
* Handlers define which actions they handle. Go through all and add event listeners.
*/
initEventHandlers: function () {
var actionName;
var registeredActions = [];
var self = this;
registerListener = registerListener.bind(this);
// Use declared handlers to know what events to listen to.
for (actionName in State.handlers) {
// Only need to register one handler for each event.
if (registeredActions.indexOf(actionName) !== -1) { continue; }
registeredActions.push(actionName);
registerListener(actionName);
}
function registerListener (actionName) {
this.el.addEventListener(actionName, evt => {
this.dispatch(actionName, evt.detail);
});
}
},
/**
* Render template to string with item data.
*/
renderTemplate: (function () {
// Braces, whitespace, optional item name, item key, whitespace, braces.
var interpRegex = /{{\s*(\w*\.)?([\w.]+)\s*}}/g;
return function (template, data, asString) {
var match;
var str;
str = template;
// Data will be null if initialize pool for bind-for.updateInPlace.
if (data) {
while (match = interpRegex.exec(template)) {
str = str.replace(
match[0],
typeof data === TYPE_OBJECT
? lib.select(data, match[2]) || ''
: data);
}
}
// Return as string.
if (asString) { return str; }
// Return as DOM.
return document.createRange().createContextualFragment(str);
};
})(),
select: lib.select
});
/**
* Bind component property to a value in state.
*
* bind="geometry.width: car.width""
* bind__material="color: enemy.color; opacity: enemy.opacity"
* bind__visible="player.visible"
*/
AFRAME.registerComponent('bind', {
schema: {
default: {},
parse: function (value) {
// Parse style-like object.
var data;
var i;
var properties;
var pair;
// Using setAttribute with object, no need to parse.
if (value.constructor === Object) { return value; }
// Using instanced ID as component namespace for single-property component,
// nothing to separate.
if (value.indexOf(':') === -1) { return value; }
// Parse style-like object as keys to values.
data = {};
properties = lib.split(value, ';');
for (i = 0; i < properties.length; i++) {
pair = lib.split(properties[i].trim(), ':');
data[pair[0]] = pair[1].trim();
}
return data;
}
},
multiple: true,
init: function () {
var componentId;
var data = this.data;
var key;
this.keysToWatch = [];
this.onStateUpdate = this.onStateUpdate.bind(this);
this.system = this.el.sceneEl.systems.state;
// Whether we are binding by namespace (e.g., bind__foo="prop1: true").
if (this.id) {
componentId = lib.split(this.id, '__')[0];
}
this.isNamespacedBind =
this.id &&
(componentId in AFRAME.components && !AFRAME.components[componentId].isSingleProp) ||
componentId in AFRAME.systems;
this.lastData = {};
this.updateObj = {};
// Subscribe to store and register handler to do data-binding to components.
this.system.subscribe(this);
this.onStateUpdate = this.onStateUpdate.bind(this);
},
update: function () {
var data = this.data;
var key;
var property;
// Index `keysToWatch` to only update state on relevant changes.
this.keysToWatch.length = 0;
if (typeof data === 'string') {
lib.parseKeysToWatch(this.keysToWatch, data);
} else {
for (key in data) {
lib.parseKeysToWatch(this.keysToWatch, data[key]);
}
}
this.onStateUpdate();
},
/**
* Handle state update.
*/
onStateUpdate: function () {
// Update component with the state.
var hasKeys = false;
var el = this.el;
var propertyName;
var stateSelector;
var state;
var tempNode;
var value;
if (!el.parentNode) { return; }
if (this.isNamespacedBind) { lib.clearObject(this.updateObj); }
state = this.system.state;
// Single-property bind.
if (typeof this.data !== TYPE_OBJECT) {
try {
value = lib.select(state, this.data);
} catch (e) {
throw new Error(`[aframe-state-component] Key '${this.data}' not found in state.` +
` #${this.el.getAttribute('id')}[${this.attrName}]`);
}
if (typeof value !== TYPE_OBJECT &&
typeof this.lastData !== TYPE_OBJECT &&
this.lastData === value) { return; }
AFRAME.utils.entity.setComponentProperty(el, this.id, value);
this.lastData = value;
return;
}
for (propertyName in this.data) {
// Pointer to a value in the state (e.g., `player.health`).
stateSelector = this.data[propertyName].trim();
try {
value = lib.select(state, stateSelector);
} catch (e) {
console.log(e);
throw new Error(`[aframe-state-component] Key '${stateSelector}' not found in state.` +
` #${this.el.getAttribute('id')}[${this.attrName}]`);
}
if (typeof value !== TYPE_OBJECT &&
typeof this.lastData[propertyName] !== TYPE_OBJECT &&
this.lastData[propertyName] === value) { continue; }
// Remove component if value is `undefined`.
if (propertyName in AFRAME.components && value === undefined) {
el.removeAttribute(propertyName);
return;
}
// Set using dot-delimited property name.
if (this.isNamespacedBind) {
// Batch if doing namespaced bind.
this.updateObj[propertyName] = value;
} else {
AFRAME.utils.entity.setComponentProperty(el, propertyName, value);
}
this.lastData[propertyName] = value;
}
// Batch if doing namespaced bind.
for (hasKeys in this.updateObj) {
// See if object is empty.
}
if (this.isNamespacedBind && hasKeys) {
el.setAttribute(this.id, this.updateObj);
}
},
remove: function () {
this.system.unsubscribe(this);
}
});
/**
* Toggle component attach and detach based on boolean value.
*
* bind-toggle__raycastable="isRaycastable""
*/
AFRAME.registerComponent('bind-toggle', {
schema: {type: 'string'},
multiple: true,
init: function () {
this.system = this.el.sceneEl.systems.state;
this.keysToWatch = [];
this.onStateUpdate = this.onStateUpdate.bind(this);
// Subscribe to store and register handler to do data-binding to components.
this.system.subscribe(this);
this.onStateUpdate();
},
update: function () {
this.keysToWatch.length = 0;
lib.parseKeysToWatch(this.keysToWatch, this.data);
},
/**
* Handle state update.
*/
onStateUpdate: function () {
var el = this.el;
var state;
var value;
state = this.system.state;
try {
value = lib.select(state, this.data);
} catch (e) {
throw new Error(`[aframe-state-component] Key '${this.data}' not found in state.` +
` #${this.el.getAttribute('id')}[${this.attrName}]`);
}
if (value) {
el.setAttribute(this.id, '');
} else {
el.removeAttribute(this.id);
}
},
remove: function () {
this.system.unsubscribe(this);
}
});
module.exports = {
composeFunctions: lib.composeFunctions,
composeHandlers: lib.composeHandlers,
select: lib.select
};
|
webpackHotUpdate_N_E(1,{
/***/ "./src/container/menu/menuList.tsx":
/*!*****************************************!*\
!*** ./src/container/menu/menuList.tsx ***!
\*****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(module) {/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-redux */ "./node_modules/react-redux/es/index.js");
/* harmony import */ var _actions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../actions */ "./src/actions/index.tsx");
/* harmony import */ var _addMenu__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./addMenu */ "./src/container/menu/addMenu.tsx");
/* harmony import */ var _component_Food__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../component/Food */ "./src/component/Food.tsx");
/* harmony import */ var _constants_Confirm__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../constants/Confirm */ "./src/constants/Confirm.tsx");
var _jsxFileName = "C:\\Program Files (x86)\\Ampps\\www\\auckland-shop-chatbot-admin\\src\\container\\menu\\menuList.tsx",
_this = undefined,
_s = $RefreshSig$();
var __jsx = react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement;
var MenuList = function MenuList(_ref) {
_s();
var match = _ref.match,
menu = _ref.menu,
fetch_menus = _ref.fetch_menus,
deleteMenu = _ref.deleteMenu,
open = _ref.open;
var _useState = Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(0),
id = _useState[0],
setID = _useState[1];
var dispatch = Object(react_redux__WEBPACK_IMPORTED_MODULE_2__["useDispatch"])();
Object(react__WEBPACK_IMPORTED_MODULE_1__["useEffect"])(function () {
fetch_menus(match.params.id);
}, []);
var delete_menu = function delete_menu(id) {
open();
setID(id);
};
var renderPosts = function renderPosts() {
return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(menu, function (item) {
return __jsx("span", {
key: item.idmenu,
__self: _this,
__source: {
fileName: _jsxFileName,
lineNumber: 40,
columnNumber: 5
}
}, __jsx(_component_Food__WEBPACK_IMPORTED_MODULE_5__["default"], {
onDelete: function onDelete() {
return delete_menu(item.idmenu);
},
label: item.menu_name,
__self: _this,
__source: {
fileName: _jsxFileName,
lineNumber: 43,
columnNumber: 6
}
}));
});
};
return __jsx("div", {
__self: _this,
__source: {
fileName: _jsxFileName,
lineNumber: 53,
columnNumber: 3
}
}, menu.length > 0 && renderPosts(), __jsx(_addMenu__WEBPACK_IMPORTED_MODULE_4__["default"], {
shop_id: match.params.id,
__self: _this,
__source: {
fileName: _jsxFileName,
lineNumber: 55,
columnNumber: 4
}
}), __jsx(_constants_Confirm__WEBPACK_IMPORTED_MODULE_6__["default"], {
submit: function submit() {
return deleteMenu(id, match.params.id);
},
title: "Are you sure to delete?",
__self: _this,
__source: {
fileName: _jsxFileName,
lineNumber: 56,
columnNumber: 4
}
}));
};
_s(MenuList, "4oPvDkCq3PiC56wt/yK57c97ucQ=", false, function () {
return [react_redux__WEBPACK_IMPORTED_MODULE_2__["useDispatch"]];
});
_c = MenuList;
var mapStateToProps = function mapStateToProps(state) {
return {
menu: state.menu
};
};
var mapDispatchToProps = function mapDispatchToProps(dispatch) {
return {
fetch_menus: function fetch_menus(id) {
dispatch(Object(_actions__WEBPACK_IMPORTED_MODULE_3__["fetchMenus"])(id));
},
deleteMenu: function deleteMenu(menuid, shopid) {
dispatch(Object(_actions__WEBPACK_IMPORTED_MODULE_3__["deleteMenu"])(menuid, shopid));
},
open: function open() {
dispatch(Object(_actions__WEBPACK_IMPORTED_MODULE_3__["confirm"])(true));
}
};
};
/* harmony default export */ __webpack_exports__["default"] = (Object(react_redux__WEBPACK_IMPORTED_MODULE_2__["connect"])(mapStateToProps, mapDispatchToProps)(MenuList));
var _c;
$RefreshReg$(_c, "MenuList");
;
var _a, _b;
// Legacy CSS implementations will `eval` browser code in a Node.js context
// to extract CSS. For backwards compatibility, we need to check we're in a
// browser context before continuing.
if (typeof self !== 'undefined' &&
// AMP / No-JS mode does not inject these helpers:
'$RefreshHelpers$' in self) {
var currentExports = module.__proto__.exports;
var prevExports = (_b = (_a = module.hot.data) === null || _a === void 0 ? void 0 : _a.prevExports) !== null && _b !== void 0 ? _b : null;
// This cannot happen in MainTemplate because the exports mismatch between
// templating and execution.
self.$RefreshHelpers$.registerExportsForReactRefresh(currentExports, module.i);
// A module can be accepted automatically based on its exports, e.g. when
// it is a Refresh Boundary.
if (self.$RefreshHelpers$.isReactRefreshBoundary(currentExports)) {
// Save the previous exports on update so we can compare the boundary
// signatures.
module.hot.dispose(function (data) {
data.prevExports = currentExports;
});
// Unconditionally accept an update to this module, we'll check if it's
// still a Refresh Boundary later.
module.hot.accept();
// This field is set when the previous version of this module was a
// Refresh Boundary, letting us know we need to check for invalidation or
// enqueue an update.
if (prevExports !== null) {
// A boundary can become ineligible if its exports are incompatible
// with the previous exports.
//
// For example, if you add/remove/change exports, we'll want to
// re-execute the importing modules, and force those components to
// re-render. Similarly, if you convert a class component to a
// function, we want to invalidate the boundary.
if (self.$RefreshHelpers$.shouldInvalidateReactRefreshBoundary(prevExports, currentExports)) {
module.hot.invalidate();
}
else {
self.$RefreshHelpers$.scheduleUpdate();
}
}
}
else {
// Since we just executed the code for the module, it's possible that the
// new exports made it ineligible for being a boundary.
// We only care about the case when we were _previously_ a boundary,
// because we already accepted this update (accidental side effect).
var isNoLongerABoundary = prevExports !== null;
if (isNoLongerABoundary) {
module.hot.invalidate();
}
}
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/harmony-module.js */ "./node_modules/webpack/buildin/harmony-module.js")(module)))
/***/ })
})
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly9fTl9FLy4vc3JjL2NvbnRhaW5lci9tZW51L21lbnVMaXN0LnRzeCJdLCJuYW1lcyI6WyJNZW51TGlzdCIsIm1hdGNoIiwibWVudSIsImZldGNoX21lbnVzIiwiZGVsZXRlTWVudSIsIm9wZW4iLCJ1c2VTdGF0ZSIsImlkIiwic2V0SUQiLCJkaXNwYXRjaCIsInVzZURpc3BhdGNoIiwidXNlRWZmZWN0IiwicGFyYW1zIiwiZGVsZXRlX21lbnUiLCJyZW5kZXJQb3N0cyIsIl8iLCJtYXAiLCJpdGVtIiwiaWRtZW51IiwibWVudV9uYW1lIiwibGVuZ3RoIiwibWFwU3RhdGVUb1Byb3BzIiwic3RhdGUiLCJtYXBEaXNwYXRjaFRvUHJvcHMiLCJmZXRjaE1lbnVzIiwibWVudWlkIiwic2hvcGlkIiwiY29uZmlybSIsImNvbm5lY3QiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFBQTtBQUNBO0FBQ0E7QUFHQTtBQUVBO0FBQ0E7QUFDQTs7QUFlQSxJQUFNQSxRQUE0QyxHQUFHLFNBQS9DQSxRQUErQyxPQUFvRDtBQUFBOztBQUFBLE1BQWpEQyxLQUFpRCxRQUFqREEsS0FBaUQ7QUFBQSxNQUExQ0MsSUFBMEMsUUFBMUNBLElBQTBDO0FBQUEsTUFBcENDLFdBQW9DLFFBQXBDQSxXQUFvQztBQUFBLE1BQXZCQyxVQUF1QixRQUF2QkEsVUFBdUI7QUFBQSxNQUFYQyxJQUFXLFFBQVhBLElBQVc7O0FBQUEsa0JBQ3BGQyxzREFBUSxDQUFDLENBQUQsQ0FENEU7QUFBQSxNQUNqR0MsRUFEaUc7QUFBQSxNQUM3RkMsS0FENkY7O0FBRXhHLE1BQU1DLFFBQVEsR0FBR0MsK0RBQVcsRUFBNUI7QUFFQUMseURBQVMsQ0FBQyxZQUFNO0FBQ2ZSLGVBQVcsQ0FBQ0YsS0FBSyxDQUFDVyxNQUFOLENBQWFMLEVBQWQsQ0FBWDtBQUNBLEdBRlEsRUFFUCxFQUZPLENBQVQ7O0FBSUEsTUFBTU0sV0FBVyxHQUFHLFNBQWRBLFdBQWMsQ0FBQ04sRUFBRCxFQUFRO0FBQzNCRixRQUFJO0FBQ0pHLFNBQUssQ0FBQ0QsRUFBRCxDQUFMO0FBQ0EsR0FIRDs7QUFJQSxNQUFNTyxXQUFXLEdBQUcsU0FBZEEsV0FBYyxHQUFNO0FBQ3pCLFdBQU9DLDZDQUFDLENBQUNDLEdBQUYsQ0FBTWQsSUFBTixFQUFZLFVBQUFlLElBQUksRUFBSTtBQUMxQixhQUNDO0FBQ0MsV0FBRyxFQUFFQSxJQUFJLENBQUNDLE1BRFg7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxTQUdDLE1BQUMsdURBQUQ7QUFDQyxnQkFBUSxFQUFFO0FBQUEsaUJBQU1MLFdBQVcsQ0FBQ0ksSUFBSSxDQUFDQyxNQUFOLENBQWpCO0FBQUEsU0FEWDtBQUVDLGFBQUssRUFBRUQsSUFBSSxDQUFDRSxTQUZiO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsUUFIRCxDQUREO0FBVUEsS0FYTSxDQUFQO0FBWUEsR0FiRDs7QUFlQSxTQUNDO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsS0FDR2pCLElBQUksQ0FBQ2tCLE1BQUwsR0FBYyxDQUFkLElBQW1CTixXQUFXLEVBRGpDLEVBRUMsTUFBQyxnREFBRDtBQUFTLFdBQU8sRUFBRWIsS0FBSyxDQUFDVyxNQUFOLENBQWFMLEVBQS9CO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsSUFGRCxFQUdDLE1BQUMsMERBQUQ7QUFDQyxVQUFNLEVBQUU7QUFBQSxhQUFNSCxVQUFVLENBQUNHLEVBQUQsRUFBS04sS0FBSyxDQUFDVyxNQUFOLENBQWFMLEVBQWxCLENBQWhCO0FBQUEsS0FEVDtBQUVDLFNBQUssRUFBQyx5QkFGUDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLElBSEQsQ0FERDtBQVVBLENBckNEOztHQUFNUCxRO1VBRVlVLHVEOzs7S0FGWlYsUTs7QUF1Q04sSUFBTXFCLGVBQWUsR0FBRyxTQUFsQkEsZUFBa0IsQ0FBQUMsS0FBSztBQUFBLFNBQUs7QUFDOUJwQixRQUFJLEVBQUVvQixLQUFLLENBQUNwQjtBQURrQixHQUFMO0FBQUEsQ0FBN0I7O0FBR0EsSUFBTXFCLGtCQUFrQixHQUFHLFNBQXJCQSxrQkFBcUIsQ0FBQ2QsUUFBRCxFQUFrRDtBQUN6RSxTQUFPO0FBQ0hOLGVBQVcsRUFBRSxxQkFBQ0ksRUFBRCxFQUFRO0FBQ2pCRSxjQUFRLENBQUNlLDJEQUFVLENBQUNqQixFQUFELENBQVgsQ0FBUjtBQUNILEtBSEU7QUFJSEgsY0FBVSxFQUFFLG9CQUFDcUIsTUFBRCxFQUFTQyxNQUFULEVBQW9CO0FBQzVCakIsY0FBUSxDQUFDTCwyREFBVSxDQUFDcUIsTUFBRCxFQUFTQyxNQUFULENBQVgsQ0FBUjtBQUNILEtBTkU7QUFPVHJCLFFBQUksRUFBRSxnQkFBTTtBQUNYSSxjQUFRLENBQUNrQix3REFBTyxDQUFDLElBQUQsQ0FBUixDQUFSO0FBQ0E7QUFUUSxHQUFQO0FBV0gsQ0FaRDs7QUFjZUMsMEhBQU8sQ0FBQ1AsZUFBRCxFQUFrQkUsa0JBQWxCLENBQVAsQ0FBNkN2QixRQUE3QyxDQUFmIiwiZmlsZSI6InN0YXRpYy93ZWJwYWNrLzEuM2NlM2QxMmM1MDc2MjJhNWY1NTYuaG90LXVwZGF0ZS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBfIGZyb20gJ2xvZGFzaCc7XHJcbmltcG9ydCBSZWFjdCwgeyB1c2VTdGF0ZSwgdXNlRWZmZWN0LCBDb21wb25lbnQgfSBmcm9tICdyZWFjdCc7XHJcbmltcG9ydCB7IGNvbm5lY3QsIHVzZVNlbGVjdG9yLCB1c2VEaXNwYXRjaCB9IGZyb20gJ3JlYWN0LXJlZHV4JztcclxuaW1wb3J0IHsgVGh1bmtEaXNwYXRjaCB9IGZyb20gXCJyZWR1eC10aHVua1wiO1xyXG5pbXBvcnQgeyBBbnlBY3Rpb24gfSBmcm9tIFwicmVkdXhcIjtcclxuaW1wb3J0IHsgZmV0Y2hNZW51cywgZGVsZXRlTWVudSwgY29uZmlybSB9IGZyb20gJy4uLy4uL2FjdGlvbnMnO1xyXG5cclxuaW1wb3J0IEFkZE1lbnUgZnJvbSAnLi9hZGRNZW51JztcclxuaW1wb3J0IEZvb2QgZnJvbSAnLi4vLi4vY29tcG9uZW50L0Zvb2QnO1xyXG5pbXBvcnQgQ29uZmlybSBmcm9tICcuLi8uLi9jb25zdGFudHMvQ29uZmlybSc7XHJcblxyXG5pbnRlcmZhY2UgUHJvcHNGcm9tU3RhdGUge1xyXG5cdG1hdGNoOiBhbnksXHJcblx0bWVudTogYW55XHJcbn1cclxuICBcclxuaW50ZXJmYWNlIHByb3BzRnJvbURpc3BhdGNoIHtcclxuXHRmZXRjaF9tZW51czogKGlkOiBudW1iZXIpID0+IHZvaWQsXHJcblx0ZGVsZXRlTWVudTogKG1lbnVpZDogbnVtYmVyLCBzaG9waWQ6IG51bWJlcikgPT4gdm9pZCxcclxuXHRvcGVuOiAoKSA9PiB2b2lkXHJcbn1cclxuXHJcbnR5cGUgQWxsUHJvcHMgPSBQcm9wc0Zyb21TdGF0ZSAmIHByb3BzRnJvbURpc3BhdGNoO1xyXG5cclxuY29uc3QgTWVudUxpc3QgOiBSZWFjdC5GdW5jdGlvbkNvbXBvbmVudDxBbGxQcm9wcz4gPSAoeyBtYXRjaCwgbWVudSwgZmV0Y2hfbWVudXMsIGRlbGV0ZU1lbnUsIG9wZW4gfSkgPT4ge1xyXG5cdGNvbnN0IFtpZCwgc2V0SURdID0gdXNlU3RhdGUoMCk7XHJcblx0Y29uc3QgZGlzcGF0Y2ggPSB1c2VEaXNwYXRjaCgpO1xyXG5cclxuXHR1c2VFZmZlY3QoKCkgPT4ge1xyXG5cdFx0ZmV0Y2hfbWVudXMobWF0Y2gucGFyYW1zLmlkKTtcclxuXHR9LFtdKVxyXG5cclxuXHRjb25zdCBkZWxldGVfbWVudSA9IChpZCkgPT4ge1xyXG5cdFx0b3BlbigpXHJcblx0XHRzZXRJRChpZClcclxuXHR9XHJcblx0Y29uc3QgcmVuZGVyUG9zdHMgPSAoKSA9PiB7XHJcblx0XHRyZXR1cm4gXy5tYXAobWVudSwgaXRlbSA9PiB7XHJcblx0XHRcdHJldHVybiAoXHJcblx0XHRcdFx0PHNwYW5cclxuXHRcdFx0XHRcdGtleT17aXRlbS5pZG1lbnV9XHJcblx0XHRcdFx0PlxyXG5cdFx0XHRcdFx0PEZvb2RcclxuXHRcdFx0XHRcdFx0b25EZWxldGU9eygpID0+IGRlbGV0ZV9tZW51KGl0ZW0uaWRtZW51KX1cclxuXHRcdFx0XHRcdFx0bGFiZWw9e2l0ZW0ubWVudV9uYW1lfVxyXG5cdFx0XHRcdFx0Lz5cclxuXHRcdFx0XHQ8L3NwYW4+XHJcblx0XHRcdCk7XHJcblx0XHR9KTtcclxuXHR9XHJcblxyXG5cdHJldHVybihcclxuXHRcdDxkaXY+XHJcblx0XHRcdHsgbWVudS5sZW5ndGggPiAwICYmIHJlbmRlclBvc3RzKCl9XHJcblx0XHRcdDxBZGRNZW51IHNob3BfaWQ9e21hdGNoLnBhcmFtcy5pZH0gLz5cclxuXHRcdFx0PENvbmZpcm1cclxuXHRcdFx0XHRzdWJtaXQ9eygpID0+IGRlbGV0ZU1lbnUoaWQsIG1hdGNoLnBhcmFtcy5pZCl9XHJcblx0XHRcdFx0dGl0bGU9XCJBcmUgeW91IHN1cmUgdG8gZGVsZXRlP1wiXHJcblx0XHRcdC8+XHJcblx0XHQ8L2Rpdj5cclxuXHQpO1xyXG59XHJcblxyXG5jb25zdCBtYXBTdGF0ZVRvUHJvcHMgPSBzdGF0ZSA9PiAoe1xyXG4gICAgbWVudTogc3RhdGUubWVudVxyXG59KTtcclxuY29uc3QgbWFwRGlzcGF0Y2hUb1Byb3BzID0gKGRpc3BhdGNoOiBUaHVua0Rpc3BhdGNoPGFueSwgYW55LCBBbnlBY3Rpb24+KSA9PiB7XHJcbiAgICByZXR1cm4ge1xyXG4gICAgICAgIGZldGNoX21lbnVzOiAoaWQpID0+IHtcclxuICAgICAgICAgICAgZGlzcGF0Y2goZmV0Y2hNZW51cyhpZCkpO1xyXG4gICAgICAgIH0sXHJcbiAgICAgICAgZGVsZXRlTWVudTogKG1lbnVpZCwgc2hvcGlkKSA9PiB7XHJcbiAgICAgICAgICAgIGRpc3BhdGNoKGRlbGV0ZU1lbnUobWVudWlkLCBzaG9waWQpKTtcclxuICAgICAgICB9LFxyXG5cdFx0b3BlbjogKCkgPT4ge1xyXG5cdFx0XHRkaXNwYXRjaChjb25maXJtKHRydWUpKTtcclxuXHRcdH1cclxuICAgIH1cclxufVxyXG5cclxuZXhwb3J0IGRlZmF1bHQgY29ubmVjdChtYXBTdGF0ZVRvUHJvcHMsIG1hcERpc3BhdGNoVG9Qcm9wcykoTWVudUxpc3QpXHJcbiJdLCJzb3VyY2VSb290IjoiIn0=
|
import clone from 'clone';
import equal from 'deep-equal';
import extend from 'extend';
import Delta, { AttributeMap } from 'quill-delta';
import { LeafBlot } from 'parchment';
import { Range } from './selection';
import CursorBlot from '../blots/cursor';
import Block, { BlockEmbed, bubbleFormats } from '../blots/block';
import Break from '../blots/break';
import TextBlot, { escapeText } from '../blots/text';
const ASCII = /^[ -~]*$/;
class Editor {
constructor(scroll) {
this.scroll = scroll;
this.delta = this.getDelta();
}
applyDelta(delta) {
let consumeNextNewline = false;
this.scroll.update();
let scrollLength = this.scroll.length();
this.scroll.batchStart();
const normalizedDelta = normalizeDelta(delta);
normalizedDelta.reduce((index, op) => {
const length = op.retain || op.delete || op.insert.length || 1;
let attributes = op.attributes || {};
if (op.insert != null) {
if (typeof op.insert === 'string') {
let text = op.insert;
if (text.endsWith('\n') && consumeNextNewline) {
consumeNextNewline = false;
text = text.slice(0, -1);
}
if (
(index >= scrollLength ||
this.scroll.descendant(BlockEmbed, index)[0]) &&
!text.endsWith('\n')
) {
consumeNextNewline = true;
}
this.scroll.insertAt(index, text);
const [line, offset] = this.scroll.line(index);
let formats = extend({}, bubbleFormats(line));
if (line instanceof Block) {
const [leaf] = line.descendant(LeafBlot, offset);
formats = extend(formats, bubbleFormats(leaf));
}
attributes = AttributeMap.diff(formats, attributes) || {};
} else if (typeof op.insert === 'object') {
const key = Object.keys(op.insert)[0]; // There should only be one key
if (key == null) return index;
this.scroll.insertAt(index, key, op.insert[key]);
}
scrollLength += length;
}
Object.keys(attributes).forEach(name => {
this.scroll.formatAt(index, length, name, attributes[name]);
});
return index + length;
}, 0);
normalizedDelta.reduce((index, op) => {
if (typeof op.delete === 'number') {
this.scroll.deleteAt(index, op.delete);
return index;
}
return index + (op.retain || op.insert.length || 1);
}, 0);
this.scroll.batchEnd();
this.scroll.optimize();
return this.update(normalizedDelta);
}
deleteText(index, length) {
this.scroll.deleteAt(index, length);
return this.update(new Delta().retain(index).delete(length));
}
formatLine(index, length, formats = {}) {
this.scroll.update();
Object.keys(formats).forEach(format => {
this.scroll.lines(index, Math.max(length, 1)).forEach(line => {
line.format(format, formats[format]);
});
});
this.scroll.optimize();
const delta = new Delta().retain(index).retain(length, clone(formats));
return this.update(delta);
}
formatText(index, length, formats = {}) {
Object.keys(formats).forEach(format => {
this.scroll.formatAt(index, length, format, formats[format]);
});
const delta = new Delta().retain(index).retain(length, clone(formats));
return this.update(delta);
}
getContents(index, length) {
return this.delta.slice(index, index + length);
}
getDelta() {
return this.scroll.lines().reduce((delta, line) => {
return delta.concat(line.delta());
}, new Delta());
}
getFormat(index, length = 0) {
let lines = [];
let leaves = [];
if (length === 0) {
this.scroll.path(index).forEach(path => {
const [blot] = path;
if (blot instanceof Block) {
lines.push(blot);
} else if (blot instanceof LeafBlot) {
leaves.push(blot);
}
});
} else {
lines = this.scroll.lines(index, length);
leaves = this.scroll.descendants(LeafBlot, index, length);
}
const formatsArr = [lines, leaves].map(blots => {
if (blots.length === 0) return {};
let formats = bubbleFormats(blots.shift());
while (Object.keys(formats).length > 0) {
const blot = blots.shift();
if (blot == null) return formats;
formats = combineFormats(bubbleFormats(blot), formats);
}
return formats;
});
return extend.apply(extend, formatsArr);
}
getHTML(index, length) {
const [line, lineOffset] = this.scroll.line(index);
if (line.length() >= lineOffset + length) {
return convertHTML(line, lineOffset, length, true);
}
return convertHTML(this.scroll, index, length, true);
}
getText(index, length) {
return this.getContents(index, length)
.filter(op => typeof op.insert === 'string')
.map(op => op.insert)
.join('');
}
insertEmbed(index, embed, value) {
this.scroll.insertAt(index, embed, value);
return this.update(new Delta().retain(index).insert({ [embed]: value }));
}
insertText(index, text, formats = {}) {
text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
this.scroll.insertAt(index, text);
Object.keys(formats).forEach(format => {
this.scroll.formatAt(index, text.length, format, formats[format]);
});
return this.update(new Delta().retain(index).insert(text, clone(formats)));
}
isBlank() {
if (this.scroll.children.length === 0) return true;
if (this.scroll.children.length > 1) return false;
const block = this.scroll.children.head;
if (block.statics.blotName !== Block.blotName) return false;
if (block.children.length > 1) return false;
return block.children.head instanceof Break;
}
removeFormat(index, length) {
const text = this.getText(index, length);
const [line, offset] = this.scroll.line(index + length);
let suffixLength = 0;
let suffix = new Delta();
if (line != null) {
suffixLength = line.length() - offset;
suffix = line
.delta()
.slice(offset, offset + suffixLength - 1)
.insert('\n');
}
const contents = this.getContents(index, length + suffixLength);
const diff = contents.diff(new Delta().insert(text).concat(suffix));
const delta = new Delta().retain(index).concat(diff);
return this.applyDelta(delta);
}
update(change, mutations = [], selectionInfo = undefined) {
const oldDelta = this.delta;
if (
mutations.length === 1 &&
mutations[0].type === 'characterData' &&
mutations[0].target.data.match(ASCII) &&
this.scroll.find(mutations[0].target)
) {
// Optimization for character changes
const textBlot = this.scroll.find(mutations[0].target);
const formats = bubbleFormats(textBlot);
const index = textBlot.offset(this.scroll);
const oldValue = mutations[0].oldValue.replace(CursorBlot.CONTENTS, '');
const oldText = new Delta().insert(oldValue);
const newText = new Delta().insert(textBlot.value());
const relativeSelectionInfo = selectionInfo && [
new Range(selectionInfo[0].index - index, selectionInfo[0].length),
new Range(selectionInfo[1].index - index, selectionInfo[1].length),
];
const diffDelta = new Delta()
.retain(index)
.concat(diffDeltas(oldText, newText, relativeSelectionInfo));
change = diffDelta.reduce((delta, op) => {
if (op.insert) {
return delta.insert(op.insert, formats);
}
return delta.push(op);
}, new Delta());
this.delta = oldDelta.compose(change);
} else {
this.delta = this.getDelta();
if (!change || !equal(oldDelta.compose(change), this.delta)) {
change = diffDeltas(oldDelta, this.delta, selectionInfo);
}
}
return change;
}
}
function convertListHTML(items, lastIndent, types) {
if (items.length === 0) {
const [endTag] = getListType(types.pop());
if (lastIndent <= 0) {
return `</li></${endTag}>`;
}
return `</li></${endTag}>${convertListHTML([], lastIndent - 1, types)}`;
}
const [{ child, offset, length, indent, type }, ...rest] = items;
const [tag, attribute] = getListType(type);
if (indent > lastIndent) {
types.push(type);
return `<${tag}><li${attribute}>${convertHTML(
child,
offset,
length,
)}${convertListHTML(rest, indent, types)}`;
}
if (indent === lastIndent) {
return `</li><li${attribute}>${convertHTML(
child,
offset,
length,
)}${convertListHTML(rest, indent, types)}`;
}
const [endTag] = getListType(types.pop());
return `</li></${endTag}>${convertListHTML(items, lastIndent - 1, types)}`;
}
function convertHTML(blot, index, length, isRoot = false) {
if (typeof blot.html === 'function') {
return blot.html(index, length);
}
if (blot instanceof TextBlot) {
return escapeText(blot.value().slice(index, index + length));
}
if (blot.children) {
// TODO fix API
if (blot.statics.blotName === 'list-container') {
const items = [];
blot.children.forEachAt(index, length, (child, offset, childLength) => {
const formats = child.formats();
items.push({
child,
offset,
length: childLength,
indent: formats.indent || 0,
type: formats.list,
});
});
return convertListHTML(items, -1, []);
}
const parts = [];
blot.children.forEachAt(index, length, (child, offset, childLength) => {
parts.push(convertHTML(child, offset, childLength));
});
if (isRoot || blot.statics.blotName === 'list') {
return parts.join('');
}
const { outerHTML, innerHTML } = blot.domNode;
const [start, end] = outerHTML.split(`>${innerHTML}<`);
// TODO cleanup
if (start === '<table') {
return `<table style="border: 1px solid #000;">${parts.join('')}<${end}`;
}
return `${start}>${parts.join('')}<${end}`;
}
return blot.domNode.outerHTML;
}
function combineFormats(formats, combined) {
return Object.keys(combined).reduce((merged, name) => {
if (formats[name] == null) return merged;
if (combined[name] === formats[name]) {
merged[name] = combined[name];
} else if (Array.isArray(combined[name])) {
if (combined[name].indexOf(formats[name]) < 0) {
merged[name] = combined[name].concat([formats[name]]);
}
} else {
merged[name] = [combined[name], formats[name]];
}
return merged;
}, {});
}
function getListType(type) {
const tag = type === 'ordered' ? 'ol' : 'ul';
switch (type) {
case 'checked':
return [tag, ' data-list="checked"'];
case 'unchecked':
return [tag, ' data-list="unchecked"'];
default:
return [tag, ''];
}
}
function normalizeDelta(delta) {
return delta.reduce((normalizedDelta, op) => {
if (typeof op.insert === 'string') {
const text = op.insert.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
return normalizedDelta.insert(text, op.attributes);
}
return normalizedDelta.push(op);
}, new Delta());
}
function splitDelta(delta, index) {
return [delta.slice(0, index), delta.slice(index)];
}
function diffDeltas(oldDelta, newDelta, selectionInfo = undefined) {
if (selectionInfo == null) {
return oldDelta.diff(newDelta);
}
// generate better diffs than Delta#diff by taking into account the
// old and new selection. for example, a text change from "xxx" to "xx"
// could be a delete or forwards-delete of any one of the x's, or the
// result of selecting two of the x's and typing "x".
const [oldSelection, newSelection] = selectionInfo;
const oldDeltaLength = oldDelta.length();
const newDeltaLength = newDelta.length();
if (oldSelection.length === 0 && newSelection.length === 0) {
// see if we have an insert or delete before or after cursor
const oldCursor = oldSelection.index;
const newCursor = newSelection.index;
const [oldBefore, oldAfter] = splitDelta(oldDelta, oldCursor);
const [newBefore, newAfter] = splitDelta(newDelta, newCursor);
if (equal(oldAfter, newAfter)) {
const prefixLength = Math.min(oldCursor, newCursor);
const [oldPrefix, oldMiddle] = splitDelta(oldBefore, prefixLength);
const [newPrefix, newMiddle] = splitDelta(newBefore, prefixLength);
if (equal(oldPrefix, newPrefix)) {
// insert or delete right before cursor
return new Delta()
.retain(prefixLength)
.concat(oldMiddle.diff(newMiddle));
}
} else if (equal(oldBefore, newBefore)) {
const suffixLength = Math.min(
oldDeltaLength - oldCursor,
newDeltaLength - newCursor,
);
const [oldMiddle, oldSuffix] = splitDelta(
oldAfter,
oldDeltaLength - oldCursor - suffixLength,
);
const [newMiddle, newSuffix] = splitDelta(
newAfter,
newDeltaLength - newCursor - suffixLength,
);
if (equal(oldSuffix, newSuffix)) {
// insert or delete right after cursor
return new Delta().retain(oldCursor).concat(oldMiddle.diff(newMiddle));
}
}
}
if (oldSelection.length > 0 && newSelection.length === 0) {
// see if diff could be a splice of the old selection range
const oldPrefix = oldDelta.slice(0, oldSelection.index);
const oldSuffix = oldDelta.slice(oldSelection.index + oldSelection.length);
const prefixLength = oldPrefix.length();
const suffixLength = oldSuffix.length();
if (newDeltaLength >= prefixLength + suffixLength) {
const newPrefix = newDelta.slice(0, prefixLength);
const newSuffix = newDelta.slice(newDeltaLength - suffixLength);
if (equal(oldPrefix, newPrefix) && equal(oldSuffix, newSuffix)) {
const oldMiddle = oldDelta.slice(
prefixLength,
oldDeltaLength - suffixLength,
);
const newMiddle = newDelta.slice(
prefixLength,
newDeltaLength - suffixLength,
);
return new Delta()
.retain(prefixLength)
.concat(newMiddle)
.delete(oldMiddle.length());
}
}
}
return oldDelta.diff(newDelta);
}
export default Editor;
|
/*!
* Quasar Framework v1.14.0
* (c) 2015-present Razvan Stoenescu
* Released under the MIT License.
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):((e=e||self).Quasar=e.Quasar||{},e.Quasar.lang=e.Quasar.lang||{},e.Quasar.lang.ru=t())}(this,function(){"use strict";return{isoName:"ru",nativeName:"русский",label:{clear:"Очистить",ok:"OK",cancel:"Отмена",close:"Закрыть",set:"Установить",select:"Выбрать",reset:"Сбросить",remove:"Удалить",update:"Обновить",create:"Создать",search:"Поиск",filter:"Фильтр",refresh:"Обновить"},date:{days:"Воскресенье_Понедельник_Вторник_Среда_Четверг_Пятница_Суббота".split("_"),daysShort:"Вс_Пн_Вт_Ср_Чт_Пт_Сб".split("_"),months:"Январь_Февраль_Март_Апрель_Май_Июнь_Июль_Август_Сентябрь_Октябрь_Ноябрь_Декабрь".split("_"),monthsShort:"Янв_Фев_Мар_Апр_Май_Июн_Июл_Авг_Сен_Окт_Ноя_Дек".split("_"),firstDayOfWeek:1,format24h:!0,pluralDay:"дней"},table:{noData:"Нет данных",noResults:"Совпадений не найдено",loading:"Загрузка...",selectedRecords:function(e){return e>0?e+" "+["строка выбрана","строки выбраны","строк выбрано"][(t=e)%10==1&&t%100!=11?0:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?1:2]+".":"Ни одна строка не выбрана.";var t},recordsPerPage:"Строк на странице:",allRows:"Все",pagination:function(e,t,r){return e+"-"+t+" из "+r},columns:"Колонки"},editor:{url:"URL",bold:"Полужирный",italic:"Курсив",strikethrough:"Зачеркнутый",underline:"Подчеркнутый",unorderedList:"Маркированный список",orderedList:"Нумерованный список",subscript:"Подстрочный",superscript:"Надстрочный",hyperlink:"Гиперссылка",toggleFullscreen:"Полноэкранный режим",quote:"Цитата",left:"Выравнивание по левому краю",center:"Выравнивание по центру",right:"Выравнивание по правому краю",justify:"Выравнивание по ширине",print:"Печать",outdent:"Уменьшить отступ",indent:"Увеличить отступ",removeFormat:"Удалить форматирование",formatting:"Форматирование",fontSize:"Размер шрифта",align:"Выравнивание",hr:"Вставить горизонтальную линию",undo:"Отменить",redo:"Повторить",heading1:"Заголовок 1",heading2:"Заголовок 2",heading3:"Заголовок 3",heading4:"Заголовок 4",heading5:"Заголовок 5",heading6:"Заголовок 6",paragraph:"Параграф",code:"Код",size1:"Очень маленький",size2:"Маленький",size3:"Нормальный",size4:"Средний",size5:"Большой",size6:"Очень большой",size7:"Огромный",defaultFont:"Шрифт по умолчанию",viewSource:"Просмотреть исходный код"},tree:{noNodes:"Нет доступных узлов",noResults:"Совпадений не найдено"}}});
|
import React from 'react';
import Button from '@material-ui/core/Button';
import Snackbar from '@material-ui/core/Snackbar';
import MuiAlert from '@material-ui/lab/Alert';
import { makeStyles } from '@material-ui/core/styles';
function Alert(props) {
return <MuiAlert elevation={6} variant="filled" {...props} />;
}
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
'& > * + *': {
marginTop: theme.spacing(2),
},
},
}));
export default function CustomizedSnackbars(props) {
const classes = useStyles();
const [open, setOpen] = React.useState(false);
const handleClick = () => {
setOpen(true);
};
const handleClose = (event, reason) => {
if (reason === 'clickaway') {
return;
}
setOpen(false);
};
return (
<div className={classes.root}>
<div className="m-3">
{props.type==="success"&&<Alert severity="success">{props.text}</Alert>}
{props.type==="warning"&&<Alert severity="warning">{props.text}</Alert>}
{props.type==="info"&&<Alert severity="info">{props.text}</Alert>}
{props.type==="error"&&<Alert severity="error">{props.text}</Alert>}
</div>
</div>
);
}
|
const magick = require("../build/Release/image.node");
const { promisify } = require("util");
exports.run = async (message) => {
message.channel.sendTyping();
const image = await require("../utils/imagedetect.js")(message);
if (image === undefined) return `${message.author.mention}, you need to provide an image to swirl!`;
const buffer = await promisify(magick.swirl)(image.path, image.type.toUpperCase(), image.delay ? (100 / image.delay.split("/")[0]) * image.delay.split("/")[1] : 0);
return {
file: buffer,
name: `swirl.${image.type}`
};
};
exports.aliases = ["whirlpool"];
exports.category = 5;
exports.help = "Swirls an image";
|
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import store from "data/store"
import axios from "axios";
import { useCookies } from 'react-cookie';
import { useForm } from "react-hook-form";
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
//rsuite
import { Toggle } from 'rsuite';
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
export default function CardUserSettings(props) {
const data = props.data;
const { register, control, formState: { errors }, handleSubmit, setValue } = useForm();
const [cookies, setCookie] = useCookies();
const [fileInfo, setFileInfo] = React.useState(null);
const [uploading, setUploading] = React.useState(false);
const [published, setPublished] = useState((data['published'] == null) ? null : data['published'])
const [submit, setSubmit] = React.useState(false);
const [coachHidden, setcoachHidden] = React.useState();
const [chirdrenHidden, setchirdrenHidden] = React.useState();
const [courseEditor, setcourseEditor] = useState();
const [uploadedImages, setuploadedImages] = React.useState([]);
const [textColor, setTextColor] = React.useState("#000000");
const [backgroundcolor, setBackgroundcolor] = React.useState('#ffffff');
const handleTextColor = (e) => {
setTextColor(e.target.value)
}
const handleBackgroundcolor = (e) => {
setBackgroundcolor(e.target.value)
}
const onEditorStateChange = (editorState) => {
var data = draftToHtml(convertToRaw(editorState.getCurrentContent()))
setcourseEditor(editorState)
setValue("content", data)
}
const _uploadImageCallBack = (file) => {
const imageObject = {
file: file,
localSrc: URL.createObjectURL(file),
}
let image = []
image.push(imageObject);
setuploadedImages(image)
return new Promise(
(resolve, reject) => {
resolve({ data: { link: imageObject.localSrc } });
}
);
}
useEffect(() => {
if (data['image'] != '' && data['image'] != null) {
var value = "data:image;base64," + data['image']
setFileInfo(value)
setValue('image', data['image'])
}
if (data['content'] != null) {
const contentBlock = htmlToDraft(data['content']);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
const editorState = EditorState.createWithContent(contentState);
setcourseEditor(editorState)
setValue("courseEditor", data['content'])
}
}
setValue("upload", data['upload'])
setValue("gender", data['gender'])
switch (data['roleId']) {
case 2:
setchirdrenHidden(true);
setcoachHidden(false);
break;
case 4:
setcoachHidden(true);
setchirdrenHidden(false);
break;
default:
setchirdrenHidden(true);
setcoachHidden(true);
break;
}
}, []);
const handleChange = (e) => {
setPublished(e)
setValue("published", e)
};
const onSubmit = jsonData => {
jsonData.tagColor = jsonData.tagColor.substr(1, 6)
jsonData.textColor = jsonData.textColor.substr(1, 6)
setSubmit(true)
const headers = {
'Authorization': 'Bearer ' + cookies.token
};
jsonData.companyId = cookies.companyId
axios.post(store.webApiUrl + 'CourseLabel/Edit', jsonData, { headers })
.then(r => {
if (r.status == "200") {
setSubmit(false)
alert("儲存成功")
window.location.reload(false);
} else {
setSubmit(false)
alert("儲存失敗")
}
}).catch((error) => {
setSubmit(false)
alert("儲存失敗")
});
}
return (
<>
<div className="relative flex flex-col min-w-0 break-words w-full mb-6 shadow-lg rounded-lg bg-blueGray-100 border-0">
<form onSubmit={handleSubmit(onSubmit)}>
<div className="rounded-t bg-white mb-0 px-6 py-6">
<div className="relative w-full px-4 max-w-full flex flex-1 justify-between">
<div className="flex flex-wrap">
<h6 className="text-blueGray-700 text-xl font-bold ">課程標籤(編輯)</h6>
<Link to="/admin/user" onClick={() => window.location.reload()} className="pl-4">
<button
className="bg-emerald-500 text-white active:bg-lightBlue-600 font-bold uppercase text-xs p-4 px-4 py-2 rounded shadow hover:shadow-md outline-none focus:outline-none mr-1 ease-linear transition-all duration-150"
type="button"
>
返回
</button>
</Link>
</div>
<div className="flex flex-wrap">
<div>
<div className="pr-4">
<Toggle size="lg"
checked={published}
onChange={handleChange}
checkedChildren="已發佈"
unCheckedChildren="未發佈"
/>
</div>
<input
style={{ opacity: 0, position: "absolute" }}
defaultValue={data['published']}
{...register("published", { required: false, maxLength: 80 })}
/>
</div>
<button
className={((submit) ? "bg-lightBlue-200 " : "bg-lightBlue-500 ") + "text-white active:bg-lightBlue-600 font-bold uppercase text-xs px-4 py-2 rounded shadow hover:shadow-md outline-none focus:outline-none mr-1 ease-linear transition-all duration-150"}
type="submit"
disabled={submit}>儲存
</button>
</div>
</div>
</div>
<div className="flex-auto px-4 lg:px-10 py-10 pt-0">
<h6 className="text-blueGray-400 text-sm mt-3 mb-6 font-bold uppercase">
課程標籤資訊
</h6>
<div className="flex flex-wrap">
<input
type="text"
defaultValue={data['id']}
hidden={true}
{...register("id", { required: true, maxLength: 80 })}
/>
<div className="w-full lg:w-6/12 px-4">
<div className="relative w-full mb-3">
<label
className="block uppercase text-blueGray-600 text-xs font-bold mb-2"
htmlFor="grid-password">標籤名稱
</label>
<input
type="text"
className="border-0 px-3 py-3 placeholder-blueGray-300 text-blueGray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"
defaultValue={data['tagName']}
{...register("tagName", { required: false, maxLength: 80 })}
/>
</div>
</div>
<div className="w-full lg:w-12/12">
<div className="w-full lg:w-6/12 px-4">
<div className="relative w-full mb-3">
<label
className="block uppercase text-blueGray-600 text-xs font-bold mb-2"
htmlFor="grid-password">背景顏色
</label>
<div className="flex item-center">
<input
type="text"
className="border-0 px-3 py-3 placeholder-blueGray-300 text-blueGray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"
value={backgroundcolor}
onChange={handleBackgroundcolor}
/>
<input
type="color"
className="pt-1 w-10 h-10 border-0 ml-2 rounded relative right-12 bg-white"
value={backgroundcolor}
onChange={handleBackgroundcolor}
/>
</div>
</div>
</div>
<div className="w-full lg:w-6/12 px-4">
<div className="relative w-full mb-3">
<label
className="block uppercase text-blueGray-600 text-xs font-bold mb-2"
htmlFor="grid-password">文字顏色
</label>
<div className="flex item-center">
<input
type="text"
className="border-0 px-3 py-3 placeholder-blueGray-300 text-blueGray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"
value={textColor}
onChange={handleTextColor}
/>
<input
type="color"
className="pt-1 w-10 h-10 border-0 ml-2 rounded relative right-12 bg-white"
value={textColor}
onChange={handleTextColor}
/>
</div>
</div>
</div>
</div>
</div>
<hr className="mt-6 border-b-1 border-blueGray-300" />
<h6 className="text-blueGray-400 text-sm mt-3 mb-6 font-bold uppercase">
關於
</h6>
<div className="flex flex-wrap">
<div className="w-full lg:w-12/12 px-4">
<div className="relative w-full mb-3">
<label
className="block uppercase text-blueGray-600 text-xs font-bold mb-2"
htmlFor="grid-password">詳細內容
</label>
<div className="bg-white h-96 overflow-y-auto overflow-x-auto">
<Editor
editorState={courseEditor}
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
onEditorStateChange={onEditorStateChange}
toolbar={{
// inline: { inDropdown: true },
image: {
uploadCallback: _uploadImageCallBack,
previewImage: true,
alt: { present: true, mandatory: false },
inputAccept: 'image/gif,image/jpeg,image/jpg,image/png,image/svg',
defaultSize: {
height: '150px',
width: '150px',
},
},
}}
/>
</div>
<input
style={{ opacity: 0, position: "absolute" }}
defaultValue={data['content']}
{...register("content", { required: false })}
/>
</div>
</div>
</div>
</div>
</form>
</div>
</>
);
}
|
'use strict';
/**
* @ngdoc service
* @name troutDashApp.LinearReferenceViewModel
* @description
* # LinearReferenceViewModel
* Factory in the troutDashApp.
*/
angular.module('troutDashApp')
.factory('LinearReferenceViewModel', function () {
var StreamLineViewModel = function (lineSegment, inverseLength) {
this.lineSegment = null;
this.xOffset = 0.0;
this.width = 0.0;
this.init(lineSegment, inverseLength);
};
StreamLineViewModel.prototype.init = function(lineSegment, inverseLength) {
this.lineSegment = lineSegment;
var stop = lineSegment.Stop * inverseLength;
var start = lineSegment.Start * inverseLength;
this.xOffset = 1.0 - stop;
this.width = Math.abs(stop - start);
};
return StreamLineViewModel;
});
|
/* This file is generated by createIcons.js any changes will be lost. */
import createIcon from '../createIcon';
var MigrationIcon = createIcon({
name: 'MigrationIcon',
height: 1024,
width: 1024,
svgPath: 'M77.678 445.513c-3.657 3.657-5.486 7.973-5.486 12.8v52.809h-73.143v-55.077c0-25.161 8.923-46.665 26.99-64.658 17.847-17.847 39.57-26.99 64.658-26.99h54.857v75.41h-55.077c-5.047 0.439-9.143 2.267-12.8 5.705zM997.23 556.544c-17.847 17.847-39.57 26.99-64.658 26.99h-475.429c-4.535 0-8.997-0.293-13.385-0.878l-130.194 130.194c-15.799 15.799-21.431 13.458-40.96 17.042s-28.965-1.243-39.936-12.142-15.726-20.407-12.142-39.936c3.511-19.529 1.243-25.234 17.042-40.96l129.243-129.243c-0.878-5.047-1.243-10.313-1.243-15.653v-54.857h-146.505v-73.143h146.505v-345.381c0-25.161 8.923-46.665 26.99-64.658 17.847-17.847 39.57-26.99 64.658-26.99h475.648c25.161 0 46.665 8.923 64.658 26.99 17.847 17.847 26.99 39.57 26.99 64.658v473.381c-0.219 25.161-9.143 46.665-27.209 64.658zM951.077 18.505c0-5.047-1.829-9.143-5.486-12.8s-7.973-5.486-12.8-5.486h-475.648c-5.047 0-9.143 1.829-12.8 5.486s-5.486 7.973-5.486 12.8v416.987l185.125-185.125c0.951-0.951 1.902-1.829 2.779-2.706l-18.505-18.651-87.918-87.918c-13.166-12.727-16.165-27.355-8.923-43.959 7.241-16.969 19.749-25.454 37.595-25.454h285.477c11.045 0 20.626 4.023 28.672 12.069s12.069 17.627 12.069 28.672v285.477c0 17.847-8.265 32.695-24.869 39.936-17.408 7.168-32.256 1.902-44.617-11.264l-82.798-82.213-20.334-20.48c-0.805 0.805-1.609 1.682-2.487 2.56l-183.735 183.735h416.475c5.047 0 9.143-1.829 12.8-5.486s5.486-7.973 5.486-12.8v-473.381zM-0.951 733.038h73.143v-147.456h-73.143v147.456zM509.733 732.087h73.143v-147.456h-73.143v147.456zM25.819 925.33c-17.847-17.847-26.77-39.278-26.77-64.439v-55.735h73.143v55.735c0 5.047 1.829 9.143 5.486 12.8s7.973 5.486 12.8 5.486h55.296v73.143h-55.296c-25.161 0-46.665-8.923-64.658-26.99zM218.039 952.247h147.456v-73.143h-147.456v73.143zM505.783 873.618v0c3.657-3.657 5.486-7.973 5.486-12.8v-91.429h75.41v91.429c0 25.161-8.923 46.665-26.99 64.658-17.847 17.847-39.57 26.99-64.658 26.99h-55.515v-73.143h53.248c5.047-0.219 9.362-2.048 13.019-5.705z',
yOffset: '64',
xOffset: '',
transform: 'rotate(180 0 512) scale(-1 1)'
});
export default MigrationIcon;
|
import React from 'react'
export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
hasError: false
}
}
static getDerivedStateFromError(error) {
// console.log("getDerivedStateFromError",error);
return { hasError: true }
}
componentDidCatch(error, info) {
console.log('error, info',error, info)
}
render() {
if (this.state.hasError) {
return <div>error</div>
}
return this.props.children;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.