language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class BrowsingPageMonitor extends RemoteCallable {
constructor(name) {
super(name);
this._monitoredHost = new HostnameSet();
this._whitelistHost = new HostnameSet();
this._eventTarget = new EventTarget();
this._browseEvent = new CustomEventWrapper(
BROWSING_MONITORED_PAGE,
this._eventTarget
);
this._monitoring = true;
this._protocol = new Set(["http:", "https:"]);
// shorter name
let browseEvent = this._browseEvent;
// avoid ambiguity of "this"
let monitor = this;
onBrowsingPageChanged.addListener((tab) => {
if (!monitor.active || !tab || !tab.url) return;
console.debug(`User are browsing: ${tab.url}`);
let monitoredHost = monitor.findMonitoredSuffix(tab.url);
if (monitoredHost === undefined) return;
// Wait for a while, to allow the browser to complete tab switching
// to reduce the effect of a weird bug
window.setTimeout(() => {
browseEvent.trigger(tab, monitoredHost);
}, TAB_SWITCH_DELAY);
});
console.debug("Browsing monitor setup.");
}
/**
* @return {Set<String>} the protocol that are monitored
*/
get monitoredProtocol() {
return this._protocol;
}
/**
* @returns {boolean} If the monitor is active
*/
get active() {
return this._monitoring;
}
set active(val) {
val = Boolean(val);
this._monitoring = val;
}
/**
* find the actual monitored suffix.
* @param {string} url the URL of web page to be checked.
* @returns {(string|undefined)} the actual monitored host suffix if the web page is monitored.
* If the web page is not monitored, return undefined
*/
findMonitoredSuffix(url) {
if (!this.active) return undefined;
let urlObj = new URL(url);
if (!this.monitoredProtocol.has(urlObj.protocol)) return undefined;
if (this.whitelist.has(urlObj.hostname)) return undefined;
return this.blacklist.findSuffix(urlObj.hostname);
}
/**
* Check if a web page is monitored.
* @param {string} url the URL of web page to be checked.
* @returns {boolean} true if the tab is monitored
*/
isMonitoring(url) {
if (!this.active) return undefined;
let urlObj = new URL(url);
if (!this.monitoredProtocol.has(urlObj.protocol)) return undefined;
if (this.whitelist.has(urlObj.hostname)) return undefined;
return this.blacklist.has(urlObj.hostname);
}
/**
* Get a set of host name that are monitored.
*/
get blacklist() {
return this._monitoredHost;
}
/**
* Get a set of host name that are in the whitelist.
*/
get whitelist() {
return this._whitelistHost;
}
/**
* The event that will be triggered when user browse the host in blacklist.
*
* The callback function format for this event is:
*
* function (tab: api.tabs.Tab, hostname: String)
*
* - tab: the tab that opened a monitored host
* - hostname: the monitored hostname
*/
get onBrowse() {
return this._browseEvent;
}
/**
* A event that will be triggered whenever user browsing new page.
*
* The callback function format for this event is:
*
* function (tab: api.tabs.Tab)
*
* - tab: the tab that are current visiting
*/
static get onBrowsingPageChanged() {
return onBrowsingPageChanged;
}
} |
JavaScript | class RatingComponent extends Component {
constructor(props) {
super(props);
this.state = {
emojis: ["😡", "😠", "😤", "😐", "😑", "😃", "😍"],
emojiIcons: [angry, mad, madAngry, thinking, happy, wow, love],
rangeValue: "3",
emojiLabel: [
"Angry",
"Mad",
"Whatever",
"Confused",
" Happy",
"Wow",
"Love"
]
};
}
/**
* Triggers when the component is mounted
*/
componentDidMount() {
let emojiIcons = this.fetchEmojiCategory(this.props.variant);
this.setState({
emojiIcons
});
}
/**
* Fetches the emojis according to the category
* @param {String} category Emoji category
*/
fetchEmojiCategory = category => {
let emojiIcons = [];
switch (category) {
case "smileys":
emojiIcons = [angry, mad, madAngry, thinking, happy, wow, love];
break;
case "emojiPeople":
emojiIcons = [
ePeopleAngry,
ePeopleMad,
ePeopleMadAngry,
ePeopleThinking,
ePeopleHappy,
ePeopleWow,
ePeopleLove
];
break;
case "emoticons":
emojiIcons = [
emoticonsAngry,
emoticonsMadAngry,
emoticonsMad,
emiconConfuced,
emoticonsHappy,
emoticonsWow,
emoticonsLove
];
break;
case "funky":
emojiIcons = [
funckyAngry,
funckyMad,
funckyMadAngry,
funckyThinking,
funckyHappy,
funckyWow,
funckyLove
];
break;
case "classic":
emojiIcons = [
classicAngry,
classicMadAngry,
classicThinking,
classicMad,
classicHappy,
classicWow,
classicLove
];
break;
case "blobs":
emojiIcons = [
blobAngry,
blobMad,
blobMadAngry,
blobThinking,
blobHappy,
blobWow,
blobLove
];
break;
default:
emojiIcons = [angry, mad, madAngry, thinking, happy, wow, love];
}
return emojiIcons;
};
/**
* Updates the slider range
* @param {String} event Changer event of the emoji slider
*/
updateRange = (event) => {
this.setState({
rangeValue: event.target.value
});
this.props.onChange(this.state.emojiLabel[this.state.rangeValue])
}
/**
* Describes the elements on the rating component
* @return {String} HTML elements
*/
render() {
const { emojis, rangeValue } = this.state;
return (
<div className={styles.rateContainer}>
<div className={styles.emojiSliderContainer}>
<div className={styles.tooltip}>
{" "}
<img
src={this.state.emojiIcons[this.state.rangeValue]}
style={grow}
/>
<span className={styles.tooltiptext}>{this.state.emojiLabel[this.state.rangeValue]}</span>
</div>
<input
id="sliderId"
className={styles.inputR}
name="sliderName"
type="range"
min="0"
max={emojis.length - 1}
defaultValue={rangeValue}
onChange={this.updateRange}
style={styleInput}
/>
<div className="label" style={{ textAlign: "center" }}></div>
</div>
</div>
);
}
} |
JavaScript | class SpellChecker {
/**
* ctor
*
* @param {boolean} enabled Whether spell checking is enabled in settings.
*/
constructor (enabled = true, lang) {
this.enabled = enabled
this.currentSpellcheckerLanguage = lang
// Helper to forbid the usage of the spell checker (e.g. failed to create native spell checker),
// even if spell checker is enabled in settings.
this.isProviderAvailable = true
}
/**
* Whether the spell checker is available and enabled.
*/
get isEnabled () {
return this.isProviderAvailable && this.enabled
}
/**
* Enable the spell checker and sets `lang` or tries to find a fallback.
*
* @param {string} lang The language to set.
* @returns {Promise<boolean>}
*/
async activateSpellchecker (lang) {
try {
this.enabled = true
this.isProviderAvailable = true
if (isOsx) {
// No language string needed on macOS.
return await ipcRenderer.invoke('mt::spellchecker-set-enabled', true)
}
return await this.switchLanguage(lang || this.currentSpellcheckerLanguage)
} catch (error) {
this.deactivateSpellchecker()
throw error
}
}
/**
* Disables the native spell checker.
*/
deactivateSpellchecker () {
this.enabled = false
this.isProviderAvailable = false
ipcRenderer.invoke('mt::spellchecker-set-enabled', false)
}
/**
* Return the current language.
*/
get lang () {
if (this.isEnabled) {
return this.currentSpellcheckerLanguage
}
return ''
}
set lang (lang) {
this.currentSpellcheckerLanguage = lang
}
/**
* Explicitly switch the language to a specific language.
*
* NOTE: This function can throw an exception.
*
* @param {string} lang The language code
* @returns {Promise<boolean>} Return the language on success or null.
*/
async switchLanguage (lang) {
if (isOsx) {
// NB: On macOS the OS spell checker is used and will detect the language automatically.
return true
} else if (!lang) {
throw new Error('Expected non-empty language for spell checker.')
} else if (this.isEnabled) {
await ipcRenderer.invoke('mt::spellchecker-switch-language', lang)
this.lang = lang
return true
}
return false
}
/**
* Returns a list of available dictionaries.
* @returns {Promise<string[]>} Available dictionary languages.
*/
static async getAvailableDictionaries () {
if (isOsx) {
// NB: On macOS the OS spell checker is used and will detect the language automatically.
return []
}
return ipcRenderer.invoke('mt::spellchecker-get-available-dictionaries')
}
} |
JavaScript | class Ticker {
constructor () {
this.pool = [];
}
/**
* Starts the animation loop.
*/
start () {
if ( ! this.animationFrameId ) {
const loop = () => {
this.animationFrameId = window.requestAnimationFrame(loop);
this.draw();
};
this.animationFrameId = window.requestAnimationFrame(loop);
}
}
/**
* Stops the animation loop.
*/
stop () {
window.cancelAnimationFrame(this.animationFrameId);
this.animationFrameId = null;
}
/**
* Invoke `.draw()` on all instances in the pool.
*/
draw () {
this.pool.forEach(instance => instance.draw());
}
/**
* Add an instance to the pool.
*
* @param {Kampos} instance
*/
add (instance) {
const index = this.pool.indexOf(instance);
if ( ! ~ index ) {
this.pool.push(instance);
instance.playing = true;
}
}
/**
* Remove an instance form the pool.
*
* @param {Kampos} instance
*/
remove (instance) {
const index = this.pool.indexOf(instance);
if ( ~ index ) {
this.pool.splice(index, 1);
instance.playing = false;
}
}
} |
JavaScript | class A11yTabs extends LitElement {
//styles function
static get styles() {
return [
css`
:host {
display: block;
--a11y-tabs-border-radius: 2px;
--a11y-tabs-justify-tabs: flex-start;
--ally-tabs-wrap: unset;
--a11y-tabs-background: white;
--a11y-tabs-border-color: #ddd;
--a11y-tabs-color: #222;
--a11y-tabs-focus-color: #000;
--a11y-tabs-faded-background: #eee;
--a11y-tabs-content-padding: 16px;
--a11y-tabs-button-padding: 0.7em 0.57em;
--a11y-tabs-vertical-button-padding: unset;
--a11y-tabs-horizontal-border-radius: unset;
--a11y-tabs-vertical-border-radius: unset;
--a11y-tabs-horizontal-button-padding: 2px 5px;
height: var(--a11y-tabs-height);
overflow: var(--a11y-tabs-overflow);
}
:host([vertical]) {
border: 1px solid var(--a11y-tabs-border-color);
border-radius: var(
--a11y-tabs-vertical-border-radius,
var(--a11y-tabs-border-radius)
);
display: flex;
justify-content: space-between;
align-items: stretch;
}
:host([hidden]) {
display: none;
}
:host #tabs {
align-items: stretch;
flex-wrap: var(--ally-tabs-wrap, unset);
margin: 0;
display: flex;
list-style: none;
padding: 0;
}
:host([vertical]) #tabs {
background-color: var(--a11y-tabs-border-color);
justify-content: var(
--a11y-tabs-vertical-justify-tabs,
var(--a11y-tabs-justify-tabs, flex-start)
);
flex-wrap: var(
--ally-tabs-vertical-wrap,
var(--ally-tabs-wrap, unset)
);
border-left: none;
flex: 0 1 auto;
flex-direction: column;
}
:host(:not([vertical])) #tabs {
justify-content: var(
--a11y-tabs-horizontal-justify-tabs,
var(--a11y-tabs-justify-tabs, flex-start)
);
}
:host #tabs .flag-type {
position: absolute;
left: -99999px;
height: 0;
overflow: hidden;
}
:host #content {
padding: var(--a11y-tabs-content-padding);
background-color: var(--a11y-tabs-background);
border: 1px solid var(--a11y-tabs-border-color);
}
:host([vertical]) #content {
flex: 1 0 auto;
border: none;
}
:host(:not([vertical])) #content {
border-radius: var(
--a11y-tabs-horizontal-border-radius,
var(--a11y-tabs-border-radius)
);
margin-top: -1px;
}
:host #tabs paper-button {
margin: 0;
text-transform: unset;
color: var(--a11y-tabs-color);
background-color: var(--a11y-tabs-faded-background);
border: 1px solid var(--a11y-tabs-border-color);
padding: var(--a11y-tabs-button-padding, 0.7em 0.57em);
}
:host([vertical]) #tabs paper-button {
border-top: none;
border-left: none;
border-radius: 0;
display: flex;
justify-content: space-between;
align-items: center;
padding: var(
--a11y-tabs-vertical-button-padding,
var(--a11y-tabs-button-padding)
);
}
:host(:not([vertical])) #tabs paper-button {
width: 100%;
border-bottom: none;
border-radius: var(
--a11y-tabs-horizontal-border-radius,
var(--a11y-tabs-border-radius)
)
var(
--a11y-tabs-horizontal-border-radius,
var(--a11y-tabs-border-radius)
)
0 0;
padding: var(
--a11y-tabs-horizontal-button-padding,
var(--a11y-tabs-button-padding)
);
}
:host(:not([vertical])) #tabs li:not(:first-of-type) paper-button {
border-left: none;
}
:host #tabs paper-button:active,
:host #tabs paper-button:focus,
:host #tabs paper-button:hover {
color: var(--a11y-tabs-focus-color);
background-color: var(--a11y-tabs-faded-background);
}
:host #tabs paper-button[disabled] {
color: var(--a11y-tabs-focus-color);
background-color: var(--a11y-tabs-background);
}
:host([vertical]) #tabs paper-button[disabled] {
border-right-color: var(--a11y-tabs-background);
}
:host(:not([vertical])) #tabs paper-button[disabled] {
border-bottom: 1px solid var(--a11y-tabs-background);
}
:host #tabs span.label,
:host #tabs .flag-icon {
margin-right: 8px;
}
:host #tabs.icons-only paper-button {
justify-content: center;
}
:host #tabs.icons-only span.label {
display: none;
}
:host #tabs:not(.icons-only) paper-tooltip {
display: none;
}
`
];
}
// render function
render() {
return html`
<ul
id="tabs"
.class="${this._showIcons(
this.__hasIcons,
this.iconBreakpoint,
this.layoutBreakpoint,
this.responsiveSize
)}"
>
${this.__items.map(
tab => html`
<li>
<paper-button
id="${tab.id}-button"
controls="${tab.id}"
@click="${e => this._handleTab(`${tab.id}`)}"
?disabled="${tab.id === this.activeTab}"
.flag="${tab.flag}"
>
<iron-icon
class="flag-icon"
?hidden="${!tab.flagIcon}"
.icon="${tab.flagIcon}"
>
</iron-icon>
<span class="label">${tab.label}</span>
<span class="flag-type" ?hidden="${!tab.flag}">
${tab.flag}
</span>
<iron-icon
class="icon"
?hidden="${!tab.icon}"
.icon="${tab.icon}"
>
</iron-icon>
</paper-button>
<paper-tooltip for="${tab.id}-button">${tab.label}</paper-tooltip>
</li>
`
)}
</ul>
<div id="content">
<slot></slot>
</div>
`;
}
// haxProperty definition
static get haxProperties() {
return {};
}
// properties available to the custom element for data binding
static get properties() {
return {
...super.properties,
/**
* the id of the active tab
*/
activeTab: {
type: String,
attribute: "active-tab"
},
/**
* whether the tabbed interface is disabled
*/
disabled: {
type: Boolean,
reflect: true
},
/**
* whether the tabbed interface is hidden
*/
hidden: {
type: Boolean,
reflect: true
},
/**
* the minimum breakpoint for showing tab text with icons, or
* - use `0` to always show icons only
* - use `-1` to always show text with icons
*/
iconBreakpoint: {
type: Number,
attribute: "icon-breakpoint"
},
/**
* unique identifier/anchor for the tabbed interface
*/
id: {
type: String,
reflect: true
},
/**
* the minimum breakpoint for horizontal layout of tabs, or
* - use `0` for horizontal-only
* - use `-1` for vertical-only
*/
layoutBreakpoint: {
type: Number,
attribute: "layout-breakpoint"
},
/**
* the size of the tabs,
* where `xs` is the smaller breakpoint
* and `xs` is the larger breakpoint
*/
responsiveSize: {
type: String,
reflect: true,
attribute: "responsive-size"
},
/**
* whether the tabbed interface is in vertical layout mode
*/
vertical: {
type: Boolean,
reflect: true
},
/**
* whether the tabbed interface has icons for each tab
*/
__hasIcons: {
type: Boolean
},
/**
* an array of tab data based on slotted `a11y-tab` elements
*/
__items: {
type: Array
},
/**
* a mutation observer to monitor slotted `a11y-tab` elements
*/
__observer: {
type: Object
}
};
}
/**
* Store the tag name to make it easier to obtain directly.
* @notice function name must be here for tooling to operate correctly
*/
static get tag() {
return "a11y-tabs";
}
constructor() {
super();
let callback = (mutationsList, observer) => this.updateItems();
this.activeTab = null;
this.disabled = false;
this.hidden = false;
this.iconBreakpoint = 400;
this.id = null;
this.layoutBreakpoint = 600;
this.responsiveSize = "xs";
this.vertical = false;
this.__hasIcons = false;
this.__items = [];
this.updateItems();
this.__observer = new MutationObserver(callback);
this._breakpointChanged();
window.ResponsiveUtility.requestAvailability();
this.__observer.observe(this, {
attributes: false,
childList: true,
subtree: false
});
this.addEventListener("a11y-tab-changed", e => this.updateItems());
}
/**
* life cycle, element is afixed to the DOM
*/
connectedCallback() {
super.connectedCallback();
}
/**
* life cycle, element is removed from the DOM
*/
disconnectedCallback() {
if (this.__observer && this.__observer.disconnect)
this.__observer.disconnect();
this.removeEventListener("a11y-tab-changed", e => this.updateItems());
this._unsetBreakpoints();
super.disconnectedCallback();
}
updated(changedProperties) {
changedProperties.forEach((oldValue, propName) => {
if (propName === "id") this._idChanged(this.id, oldValue);
if (propName === "activeTab") this.selectTab(this.activeTab);
if (propName === "iconBreakpoint") this._breakpointChanged();
if (propName === "layoutBreakpoint") this._breakpointChanged();
if (propName === "responsiveSize") this._setVertical();
});
}
/**
* selects a tab
* @param {string} id the active tab's id
*/
selectTab(id) {
let tabs = this.querySelectorAll("a11y-tab"),
selected =
id && this.querySelector(`a11y-tab#${id}`)
? this.querySelector(`a11y-tab#${id}`)
: this.querySelector("a11y-tab");
if (selected && selected.id !== id) {
this.activeTab = selected.id;
return;
} else if (tabs && tabs.length > 0) {
tabs.forEach(tab => {
tab.hidden = tab.id !== id;
});
}
}
/**
* updates the list of items based on slotted a11y-tab elements
*/
updateItems(e) {
this.__items = [];
let tabs = this.querySelectorAll("a11y-tab"),
ctr = 1;
this.__hasIcons = true;
if (!this.id) this.id = this._generateUUID();
if (tabs && tabs.length > 0)
tabs.forEach(tab => {
this.__items.push({
id: tab.id || `tab-${ctr}`,
flag: tab.flag,
flagIcon: tab.flagIcon,
icon: tab.icon,
label: tab.label || `Tab ${ctr}`
});
if (!tab.icon) this.__hasIcons = false;
tab.__xOfY = `${ctr} of ${tabs.length}`;
tab.__toTop = this.id;
});
this.selectTab(this.activeTab);
}
/**
* Observer activeTab for changes
* @param {string} newValue the new active tab's id
*/
_activeTabChanged(newValue) {
this.selectTab(newValue);
}
/**
* handles any breakpoint changes
* @param {event} e the tab change event
*/
_breakpointChanged() {
this._unsetBreakpoints();
this._setBreakpoints();
this._setVertical();
}
/**
* generates a unique id
* @returns {string } unique id
*/
_generateUUID() {
return "ss-s-s-s-sss".replace(
/s/g,
Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1)
);
}
/**
* handles a tab being tapped and sets the new active tab
* @param {event} e the tab tap event
*/
_handleTab(id) {
this.activeTab = id;
}
/**
* ensures that there is always an id for this tabbed interface so that we can link back to the top of it
* @param {string} newValue the new id
* @param {string} oldValue the old id
*/
_idChanged(newValue, oldValue) {
if (!newValue) this.id = "a11y-tabs" + this._generateUUID();
}
/**
* Fires when element is ready to request breakpoint tracking from repsonsive utility.
*
* @event responsive-element
*/
_setBreakpoints() {
let v = this.layoutBreakpoint > -1 ? this.layoutBreakpoint : 0,
i = this.iconBreakpoint > -1 ? this.iconBreakpoint : 0,
sm = i > v ? v : i,
md = i > v ? i : v,
lg = Math.max(i, v) + 1,
xl = Math.max(i, v) + 2;
window.dispatchEvent(
new CustomEvent("responsive-element", {
detail: {
element: this,
attribute: "responsive-size",
relativeToParent: true,
sm: sm,
md: md,
lg: lg,
xl: xl
}
})
);
}
/**
* determines if tabs should be in a vertical layout
* @param {number} icon breakpoint for icon-only view
* @param {number} layout breakpoint for vertical layout
* @param {string} size the responsive size
*/
_setVertical() {
this.vertical =
this.layoutBreakpoint === -1 ||
this.iconBreakpoint > this.layoutBreakpoint
? this.responsiveSize === "xs"
: this.responsiveSize.indexOf("s") > -1;
}
/**
* determines if tabs should show icons only
* @param {boolean} hasIcons does every tab have an icon?
* @param {number} icon breakpoint for icon-only view
* @param {number} layout breakpoint for vertical layout
* @param {string} size the responsive size
* @returns {boolean} if tabs should be in a vertical layout
*/
_showIcons(hasIcons, icon, layout, size) {
return hasIcons &&
icon !== -1 &&
(size === "xs" || (icon > layout && size === "sm"))
? "icons-only"
: "";
}
/**
* Fires when element is rno longer needs specific breakpoints tracked.
*
* @event responsive-element-deleted
*/
_unsetBreakpoints() {
window.dispatchEvent(
new CustomEvent("responsive-element-deleted", {
bubbles: true,
cancelable: true,
composed: true,
detail: this
})
);
}
} |
JavaScript | class IntrinsicType extends abstract_1.Type {
/**
* Create a new instance of IntrinsicType.
*
* @param name The name of the intrinsic type like `string` or `boolean`.
*/
constructor(name) {
super();
/**
* The type name identifier.
*/
this.type = "intrinsic";
this.name = name;
}
/**
* Clone this type.
*
* @return A clone of this type.
*/
clone() {
return new IntrinsicType(this.name);
}
/**
* Test whether this type equals the given type.
*
* @param type The type that should be checked for equality.
* @returns TRUE if the given type equals this type, FALSE otherwise.
*/
equals(type) {
return type instanceof IntrinsicType && type.name === this.name;
}
/**
* Return a string representation of this type.
*/
toString() {
return this.name;
}
} |
JavaScript | class ArrayNode {
constructor(typeCode, size, data) {
this.typeCode = typeCode;
this.size = size;
this.data = data;
}
static read(reader, typeCode) {
switch (typeCode) {
case TwsType.UINT32_BYTE_ARRAY:
case TwsType.UINT32_SHORT_ARRAY:
case TwsType.UINT32_24BIT_ARRAY:
case TwsType.INT32_24BIT_ARRAY:
case TwsType.INT32_BYTE_ARRAY:
case TwsType.INT32_SHORT_ARRAY:
case TwsType.UINT8_ARRAY:
case TwsType.UINT32_ARRAY:
case TwsType.UINT64_ARRAY:
case TwsType.ASCII_ARRAY:
case TwsType.UTF16_ARRAY:
case TwsType.COORD2D_ARRAY:
case TwsType.UINT16_ARRAY:
case TwsType.INT8_ARRAY:
case TwsType.SINGLE_ARRAY:
case TwsType.BOOL_ARRAY:
case TwsType.INT32_ARRAY:
case TwsType.COORD3D_ARRAY:
return ArrayNode.readArray(reader, typeCode);
case TwsType.INT16_ARRAY:
case TwsType.INT64_ARRAY:
case TwsType.DOUBLE_ARRAY:
case TwsType.ANGLE_ARRAY:
// i.e. untested, need a savefile to test
throw new Error(`Array type - Not implemented: ${typeCode}`);
case TwsType.BOOL_TRUE_ARRAY:
case TwsType.BOOL_FALSE_ARRAY:
case TwsType.UINT_ZERO_ARRAY:
case TwsType.UINT_ONE_ARRAY:
case TwsType.INT32_ZERO_ARRAY:
case TwsType.SINGLE_ZERO_ARRAY:
// trying to read this should result in an infinite loop
throw new Error(`Array ${typeCode.toString(16)} of zero-byte entries makes no sense`);
default:
throw new Error(`Unknown array type code ${typeCode}`);
}
}
static readArray(reader, typeCode) {
const size = reader.readSize();
const containedTypeCode = (typeCode - 0x40);
const offset = reader.position();
const elements = [];
while (reader.position() < (offset + size)) {
const node = reader.readValueNode(containedTypeCode);
elements.push(node);
}
return new ArrayNode(typeCode, size, elements);
}
} |
JavaScript | class Student {
/**
* Constructor untuk membuat objek siswa dengan data nama, kota, dan nilai.
* @param {String} name - Nama siswa.
* @param {String} city - Kota tempat tinggal siswa.
* @param {Number} score - Nilai siswa.
*/
constructor(name, city, score) {
this.name = name;
this.city = city;
this.score = score;
}
} |
JavaScript | class StudentComparator {
/**
* Comparator untuk membandingkan data siswa berdasarkan nama,
* dengan menggunakan method String.prototype.localeCompare().
* Method String.prototype.localeCompare sendiri merupakan comparator bawaan untuk string,
* yaitu membandingkan dua string, dan mengembalikan nilai yang menentukan urutan kedua string tersebut.
* Contohnya "a".localeCompare("c") akan mengembalikan nilai -1, berarti a menjadi urutan pertama.
* @param {Student} firstStudent - Data siswa pertama
* @param {Student} secondStudent - Data siswa kedua
* @returns {Number} - Nilai yang menentukan urutan dari data siswa.
*/
static compareByName(firstStudent, secondStudent) {
return firstStudent.name.localeCompare(secondStudent.name);
}
/**
* Comparator untuk membandingkan data siswa berdasarkan nilai siswa,
* dengan melakukan pengurangan dari dua nilai siswa.
* Pengurangan dua nilai siswa ini akan menghasilkan nilai yang menentukan urutan siswa.
* Contohnya: 70 - 90 = -20. Berarti data 70 akan menjadi urutan pertama.
* @param {Student} firstStudent - Data siswa pertama
* @param {Student} secondStudent - Data siswa kedua
* @returns {Number} - Nilai yang menentukan urutan dari data siswa.
*/
static compareByScore(firstStudent, secondStudent) {
return firstStudent.score - secondStudent.score;
}
/**
* Comparator untuk membandingkan data siswa berdasarkan kota,
* dengan menggunakan method String.prototype.localeCompare().
* @param {Student} firstStudent - Data siswa pertama
* @param {Student} secondStudent - Data siswa kedua
* @returns {Number} - Nilai yang menentukan urutan dari data siswa.
*/
static compareByCity(firstStudent, secondStudent) {
return firstStudent.city.localeCompare(secondStudent.city);
}
/**
* Comparator untuk membandingkan data siswa berdasarkan kota, kemudian nama.
* Comparator ini pertama membandingkan kota dari dua siswa, dan jika memiliki kota yang sama,
* maka membandingkan berdasarkan nama siswa.
* @param {Student} firstStudent - Data siswa pertama
* @param {Student} secondStudent - Data siswa kedua
* @returns {Number} - Nilai yang menentukan urutan dari data siswa.
*/
static compareByCityAndName(firstStudent, secondStudent) {
if (firstStudent.city === secondStudent.city) {
return StudentComparator.compareByName(firstStudent, secondStudent);
} else {
return StudentComparator.compareByCity(firstStudent, secondStudent);
}
}
/**
* Comparator untuk membandingkan data siswa berdasarkan kota, nilai, kemudian nama.
* Comparator ini pertama membandingkan kota dari dua siswa, dan jika memiliki kota yang sama,
* maka membandingkan berdasarkan nilai siswa, dan jika memiliki nilai yang sama, maka membandingkan nama siswa.
* @param {Student} firstStudent - Data siswa pertama
* @param {Student} secondStudent - Data siswa kedua
* @returns {Number} - Nilai yang menentukan urutan dari data siswa.
*/
static compareByCityAndScoreAndName(firstStudent, secondStudent) {
if (firstStudent.city === secondStudent.city) {
if (firstStudent.score === secondStudent.score) {
return StudentComparator.compareByName(firstStudent, secondStudent);
} else {
return StudentComparator.compareByScore(firstStudent, secondStudent);
}
} else {
return StudentComparator.compareByCity(firstStudent, secondStudent);
}
}
/**
* Comparator untuk membandingkan data siswa berdasarkan nilai siswa secara descending,
* dengan menggunakan pembalikkan dari StudentComparator.compareByScore.
* Pembalikkan StudentComparator.compareByScore ini digunakan agar data diurutkan secara descending.
* Contohnya: StudentComparator.compareByScore(70, 90) * -1 akan menghasilkan 20.
* Berarti data 90 akan menjadi urutan pertama.
* @param {Student} firstStudent - Data siswa pertama
* @param {Student} secondStudent - Data siswa kedua
* @returns {Number} - Nilai yang menentukan urutan dari data siswa.
*/
static compareByScoreDesc(firstStudent, secondStudent) {
return -StudentComparator.compareByScore(firstStudent, secondStudent);
}
} |
JavaScript | class Contact extends React.Component {
constructor(props) {
super(props);
this.state = { feedback: '', name: '', email: '', sent: false };
this.handleChange = this.handleChange.bind(this);
this.handleChangeEmail = this.handleChangeEmail.bind(this);
this.handleChangeText = this.handleChangeText.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.resetForm = this.resetForm.bind(this);
this.messageSentSuccess = this.messageSentSuccess.bind(this);
}
render() {
return (
<div className="contactContainer">
<Head title={this.props.t('contact.titlePage')}/>
<div className="wMarginCont">
<p className="titleContact">{this.props.t('contact.titleContact')}</p>
<div className="formContainer">
<form className="contactForm" onSubmit={this.handleSubmit}>
<div className="rowCont">
<div className="labelsCont">
<p className="lblForm">{this.props.t('contact.name')}</p>
<p className="lblForm">{this.props.t('contact.email')}</p>
<p className="lblForm">{this.props.t('contact.comments')}</p>
</div>
<div className="inputsCont">
<input
id="test-text"
name="test-text"
onChange={this.handleChangeText}
placeholder={this.props.t('contact.phName')}
required
value={this.state.name}
className="inputForm"
/>
<input
id="test-email"
name="test-email"
onChange={this.handleChangeEmail}
placeholder={this.props.t('contact.phEmail')}
type="email"
required
value={this.state.email}
className="inputForm"
/>
<textarea
id="test-mailing"
name="test-mailing"
onChange={this.handleChange}
placeholder={this.props.t('contact.phFeedback')}
required
value={this.state.feedback}
className="inputForm"
/>
</div>
</div>
<div className="btnCont">
<input type="submit" value={this.props.t('contact.submitValue')} className="btnForm" />
<input type="button" value={this.props.t('contact.cancelValue')} className="btnForm" onClick={this.resetForm} />
</div>
</form>
{ this.state.sent &&
<div className="emailSentCont">
<p className="pEmailSent">{this.props.t('contact.emailSent')}</p>
<img src={iconSent} alt="Message Delivered" className="iconSent" />
</div>
}
</div>
<ul className="ulMediaIcons">
<li>
<a href="https://www.facebook.com/saturno.mangieri/">
<img src={iconFb} alt="Facebook Profile" className="iconsSocial" />
</a>
</li>
<li>
<a href="https://github.com/theghost1980">
<img src={iconGH} alt="GitHub Profile" className="iconsSocial" />
</a>
</li>
<li>
<a href="https://www.linkedin.com/in/saturno-mangieri-011265138/">
<img src={iconLD} alt="Linkedin Profile" className="iconsSocial" />
</a>
</li>
</ul>
</div>
</div>
)
}
handleChangeText(event) {
this.setState({name: event.target.value})
}
handleChangeEmail(event) {
this.setState({email: event.target.value})
}
handleChange(event) {
this.setState({feedback: event.target.value})
}
resetForm = () => {
this.setState({
name: '',
email: '',
feedback: '',
sent: false
})
}
messageSentSuccess() {
this.setState({sent: true});
setTimeout(this.resetForm,4000);
}
handleSubmit (event) {
this.sendFeedback({message_html: this.state.feedback, from_name: this.state.name, reply_to: this.state.email})
event.preventDefault();
}
sendFeedback (variables) {
_emailJs.init(userId);
_emailJs.send(
serviceId, templateId,
variables
).then(res => {
console.log('Email successfully sent!');
this.messageSentSuccess();
})
// Handle errors here however you like, or use a React error boundary
.catch(err => console.error('Oh well, you failed. Here some thoughts on the error that occured:', err))
}
} |
JavaScript | class BshbMessagesHandler extends bshb_handler_1.BshbHandler {
handleBshcUpdate(resultEntry) {
if (resultEntry['@type'] === 'message') {
this.bshb.log.debug('Updating messages...');
// we just trigger detection on changes of scenarios
this.detectMessages().subscribe(() => {
// we do nothing here because we do not need to.
this.bshb.log.debug('Updating messages finished');
}, error => {
this.bshb.log.warn('something went wrong during message detection');
this.bshb.log.warn(error);
});
return true;
}
return false;
}
handleDetection() {
this.bshb.log.info('Start detecting messages...');
// we need to do that because of concat
return new rxjs_1.Observable(subscriber => {
this.detectMessages().subscribe(() => {
this.bshb.log.info('Detecting messages finished');
subscriber.next();
subscriber.complete();
});
});
}
sendUpdateToBshc(id, state) {
return false;
}
detectMessages() {
return new rxjs_1.Observable(subscriber => {
this.getBshcClient().getMessages({ timeout: this.long_timeout }).subscribe(response => {
const messages = response.parsedResponse;
this.bshb.setObjectNotExists('messages', {
type: 'state',
common: {
name: 'messages',
type: 'object',
role: 'state',
write: false,
read: true
},
native: {
id: 'messages',
name: 'messages'
},
});
this.bshb.setState('messages', { val: messages, ack: true });
subscriber.next();
subscriber.complete();
}, err => {
subscriber.error(err);
});
});
}
} |
JavaScript | class CaseDetailPage {
// constructor for used components
constructor () {
this.compCasesList = new CasesList(2);
this.compModel = new Model();
}
// get the data of the selcted case from the BAAS
// check if the project is 3d or not
async getCase () {
const searchLink = window.location.hash;
const searchId = searchLink.substring(searchLink.lastIndexOf('/') + 1);
const project = await BAAS.getCase(searchId);
if (project === undefined) {
window.location.assign('#!/404');
return ``;
}
if (project.is3d === false) {
return `
<div class="case">
<div class="row case-basic">
<div class="col-10 col-lg-11">
<h1 class="case-basic__item">case - ${project.title}</h1>
</div>
<div class="btn-back col-2 col-md-1">
<a href="#!${routes.PORTFOLIO}"><i class="fas fa-times"></i></a>
</div>
</div>
<div class="row case-about">
<div class="col-12 col-md-8 case-about__main">
<p>${project.description}</p>
</div>
<div class="col-12 col-md-3 offset-md-1 case-about__side-info">
<div class="d-flex makers">
<p>Door:</p>
<ul>
${this.getMakers(project.makers)}
</ul>
</div>
<p>Jaar: ${project.yearCreated}</p>
<p>Vak: ${project.course}</p>
</div>
</div>
<div class="row case-images">
${this.getImages(project.images)}
</div>
<div class="case-tags">
<h2><i class="fas fa-tags no-borders"></i> Tags</h2>
<div class="d-flex">
${this.getTags(project.tags)}
</div>
</div>
<div class="case-technologies">
<h2>Gebruikte technologieën</h2>
<ul class="row case-technologies__list">
${this.getTechnologies(project.technologies)}
</ul>
</div>
<div class="case-related">
<h2>Bekijk ook</h2>
<div class="row cases-list justify-content-center">
${await this.compCasesList.render()}
</div>
</div>
</div>
`;
}
if (project.is3d === true) {
this.getModel(project.images);
return `
<div class="case">
<div class="row case-basic">
<div class="col-10 col-lg-11">
<h1 class="case-basic__item">case - ${project.title}</h1>
</div>
<div class="btn-back col-2 col-md-1">
<a href="#!${routes.PORTFOLIO}"><i class="fas fa-times"></i></a>
</div>
</div>
<div class="row case-about">
<div class="col-12 col-md-8 case-about__main">
<p>${project.description}</p>
</div>
<div class="col-12 col-md-3 offset-md-1 case-about__side-info">
<div class="d-flex makers">
<p>Door:</p>
<ul>
${this.getMakers(project.makers)}
</ul>
</div>
<p>Jaar: ${project.yearCreated}</p>
<p>Vak: ${project.course}</p>
</div>
</div>
<div class="row justify-content-center">
<canvas class="case-model"></canvas>
</div>
<div class="case-tags">
<h2><i class="fas fa-tags no-borders"></i> Tags</h2>
<div class="d-flex">
${this.getTags(project.tags)}
</div>
</div>
<div class="case-technologies">
<h2>Gebruikte technologieën</h2>
<ul class="row case-technologies__list">
${this.getTechnologies(project.technologies)}
</ul>
</div>
<div class="case-related">
<h2>Bekijk ook</h2>
<div class="row cases-list justify-content-center">
${await this.compCasesList.render()}
</div>
</div>
</div>
`;
}
return this;
}
// get the makers of a case
getMakers (array) {
return array.map(maker => `
<li>${maker}</li>
`).join('');
}
// get the images of a case
getImages (array) {
return array.map(image => `
<img src="${image.src}" alt="Image of ${image.alt}" class="col-12 col-lg-6 case-images__image">
`).join('');
}
// get the tags of a case
getTags (array) {
return array.map(tag => `
<p>${tag}</p>
`).join('');
}
// get the technologies of a case
getTechnologies (array) {
return array.map(technologie => `
<li class="col-6 col-md-4 col-lg-3 d-flex flex-column align-items-center case-technologies__item">
<p>${technologie.name}</p>
<img src="${technologie.logoURL}" alt="Logo of ${technologie.name}">
</li>
`).join('');
}
// get the model of a case and save it in session storage
getModel (array) {
/* eslint-disable arrow-body-style */
const model = array.find((image) => {
return (image.thumbnail === false);
});
window.sessionStorage.setItem('model', JSON.stringify(model));
}
// render the content
async render () {
return `
<div class="page page--case_detail container">
${await this.getCase()}
</div>
`;
}
async afterRender () {
// afterRender all components on the page
this.compCasesList.afterRender();
const modelContainer = document.querySelector('.case-model');
if (modelContainer !== null) {
this.compModel.render(JSON.parse(window.sessionStorage.getItem('model')));
this.compModel.afterRender();
}
// Connect the listeners
return this;
}
async mount () {
// Before the rendering of the page
// scroll to the top
window.scrollTo(0, 0);
return this;
}
async unmount () {
// After leaving the page
return this;
}
} |
JavaScript | class Room extends EventEmitter {
/**
* Creates a Room instance.
* @param {string} name - Room name.
* @param {string} peerId - User's peerId.
* @param {object} [options] - Optional arguments for the connection.
* @param {object} [options.stream] - User's medias stream to send other participants.
* @param {object} [options.pcConfig] - A RTCConfiguration dictionary for the RTCPeerConnection.
* @param {number} [options.videoBandwidth] - A max video bandwidth(kbps)
* @param {number} [options.audioBandwidth] - A max audio bandwidth(kbps)
* @param {string} [options.videoCodec] - A video codec like 'H264'
* @param {string} [options.audioCodec] - A video codec like 'PCMU'
* @param {boolean} [options.videoReceiveEnabled] - A flag to set video recvonly
* @param {boolean} [options.audioReceiveEnabled] - A flag to set audio recvonly
*/
constructor(name, peerId, options = {}) {
super();
// Abstract class
if (this.constructor === Room) {
throw new TypeError('Cannot construct Room instances directly');
}
this.name = name;
this._options = options;
this._peerId = peerId;
this._localStream = this._options.stream;
this._pcConfig = this._options.pcConfig;
this.lastSent = 0;
this.messageQueue = [];
this.sendIntervalID = null;
}
/**
* Validate whether the size of data to send is over the limits or not.
* @param {object} data - The data to Validate.
*/
validateSendDataSize(data) {
const isBin = hasBin([data]);
const packet = {
type: isBin ? parser.BINARY_EVENT : parser.EVENT,
data: [data],
};
const encoder = new parser.Encoder();
let dataSize;
encoder.encode(packet, encodedPackets => {
dataSize = isBin
? encodedPackets[1].byteLength
: encodedPackets[0].length;
});
const maxDataSize = config.maxDataSize;
if (dataSize > maxDataSize) {
throw new Error('The size of data to send must be less than 20 MB');
}
return true;
}
/**
* Send a message to the room with a delay so that the transmission interval does not exceed the limit.
* @param {object} msg - The data to send to this room.
* @param {string} key - The key of broadcast event.
*/
_sendData(msg, key) {
const sendInterval = config.minBroadcastIntervalMs;
const now = Date.now();
const diff = now - this.lastsend;
// When no queued message and last message is enough old
if (this.messageQueue.length == 0 && diff >= sendInterval) {
// Update last send time and send message without queueing.
this.lastsend = now;
this.emit(key, msg);
return;
}
// Send a message to the room with a delay because the transmission interval exceeds the limit.
// Push this message into a queue.
this.messageQueue.push({ msg, key });
// Return if setInterval is already set.
if (this.sendIntervalID !== null) {
return;
}
this.sendIntervalID = setInterval(() => {
// If all message are sent, remove this interval ID.
if (this.messageQueue.length === 0) {
clearInterval(this.sendIntervalID);
this.sendIntervalID = null;
return;
}
// Update last send time send message.
const message = this.messageQueue.shift();
this.lastsend = Date.now();
this.emit(message.key, message.msg);
}, sendInterval);
}
/**
* Handle received data message from other paricipants in the room.
* It emits data event.
* @param {object} dataMessage - The data message to handle.
* @param {ArrayBuffer} dataMessage.data - The data that a peer sent in the room.
* @param {string} dataMessage.src - The peerId of the peer who sent the data.
* @param {string} [dataMessage.roomName] - The name of the room user is joining.
*/
handleData(dataMessage) {
const message = {
data: dataMessage.data,
src: dataMessage.src,
};
this.emit(Room.EVENTS.data.key, message);
}
/**
* Handle received log message.
* It emits log event with room's logs.
* @param {Array} logs - An array containing JSON text.
*/
handleLog(logs) {
this.emit(Room.EVENTS.log.key, logs);
}
/**
* Start getting room's logs from SkyWay server.
*/
getLog() {
const message = {
roomName: this.name,
};
this.emit(Room.MESSAGE_EVENTS.getLog.key, message);
}
/**
* Events the Room class can emit.
* @type {Enum}
*/
static get EVENTS() {
return RoomEvents;
}
/**
* MediaStream received from peer in the room.
*
* @event Room#stream
* @type {MediaStream}
*/
/**
* Room is ready.
*
* @event Room#open
*/
/**
* All connections in the room has closed.
*
* @event Room#close
*/
/**
* New peer has joined.
*
* @event Room#peerJoin
* @type {string}
*/
/**
* A peer has left.
*
* @event Room#peerLeave
* @type {string}
*/
/**
* Error occured
*
* @event Room#error
*/
/**
* Data received from peer.
*
* @event Room#data
* @type {object}
* @property {string} src - The peerId of the peer who sent the data.
* @property {*} data - The data that a peer sent in the room.
*/
/**
* Room's log received.
*
* @event Room#log
* @type {Array}
*/
/**
* Connection closed event.
*
* @event Connection#close
*/
/**
* Events the Room class can emit.
* @type {Enum}
*/
static get MESSAGE_EVENTS() {
return RoomMessageEvents;
}
/**
* Offer created event.
*
* @event Room#offer
* @type {object}
* @property {RTCSessionDescription} offer - The local offer to send to the peer.
* @property {string} dst - Destination peerId
* @property {string} connectionId - This connection's id.
* @property {string} connectionType - This connection's type.
* @property {object} metadata - Any extra data to send with the connection.
*/
/**
* Answer created event.
*
* @event Room#answer
* @type {object}
* @property {RTCSessionDescription} answer - The local answer to send to the peer.
* @property {string} dst - Destination peerId
* @property {string} connectionId - This connection's id.
* @property {string} connectionType - This connection's type.
*/
/**
* ICE candidate created event.
*
* @event Room#candidate
* @type {object}
* @property {RTCIceCandidate} candidate - The ice candidate.
* @property {string} dst - Destination peerId
* @property {string} connectionId - This connection's id.
* @property {string} connectionType - This connection's type.
*/
/**
* Left the room.
*
* @event Room#peerLeave
* @type {object}
* @property {string} roomName - The room name.
*/
/**
* Get room log from SkyWay server.
*
* @event Room#log
* @type {object}
* @property {string} roomName - The room name.
*/
} |
JavaScript | class ServiceAllOf {
/**
* Constructs a new <code>ServiceAllOf</code>.
* @alias module:model/ServiceAllOf
*/
constructor() {
ServiceAllOf.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>ServiceAllOf</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/ServiceAllOf} obj Optional instance to populate.
* @return {module:model/ServiceAllOf} The populated <code>ServiceAllOf</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new ServiceAllOf();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'String');
}
if (data.hasOwnProperty('providerId')) {
obj['providerId'] = ApiClient.convertToType(data['providerId'], 'String');
}
if (data.hasOwnProperty('tenantId')) {
obj['tenantId'] = ApiClient.convertToType(data['tenantId'], 'String');
}
if (data.hasOwnProperty('userId')) {
obj['userId'] = ApiClient.convertToType(data['userId'], 'String');
}
if (data.hasOwnProperty('subscriptionId')) {
obj['subscriptionId'] = ApiClient.convertToType(data['subscriptionId'], 'String');
}
if (data.hasOwnProperty('createdOn')) {
obj['createdOn'] = ApiClient.convertToType(data['createdOn'], 'Date');
}
if (data.hasOwnProperty('modifiedOn')) {
obj['modifiedOn'] = ApiClient.convertToType(data['modifiedOn'], 'Date');
}
if (data.hasOwnProperty('provisionedOn')) {
obj['provisionedOn'] = ApiClient.convertToType(data['provisionedOn'], 'Date');
}
}
return obj;
}
} |
JavaScript | class MapEvent_RepeatEvents extends ActionValue {
/**
* Create a RepeatEvents event using these parameters.
* @param {Number} repetitions Repetitions (Repeating count) of the events.
* @param {Number} interval Interval of each events.
* @param {String} tag Tag of the events.
*/
constructor(repetitions, interval, tag) {
super();
this.repetitions = repetitions == null ? this.repetitions : repetitions;
this.interval = interval == null ? this.interval : interval;
this.tag = tag == null ? this.tag : tag;
}
/**
* Repetitions (Repeating count) of the events.
*/
repetitions = 1;
/**
* Interval of each events.
*/
interval = 1;
/**
* Tag of the events.
*/
tag = new String();
/**
* Returns a json part of this event.
*/
asJsonPart(...params) {
return `, "repetitions": ${JSON.stringify(
params[0] == null ? this.repetitions : params[0]
)}, "interval": ${JSON.stringify(
params[1] == null ? this.interval : params[1]
)}, "tag": ${JSON.stringify(params[2] == null ? this.tag : params[2])}`;
}
/**
* Create value by converting from object
* @param {Object} obj
*/
static fromObject(obj) {
var res = new this();
Object.keys(obj).forEach((key) => {
res[key] = obj[key];
});
return res;
}
} |
JavaScript | class Node {
constructor(data) {
this.data = data;
this.next = null;
}
} |
JavaScript | class VaccineQueryUtils {
constructor(ctx, listName) {
this.ctx = ctx;
this.name = listName;
//this.supportedTypes = {};
}
// =========================================================================================
// getAssetHistory takes the composite key as arg, gets returns results as JSON to 'main contract'
// =========================================================================================
/**
* Get Asset History for a vaccine
* @param {String} vaccineUUID the unique id of a vaccine dose
*/
async getAssetHistory(batchNumber, manufacturer) {
let ledgerKey = await this.ctx.stub.createCompositeKey(this.name, [vaccineUUID]);
// returns a Promise for a QueryHistoryIterator that allows iterating over a set of key/value pairs
const resultsIterator = await this.ctx.stub.getHistoryForKey(ledgerKey);
let results = await this.getAllResults(resultsIterator, true);
return results;
}
// ===========================================================================================
// queryKeyByPartial performs a partial query based on the namespace and prefix of the composite key,
// which is the vaccineUUID
// returns composite key based on partial key provided
// Read-only function results are not typically submitted to ordering. If the read-only
// results are submitted to ordering, or if the query is used in an update transaction
// and submitted to ordering, then the committing peers will re-execute to guarantee that
// result sets are stable between endorsement time and commit time. The transaction is
// invalidated by the committing peers if the result set has changed between endorsement
// time and commit time.
//
// ===========================================================================================
/**
*
* @param {String} vaccineUUID
*/
async queryKeyByPartial(vaccineUUID) {
if (arguments.length < 1) {
throw new Error('Incorrect number of arguments. Expecting 1');
}
// partial composite key = namespace + prefix to raw materials (i.e. manufacturer name)
// "Key": e.g. "org.vaccine.rawmaterialManufacturerA#31415962"
// "Partial": e.g. "org.vaccine.rawmaterialManufacturerA" (using partial key, find keys "#31415962")
// Queries the state in the ledger based on a given partial composite key.
// Returns an iterator which can be used to iterate over all composite keys
// whose prefix matches the given partial composite key
// [manufacturer] is array of strings that will be concatenated together to form partial key
const resultsIterator = await this.ctx.stub.getStateByPartialCompositeKey(this.name, [vaccineUUID]);
let method = this.getAllResults;
let results = await method(resultsIterator, false);
return results;
}
// ===== Example: Parameterized rich query =================================================
// queryByPurchaser queries for assets based on a passed in purchaser.
// This is an example of a parameterized query accepting a single query parameter (purchaser).
// Only available on state databases that support rich query (e.g. CouchDB)
// =========================================================================================
/**
* queryByPurchaser gets instance(s) with given purchaser
* @param {String} purchaser purchaser of vaccine
*/
async queryByPurchaser(purchaser) {
let self = this;
if (arguments.length < 1) {
throw new Error('Incorrect number of arguments. Expecting purchaser.');
}
let queryString = {}; // query string format dependent on database used
queryString.selector = {};
queryString.selector.purchaser = purchaser; // final result: '{selector:{purchaser:Pfizer}}'
let method = self.getQueryResultForQueryString;
let queryResults = await method(this.ctx, self, JSON.stringify(queryString));
return queryResults;
}
/**
* gets instance(s) with given dateMixedIn
* @param {String} issueDateTime
* @returns array of objects (in JS, aka dictionary or JSON)
*/
async queryByIssueDateTime(issueDateTime) {
let self = this;
if (arguments.length < 1) {
throw new Error('Incorrect number of arguments. Expecting dateMixedIn.');
}
let queryString = {}; // query string format dependent on database used
queryString.selector = {};
queryString.selector.issueDateTime = issueDateTime;
let method = self.getQueryResultForQueryString;
let queryResults = await method(this.ctx, self, JSON.stringify(queryString));
return queryResults;
}
/**
* gets instance with given batch number
* @param {String} batchNum
*/
async queryByBatchNumber(batchNum) {
let self = this;
if (arguments.length < 1) {
throw new Error('Incorrect number of arguments. Expecting batch number.');
}
let queryString = {}; // query string format dependent on database used
queryString.selector = {};
queryString.selector.batchNum = batchNum;
let method = self.getQueryResultForQueryString;
let queryResults = await method(this.ctx, self, JSON.stringify(queryString));
return queryResults;
}
/**
* gets instance(s) with given manufacturer
* @param {String} manufacturer
*/
async queryByManufacturer(manufacturer) {
let self = this;
if (arguments.length < 1) {
throw new Error('Incorrect number of arguments. Expecting manufacturer.');
}
let queryString = {}; // query string format dependent on database used
queryString.selector = {};
queryString.selector.manufacturer = manufacturer;
let method = self.getQueryResultForQueryString;
let queryResults = await method(this.ctx, self, JSON.stringify(queryString));
return queryResults;
}
/**
* gets instance(s) with given vaccineUUID
* @param {String} vaccineUUID
*/
async queryByVaccineUUID(vaccineUUID) {
let self = this;
if (arguments.length < 1) {
throw new Error('Incorrect number of arguments. Expecting manufacturer.');
}
let queryString = {}; // query string format dependent on database used
queryString.selector = {};
queryString.selector.vaccineUUID = vaccineUUID;
let method = self.getQueryResultForQueryString;
let queryResults = await method(this.ctx, self, JSON.stringify(queryString));
return queryResults;
}
/**
* gets instance(s) with given recipient
* @param {String} recipient
*/
async queryByRecipient(recipient) {
let self = this;
if (arguments.length < 1) {
throw new Error('Incorrect number of arguments. Expecting manufacturer.');
}
let queryString = {}; // query string format dependent on database used
queryString.selector = {};
queryString.selector.recipient = recipient;
let method = self.getQueryResultForQueryString;
let queryResults = await method(this.ctx, self, JSON.stringify(queryString));
return queryResults;
}
// ===== Example: Ad hoc rich query ========================================================
// queryAdhoc uses a query string to perform a query for marbles..
// Query string matching state database syntax is passed in and executed as is.
// Supports ad hoc queries that can be defined at runtime by the client.
// If this is not desired, follow the queryKeyByOwner example for parameterized queries.
// Only available on state databases that support rich query (e.g. CouchDB)
// example passed using VS Code ext: ["{\"selector\": {\"owner\": \"MagnetoCorp\"}}"]
// =========================================================================================
/**
* query By AdHoc string (commercial paper)
* @param {String} queryString actual MangoDB query string (escaped)
*/
async queryByAdhoc(queryString) {
if (arguments.length < 1) {
throw new Error('Incorrect number of arguments. Expecting ad-hoc string, which gets stringified for mango query');
}
let self = this;
if (!queryString) {
throw new Error('queryString must not be empty');
}
let method = self.getQueryResultForQueryString;
let queryResults = await method(this.ctx, self, JSON.stringify(queryString));
return queryResults;
}
// WORKER functions are below this line: these are called by the above functions, where iterator is passed in
// =========================================================================================
// getQueryResultForQueryString worker function executes the passed-in query string.
// Result set is built and returned as a byte array containing the JSON results.
// =========================================================================================
/**
* Function getQueryResultForQueryString
* @param {Context} ctx the transaction context
* @param {any} self within scope passed in
* @param {String} the query string created prior to calling this fn
*/
async getQueryResultForQueryString(ctx, self, queryString) {
console.log('- getQueryResultForQueryString queryString:\n' + queryString);
// The query string is in the native syntax of the underlying state database.
// An StateQueryIterator is returned which can be used to iterate over all keys in the query result set.
const resultsIterator = await ctx.stub.getQueryResult(queryString);
let results = await self.getAllResults(resultsIterator, false);
return results;
}
/**
* Function getAllResults
* @param {resultsIterator} iterator within scope passed in
* @param {Boolean} isHistory query string created prior to calling this fn
* @returns array of objects
*/
async getAllResults(iterator, isHistory) {
let allResults = [];
let res = { done: false, value: null };
console.log("Entered getAllResults\n");
while (true) {
res = await iterator.next();
console.log("Iterator item is ", res, "\n");
console.log("res.value is ", res.value, "\nres.value.value is ", res.value.value,"\n");
console.log("res.value.value to string is ", res.value.value.toString());
let jsonRes = {};
// if res.value is not undefined or null
if (res.value && res.value.value.toString()) {
if (isHistory && isHistory === true) {
// add key-value pair for transaction id
jsonRes.TxId = res.value.txId;
jsonRes.Timestamp = res.value.timestamp;
jsonRes.Timestamp = new Date((res.value.timestamp.seconds.low * 1000));
let ms = res.value.timestamp.nanos / 1000000;
jsonRes.Timestamp.setMilliseconds(ms);
if (res.value.is_delete) {
jsonRes.IsDelete = res.value.is_delete.toString();
} else {
try {
jsonRes.Value = JSON.parse(res.value.value.toString('utf8'));
} catch (err) {
console.log(err);
jsonRes.Value = res.value.value.toString('utf8');
}
}
} else { // non history query ..
jsonRes.Key = res.value.key;
try {
jsonRes.Record = JSON.parse(res.value.value.toString('utf8'));
} catch (err) {
console.log(err);
jsonRes.Record = res.value.value.toString('utf8');
}
}
allResults.push(jsonRes);
}
// check to see if we have reached the end
if (res.done) {
// explicitly close the iterator
console.log('iterator is done');
await iterator.close();
return allResults;
}
} // while true
}
} |
JavaScript | class MutationExpressionsHandler {
async handle(pathData) {
const mutationExpressions = []; // Add all mutationExpressions to the path
let current = pathData;
while (current) {
// Obtain and store mutationExpressions
if (current.mutationExpressions) mutationExpressions.unshift(...(await current.mutationExpressions)); // Move to parent link
current = current.parent;
}
return mutationExpressions;
}
} |
JavaScript | class UndoGroup {
/**
* Start an Undo group - begin recording
* @param workspace the workspace
*/
static startUndoGroup(workspace) {
const undoStack = workspace.undoStack_;
if (undoStack.length) {
undoStack[undoStack.length - 1]._devtoolsLastUndo = true;
}
}
/**
* End an Undo group - stops recording
* @param workspace the workspace
*/
static endUndoGroup(workspace) {
const undoStack = workspace.undoStack_;
// Events (responsible for undoStack updates) are delayed with a setTimeout(f, 0)
// https://github.com/LLK/scratch-blocks/blob/f159a1779e5391b502d374fb2fdd0cb5ca43d6a2/core/events.js#L182
setTimeout(() => {
const group = generateUID();
for (let i = undoStack.length - 1; i >= 0 && !undoStack[i]._devtoolsLastUndo; i--) {
undoStack[i].group = group;
}
}, 0);
}
} |
JavaScript | class Translator {
constructor() {
/**
* A map of translation keys to their translated values.
*
* @type {Object}
* @public
*/
this.translations = {};
this.locale = null;
}
trans(id, parameters) {
const translation = this.translations[id];
if (translation) {
return this.apply(translation, parameters || {});
}
return id;
}
transChoice(id, number, parameters) {
let translation = this.translations[id];
if (translation) {
number = parseInt(number, 10);
translation = this.pluralize(translation, number);
return this.apply(translation, parameters || {});
}
return id;
}
apply(translation, input) {
// If we've been given a user model as one of the input parameters, then
// we'll extract the username and use that for the translation. In the
// future there should be a hook here to inspect the user and change the
// translation key. This will allow a gender property to determine which
// translation key is used.
if ('user' in input) {
const user = extract(input, 'user');
if (!input.username) input.username = username(user);
}
translation = translation.split(new RegExp('({[a-z0-9_]+}|</?[a-z0-9_]+>)', 'gi'));
const hydrated = [];
const open = [hydrated];
translation.forEach(part => {
const match = part.match(new RegExp('{([a-z0-9_]+)}|<(/?)([a-z0-9_]+)>', 'i'));
if (match) {
if (match[1]) {
open[0].push(input[match[1]]);
} else if (match[3]) {
if (match[2]) {
open.shift();
} else {
let tag = input[match[3]] || {tag: match[3], children: []};
open[0].push(tag);
open.unshift(tag.children || tag);
}
}
} else {
open[0].push(part);
}
});
return hydrated.filter(part => part);
}
pluralize(translation, number) {
const sPluralRegex = new RegExp(/^\w+\: +(.+)$/),
cPluralRegex = new RegExp(/^\s*((\{\s*(\-?\d+[\s*,\s*\-?\d+]*)\s*\})|([\[\]])\s*(-Inf|\-?\d+)\s*,\s*(\+?Inf|\-?\d+)\s*([\[\]]))\s?(.+?)$/),
iPluralRegex = new RegExp(/^\s*(\{\s*(\-?\d+[\s*,\s*\-?\d+]*)\s*\})|([\[\]])\s*(-Inf|\-?\d+)\s*,\s*(\+?Inf|\-?\d+)\s*([\[\]])/),
standardRules = [],
explicitRules = [];
translation.split('|').forEach(part => {
if (cPluralRegex.test(part)) {
const matches = part.match(cPluralRegex);
explicitRules[matches[0]] = matches[matches.length - 1];
} else if (sPluralRegex.test(part)) {
const matches = part.match(sPluralRegex);
standardRules.push(matches[1]);
} else {
standardRules.push(part);
}
});
explicitRules.forEach((rule, e) => {
if (iPluralRegex.test(e)) {
const matches = e.match(iPluralRegex);
if (matches[1]) {
const ns = matches[2].split(',');
for (let n in ns) {
if (number == ns[n]) {
return explicitRules[e];
}
}
} else {
var leftNumber = this.convertNumber(matches[4]);
var rightNumber = this.convertNumber(matches[5]);
if (('[' === matches[3] ? number >= leftNumber : number > leftNumber) &&
(']' === matches[6] ? number <= rightNumber : number < rightNumber)) {
return explicitRules[e];
}
}
}
});
return standardRules[this.pluralPosition(number, this.locale)] || standardRules[0] || undefined;
}
convertNumber(number) {
if ('-Inf' === number) {
return Number.NEGATIVE_INFINITY;
} else if ('+Inf' === number || 'Inf' === number) {
return Number.POSITIVE_INFINITY;
}
return parseInt(number, 10);
}
pluralPosition(number, locale) {
if ('pt_BR' === locale) {
locale = 'xbr';
}
if (locale.length > 3) {
locale = locale.split('_')[0];
}
switch (locale) {
case 'bo':
case 'dz':
case 'id':
case 'ja':
case 'jv':
case 'ka':
case 'km':
case 'kn':
case 'ko':
case 'ms':
case 'th':
case 'vi':
case 'zh':
return 0;
case 'af':
case 'az':
case 'bn':
case 'bg':
case 'ca':
case 'da':
case 'de':
case 'el':
case 'en':
case 'eo':
case 'es':
case 'et':
case 'eu':
case 'fa':
case 'fi':
case 'fo':
case 'fur':
case 'fy':
case 'gl':
case 'gu':
case 'ha':
case 'he':
case 'hu':
case 'is':
case 'it':
case 'ku':
case 'lb':
case 'ml':
case 'mn':
case 'mr':
case 'nah':
case 'nb':
case 'ne':
case 'nl':
case 'nn':
case 'no':
case 'om':
case 'or':
case 'pa':
case 'pap':
case 'ps':
case 'pt':
case 'so':
case 'sq':
case 'sv':
case 'sw':
case 'ta':
case 'te':
case 'tk':
case 'tr':
case 'ur':
case 'zu':
return (number == 1) ? 0 : 1;
case 'am':
case 'bh':
case 'fil':
case 'fr':
case 'gun':
case 'hi':
case 'ln':
case 'mg':
case 'nso':
case 'xbr':
case 'ti':
case 'wa':
return ((number === 0) || (number == 1)) ? 0 : 1;
case 'be':
case 'bs':
case 'hr':
case 'ru':
case 'sr':
case 'uk':
return ((number % 10 == 1) && (number % 100 != 11)) ? 0 : (((number % 10 >= 2) && (number % 10 <= 4) && ((number % 100 < 10) || (number % 100 >= 20))) ? 1 : 2);
case 'cs':
case 'sk':
return (number == 1) ? 0 : (((number >= 2) && (number <= 4)) ? 1 : 2);
case 'ga':
return (number == 1) ? 0 : ((number == 2) ? 1 : 2);
case 'lt':
return ((number % 10 == 1) && (number % 100 != 11)) ? 0 : (((number % 10 >= 2) && ((number % 100 < 10) || (number % 100 >= 20))) ? 1 : 2);
case 'sl':
return (number % 100 == 1) ? 0 : ((number % 100 == 2) ? 1 : (((number % 100 == 3) || (number % 100 == 4)) ? 2 : 3));
case 'mk':
return (number % 10 == 1) ? 0 : 1;
case 'mt':
return (number == 1) ? 0 : (((number === 0) || ((number % 100 > 1) && (number % 100 < 11))) ? 1 : (((number % 100 > 10) && (number % 100 < 20)) ? 2 : 3));
case 'lv':
return (number === 0) ? 0 : (((number % 10 == 1) && (number % 100 != 11)) ? 1 : 2);
case 'pl':
return (number == 1) ? 0 : (((number % 10 >= 2) && (number % 10 <= 4) && ((number % 100 < 12) || (number % 100 > 14))) ? 1 : 2);
case 'cy':
return (number == 1) ? 0 : ((number == 2) ? 1 : (((number == 8) || (number == 11)) ? 2 : 3));
case 'ro':
return (number == 1) ? 0 : (((number === 0) || ((number % 100 > 0) && (number % 100 < 20))) ? 1 : 2);
case 'ar':
return (number === 0) ? 0 : ((number == 1) ? 1 : ((number == 2) ? 2 : (((number >= 3) && (number <= 10)) ? 3 : (((number >= 11) && (number <= 99)) ? 4 : 5))));
default:
return 0;
}
}
} |
JavaScript | class Coordinates {
constructor(root) {
this.root = root;
}
/**
* Check whether pointer coordinates matches with safe area coordinates
* @public
* @returns {boolean} Whether the coordinates are correct
*/
checkPosition() {
const areaRange = this.getRange(this.root._ui._Bar.areaNode);
const pointerRange = this.getRange(this.root._ui._Bar.pointerNode);
if (
pointerRange.from === areaRange.from ||
pointerRange.from === areaRange.to ||
pointerRange.to === areaRange.from ||
pointerRange.to === areaRange.to
) {
return true;
}
if (pointerRange.from < areaRange.from) {
if (pointerRange.to < areaRange.from) {
return false;
}
if (pointerRange.to > areaRange.from) {
return true;
}
}
return pointerRange.from <= areaRange.to;
}
/**
* @private
* @param {HTMLElement} node
* @returns {Range} Range
*/
getRange(node) {
const range = {};
const { translateY, top, height } = this.getCoordinates(node);
const offset = top || translateY || 0
range.from = offset;
range.to = offset + height;
return range;
}
/**
* @private
* @param {HTMLElement} node
* @returns {Coordinates} Coordinates
*/
getCoordinates(node) {
return {
height: node.clientHeight,
top: this.percentsOf(this.root._ui._Bar.node.clientHeight, +node.style.top.split("%")[0]),
...this.getTransformProperties(node),
};
}
percentsOf(target, percents) {
return target / 100 * percents
}
/**
* @private
* @param {HTMLElement} node
* @returns {TransformStyles} TransformStyles
*/
getTransformProperties(node) {
const rawValues = node.style.transform.split(" ");
if (!rawValues[0]) {
return {};
}
const transformStyles = {};
rawValues.forEach((value) => {
const splitValue = value.split("(");
const propertyName = splitValue[0];
transformStyles[propertyName] = +splitValue[1].slice(0, -1).split("p")[0];
});
return transformStyles;
}
} |
JavaScript | class Lang {
/**
* Creates a new language.
* @param {String} [lang] - The language code.
* @param {String} [namespace] - The namespace for the language.
* @constructs Lang
*/
constructor(lang = defaultSettings.lang, namespace = '') {
this.lang = lang;
this.namespace = namespace;
this.fallback = ( i18n?.[lang]?.fallback.slice() || [defaultSettings.lang] ).filter( fb => fb.trim() );
this.localNames = {};
this.aliases = {};
let aliases = ( i18n?.[lang]?.aliases || {} );
Object.keys(aliases).forEach( cmd => {
if ( aliases[cmd][0].trim() && !( cmd in this.localNames ) ) {
this.localNames[cmd] = aliases[cmd][0];
}
aliases[cmd].forEach( alias => {
if ( alias.trim() && !( alias in this.aliases ) ) this.aliases[alias] = cmd;
} );
} );
Object.keys(defaultAliases).forEach( cmd => {
if ( defaultAliases[cmd][0].trim() && !( cmd in this.localNames ) ) {
this.localNames[cmd] = defaultAliases[cmd][0];
}
defaultAliases[cmd].forEach( alias => {
if ( alias.trim() && !( alias in this.aliases ) ) this.aliases[alias] = cmd;
} );
} );
}
/**
* Get a localized message.
* @param {String} message - Name of the message.
* @param {String[]} args - Arguments for the message.
* @returns {String}
*/
get(message = '', ...args) {
if ( this.namespace.length ) message = this.namespace + '.' + message;
let keys = ( message.length ? message.split('.') : [] );
let lang = this.lang;
let text = i18n?.[lang];
let fallback = 0;
for (let n = 0; n < keys.length; n++) {
if ( text ) {
text = text?.[keys[n]];
if ( typeof text === 'string' ) text = text.trim()
}
if ( !text ) {
if ( fallback < this.fallback.length ) {
lang = this.fallback[fallback];
fallback++;
text = i18n?.[lang];
n = -1;
}
else {
n = keys.length;
}
}
}
if ( typeof text === 'string' ) {
args.forEach( (arg, i) => {
text = text.replaceSave( new RegExp( `\\$${i + 1}`, 'g' ), arg );
} );
text = text.replace( /{{\s*PLURAL:\s*[+-]?(\d+)\s*\|\s*([^\{\}]*?)\s*}}/g, (m, number, cases) => {
return plural(lang, parseInt(number, 10), cases.split(/\s*\|\s*/));
} );
}
return ( text || '⧼' + message + ( isDebug && args.length ? ': ' + args.join(', ') : '' ) + '⧽' );
}
// /**
// * Get a localized message.
// * @param {String} message - Name of the message.
// * @param {String[]} args - Arguments for the message.
// * @returns {String}
// */
// get(message = '', ...args) {
// if ( this.namespace.length ) message = this.namespace + '.' + message;
// let lang = this.lang;
// let text = i18n?.[lang]?.[message];
// let fallback = 0;
// while ( !text ) {
// if ( fallback < this.fallback.length ) {
// lang = this.fallback[fallback];
// fallback++;
// text = i18n?.[lang]?.[message];
// }
// else break;
// }
// if ( typeof text === 'string' ) {
// args.forEach( (arg, i) => {
// text = text.replaceSave( new RegExp( `\\$${i + 1}`, 'g' ), arg );
// } );
// text = text.replace( /{{\s*PLURAL:\s*[+-]?(\d+)\s*\|\s*([^\{\}]*?)\s*}}/g, (m, number, cases) => {
// return plural(lang, parseInt(number, 10), cases.split(/\s*\|\s*/));
// } );
// }
// return ( text || '⧼' + message + ( isDebug && args.length ? ': ' + args.join(', ') : '' ) + '⧽' );
// }
/**
* Get names for all languages.
* @param {Boolean} isRcGcDw - Get the languages for RcGcDw?
* @returns {Object}
* @static
*/
static allLangs(isRcGcDw = false) {
if ( isRcGcDw ) return i18n.RcGcDw;
return i18n.allLangs;
}
} |
JavaScript | class HeatmapWidgetView extends InputWidgetView {
initialize(options) {
super.initialize(options);
empty(this.el);
const reactDiv = div({id: this.model.element_id});
this.el.appendChild(reactDiv);
const initializeReact = () => {
// Must delay-load React because the reactDiv hasn't been written to the DOM yet
pyreporting.initializeBokehHeatmap({model: this.model});
};
setTimeout(initializeReact, 0);
}
} |
JavaScript | class TwoColumn extends React.Component {
constructor(props) {
super(props);
// console.log(props)
}
something = () => {
return 'frank';
}
render () {
return (
<section id={this.props.id && this.props.id} className="main style1">
<div className="grid-wrapper">
<div className={this.props.swap ? `swap col-6` : 'col-6'}>
<span className="image fit"><img src={require(`../assets/images/${this.props.image}`)} alt={this.props.alt} /></span>
</div>
<div className="col-6">
{this.props.headline &&
<header className="major">
<h2>{this.props.headline }</h2>
</header>
}
{this.props.subHeadline &&
<h3>{this.props.subHeadline}</h3>
}
{this.props.content &&
<p>{this.props.content}</p>
}
{this.props.listItems &&
<ul>
{this.props.listItems.map( (item, index) =>
<li key={index}>{item}</li>
)}
</ul>
}
</div>
</div>
</section>
)
}
} |
JavaScript | class SchemaNamedTypeElement {
/**
* @param {StringElement} name
* @param {SourceMap} sourceMap
*/
constructor(name, sourceMap) {
this.name = name;
/**
* @type {BodyElement}
*/
this.bodyEl = null;
/**
* @type {SchemaElement}
*/
this.schemaEl = null;
/**
* a bodyEl transformed to object via JSON.parse
*/
this.body = null;
/**
* @type {DescriptionElement}
*/
this.description = null;
/**
* @type {UnrecognizedBlockElement[]}
*/
this.unrecognizedBlocks = [];
this.sourceMap = sourceMap;
}
isComplex() {
return true;
}
getBody() {
return this.body;
}
getSchema() {
const usedTypes = [];
return [this.schemaEl.schema, usedTypes];
}
/**
* @param {boolean} sourceMapsEnabled
*/
toRefract(sourceMapsEnabled) {
const result = {
element: Refract.elements.schemaStructure,
meta: {
id: this.name.toRefract(sourceMapsEnabled),
},
content: [this.bodyEl, this.schemaEl].filter(el => el).map(el => el.toRefract(sourceMapsEnabled)),
};
if (this.description) {
const description = {
element: Refract.elements.string,
content: this.description.description,
};
if (sourceMapsEnabled && this.description.sourceMap) {
description.attributes = {
sourceMap: new SourceMapElement(this.description.sourceMap.byteBlocks).toRefract(),
};
}
result.meta.description = description;
}
if (sourceMapsEnabled) {
const sourceMapEl = new SourceMapElement(this.sourceMap.byteBlocks);
result.attributes = {
sourceMap: sourceMapEl.toRefract(),
};
}
if (this.unrecognizedBlocks.length) {
result.attributes = result.attributes || {};
result.attributes.unrecognizedBlocks = {
element: Refract.elements.array,
content: this.unrecognizedBlocks.map(b => b.toRefract(sourceMapsEnabled)),
};
}
return result;
}
} |
JavaScript | class GetCenter {
/**
* @static
* @param {any} req {request object}
* @param {any} res {response object}
* @return {*} JSON
* @memberof GetCenter
*/
static getCenter(req, res) {
const { centerId } = req.params;
let events;
return Centers.findOne({
where: {
id: centerId
}
})
.then(center => {
if (!center) {
return res.status(404).send({
status: 'Unsuccessful',
message: 'Center Not Found'
});
}
return Events.findAndCountAll({
limit: 10,
offset: Math.ceil((parseInt(req.query.page, 10) - 1) * 10),
order: [['id', 'ASC']],
where: {
centerId
}
}).then(event => {
events = event;
return res.status(200).send({
status: 'Success',
message: 'This is your event center',
data: {
center,
events: events
}
});
});
})
.catch(err =>
res.status(422).send({
status: 'Unsuccessful',
data: err.message
})
);
}
} |
JavaScript | class GetAllCenters {
/**
* @static
* @param {any} req {request object}
* @param {any} res {response object}
* @returns {*} JSON
* @memberof GetAllCenters
*/
static getAllCenters(req, res) {
if (isNaN(req.query.page)) {
req.query.page = 1;
}
return Centers.findAndCountAll({
limit: 10,
offset: (parseInt(req.query.page, 10) - 1) * 10,
order: [['id', 'ASC']]
}).then(centers => {
if (centers.rows.length === 0) {
return res.status(404).send({
status: 'Unsuccessful',
message: 'No Centers Found'
});
}
return res.status(200).send({
status: 'Success',
message: 'Centers found',
data: centers
});
});
}
} |
JavaScript | class EventReportingTest extends SdkBaseTest {
constructor(name, kiteConfig) {
super(name, kiteConfig, "EventReporting");
}
async runIntegrationTest() {
const session = this.seleniumSessions[0];
let attendee_id = uuidv4();
await OpenAppStep.executeStep(this, session);
await AuthenticateUserStep.executeStep(this, session, attendee_id, false, false, true);
await UserAuthenticationCheck.executeStep(this, session);
await JoinMeetingStep.executeStep(this, session);
await UserJoinedMeetingCheck.executeStep(this, session, attendee_id);
await RosterCheck.executeStep(this, session, 1);
await EndMeetingStep.executeStep(this, session);
await this.waitAllSteps();
}
} |
JavaScript | class ResourceJsonDeserializer {
/**
* Creates an instance of ResourceJsonDeserializer.
* @param {Edm} edm the current EDM instance
* @param {JsonContentTypeInfo} [formatParams] JSON format parameters
*/
constructor (edm, formatParams = new JsonContentTypeInfo()) {
this._edm = edm
this._decoder = new PrimitiveValueDecoder().setJsonFormatParameters(formatParams)
}
/**
* Deserializes a provided JSON payload string of an entity.
* @param {EdmType} edmType the EDM type of the entity
* @param {string} value the JSON data string to deserialize
* @param {ExpandItem[]} expand the current expand items
* @param {Object} additionalInformation additional information to be set in the deserializer
* @returns {Object} the deserialized result
* @throws {DeserializationError} if provided data can not be deserialized
*/
deserializeEntity (edmType, value, expand, additionalInformation) {
try {
let data = JSON.parse(value)
this._deserializeStructuralType(edmType, data, null, false, expand, additionalInformation)
return data
} catch (e) {
if (e instanceof DeserializationError) throw e
throw new DeserializationError('An error occurred during deserialization of the entity.', e)
}
}
/**
* Deserializes a provided JSON payload string of an entity collection.
* @param {EdmType} edmType the EDM type of the entity collection
* @param {string|Object[]} value the JSON data string to deserialize
* @param {ExpandItem[]} expand the array expand items will be created in
* @param {Object} additionalInformation additional information to be set in the deserializer
* @returns {Object[]} the deserialized result
* @throws {DeserializationError} if provided data can not be deserialized
*/
deserializeEntityCollection (edmType, value, expand, additionalInformation) {
let tempData = JSON.parse(value)
if (typeof tempData !== 'object') {
throw new DeserializationError('Value for the collection must be an object.')
}
const wrongName = Object.keys(tempData).find(name => !odataAnnotations.has(name) && name !== 'value')
if (wrongName) throw new DeserializationError("'" + wrongName + "' is not allowed in a collection value.")
tempData = tempData.value
if (!Array.isArray(tempData)) {
throw new DeserializationError("Input must be a collection of type '" + edmType.getFullQualifiedName() + "'.")
}
try {
for (let entityValue of tempData) {
this._deserializeStructuralType(edmType, entityValue, [], false, expand, additionalInformation)
}
return tempData
} catch (e) {
if (e instanceof DeserializationError) throw e
throw new DeserializationError('An error occurred during deserialization of the collection.', e)
}
}
/**
* Deserializes a provided JSON payload string of a complex property.
* @param {EdmProperty} edmProperty the EDM property of this complex property
* @param {string} propertyValue the JSON data string to deserialize
* @returns {Object} the deserialized result
* @throws {DeserializationError} if provided data can not be deserialized
*/
deserializeComplexProperty (edmProperty, propertyValue) {
return this.deserializeEntity(edmProperty.getType(), propertyValue)
}
/**
* Deserializes a provided JSON payload string of a complex property collection.
* @param {EdmProperty} edmProperty the EDM property of this complex property collection
* @param {string} propertyValue the JSON data string
* @returns {Object[]} The deserialized result
* @throws {DeserializationError} if provided data can not be deserialized
*/
deserializeComplexPropertyCollection (edmProperty, propertyValue) {
return this.deserializeEntityCollection(edmProperty.getType(), propertyValue)
}
/**
* Deserializes a provided JSON payload string of a primitive property.
* @param {EdmProperty} edmProperty the EDM property of this primitive property
* @param {string} propertyValue the JSON data string to deserialize
* @returns {?(number|string|boolean|Buffer|Object)} the deserialized result
* @throws {DeserializationError} if provided data can not be deserialized
*/
deserializePrimitiveProperty (edmProperty, propertyValue) {
let tempData = JSON.parse(propertyValue)
if (typeof tempData !== 'object') {
throw new DeserializationError('Value for primitive property must be an object.')
}
const wrongName = Object.keys(tempData).find(name => !odataAnnotations.has(name) && name !== 'value')
if (wrongName) throw new DeserializationError(`'${wrongName}' is not allowed in a primitive value.`)
tempData = tempData.value
if (tempData === undefined) throw new DeserializationError('Value can not be omitted.')
try {
return this._deserializePrimitive(edmProperty, tempData)
} catch (e) {
if (e instanceof DeserializationError) throw e
throw new DeserializationError('An error occurred during deserialization of the property.', e)
}
}
/**
* Deserializes a provided JSON payload string of a primitive property collection.
* @param {EdmProperty} edmProperty the EDM property of this primitive property collection
* @param {string} value the JSON data string to deserialize
* @returns {number[]|string[]|boolean[]|Buffer[]|Object[]} the deserialized result
* @throws {DeserializationError} if provided data can not be deserialized
*/
deserializePrimitivePropertyCollection (edmProperty, value) {
let tempData = JSON.parse(value)
if (typeof tempData !== 'object') {
throw new DeserializationError('Value for primitive collection property must be an object.')
}
const wrongName = Object.keys(tempData).find(name => !odataAnnotations.has(name) && name !== 'value')
if (wrongName) throw new DeserializationError(`'${wrongName}' is not allowed in a primitive-collection value.`)
tempData = tempData.value
this._assertPropertyIsCollection(edmProperty, tempData)
try {
return this._deserializePrimitive(edmProperty, tempData)
} catch (e) {
if (e instanceof DeserializationError) throw e
throw new DeserializationError('An error occurred during deserialization of the property.', e)
}
}
/**
* Deserializes a provided JSON payload string of an entity reference.
* @param {EdmType} edmType the EDM type of the entity
* @param {string} value the JSON data string to deserialize
* @returns {UriInfo} the deserialized result
* @throws {DeserializationError} if provided data can not be deserialized
*/
deserializeReference (edmType, value) {
const tempData = JSON.parse(value)
if (typeof tempData !== 'object') throw new DeserializationError('Value for reference must be an object.')
try {
return this._deserializeReference(edmType, tempData)
} catch (e) {
if (e instanceof DeserializationError) throw e
throw new DeserializationError('An error occurred during deserialization of the reference.', e)
}
}
/**
* Deserializes a provided JSON payload string of action parameters.
* @param {EdmAction} edmAction the action to deserialize the payload for
* @param {string} value the JSON data string to deserialize
* @returns {Object} the deserialized result
* @throws {DeserializationError} if provided data can not be deserialized
*/
deserializeActionParameters (edmAction, value) {
let data
let result = {}
let parameters = Array.from(edmAction.getParameters())
// Skip the first parameter if the action is bound
// because the first parameter of a bound action is the binding parameter
// which is not part of the payload data.
if (edmAction.isBound()) parameters.shift()
for (const [paramName, edmParam] of parameters) {
if ((value === null || value === undefined) && !edmParam.isNullable()) {
throw new DeserializationError(`Parameter '${paramName}' is not nullable but payload is null`)
} else if (!data) {
data = JSON.parse(value)
if (typeof data !== 'object') {
throw new DeserializationError('Value for action parameters must be an object.')
}
}
let paramValue = data[paramName]
if (paramValue === undefined) {
// OData JSON Format Version 4.0 Plus Errata 03 - 17 Action Invocation:
// "Any parameter values not specified in the JSON object are assumed to have the null value."
//
// Set the value to null because further algorithm asserts nullable values already.
// Therefore the value must be null, not undefined.
paramValue = null
}
this._assertPropertyIsCollection(edmParam, paramValue)
const edmType = edmParam.getType()
switch (edmType.getKind()) {
case EdmTypeKind.PRIMITIVE:
case EdmTypeKind.ENUM:
case EdmTypeKind.DEFINITION:
result[paramName] = this._deserializePrimitive(edmParam, paramValue)
break
case EdmTypeKind.COMPLEX:
case EdmTypeKind.ENTITY: // Both are structured types.
this._deserializeComplex(edmParam, paramValue, [], [])
result[paramName] = paramValue
break
default:
throw new DeserializationError(
`Could not deserialize parameter '${paramName}'. EdmTypeKind '${edmType.getKind()}' is invalid.`
)
}
}
const names = data ? Object.keys(data) : []
const wrongParameter = names.find(name => !parameters.some(p => p[0] === name))
if (wrongParameter) {
throw new DeserializationError(
`'${wrongParameter}' is not a non-binding parameter of action '${edmAction.getName()}'.`
)
}
return result
}
/**
* Deserializes a value for a structural type with its properties.
* @param {EdmEntityType|EdmComplexType} edmType the EDM type of the provided value
* @param {Object} structureValue the structural object to deserialize
* @param {?(EdmProperty[])} nesting the complex properties the object is nested in
* @param {boolean} isDelta whether the structural object is inside a delta annotation
* @param {ExpandItem[]} expand The current expand items
* @param {Object} additionalInformation additional information to be set in the deserializer
* @throws {DeserializationError} if provided data can not be deserialized
* @private
*/
_deserializeStructuralType (edmType, structureValue, nesting, isDelta, expand, additionalInformation) {
if (typeof structureValue !== 'object' || Array.isArray(structureValue)) {
throw new DeserializationError('Value for structural type must be an object.')
}
for (const [name, value] of Object.entries(structureValue)) {
if (name.includes('@')) {
this._deserializeAnnotation(
edmType,
structureValue,
name,
value,
nesting !== null,
isDelta,
additionalInformation
)
} else {
const edmProperty = edmType.getProperty(name)
this._assertPropertyExists(edmProperty, edmType, name)
this._assertPropertyIsCollection(edmProperty, value)
let structValue = structureValue
const propertyType = edmProperty.getEntityType ? edmProperty.getEntityType() : edmProperty.getType()
// REVISIT: unofficial!!!
// !propertyType && cds.env.odata.asProvided -> just use the provided value
if (!propertyType && cds.env.odata.asProvided) {
continue
}
switch (propertyType.getKind()) {
case EdmTypeKind.COMPLEX:
this._deserializeComplex(
edmProperty,
value,
(nesting || []).concat(edmProperty),
expand,
additionalInformation
)
break
case EdmTypeKind.ENTITY:
this._deserializeNavigation(edmProperty, value, nesting || [], expand, additionalInformation)
break
default:
structValue[name] = this._deserializePrimitive(edmProperty, value)
break
}
}
}
}
/**
* Deserializes an annotation.
* @param {EdmEntityType|EdmComplexType} edmType the EDM type of the structure the annotation is part of
* @param {Object} outerValue the structure the annotation is part of
* @param {string} name the name of the annotation
* @param {?(string|string[]|Object|Object[])} value the value of the annotation
* @param {boolean} isNested whether the structural object is nested in another object
* @param {boolean} isDelta whether the structural object is inside a delta annotation
* @param {Object} additionalInformation additional information to be set in the deserializer
* @throws {DeserializationError} if provided data can not be deserialized
* @private
*/
_deserializeAnnotation (edmType, outerValue, name, value, isNested, isDelta, additionalInformation) {
let structureValue = outerValue
if (name === JsonAnnotations.CONTEXT && !isNested) {
// Context URL is allowed only in outermost structure.
} else if (name === JsonAnnotations.ID && edmType.getKind() === EdmTypeKind.ENTITY) {
if (value !== null) structureValue[name] = this._parseEntityUri(edmType, value)
} else if (name.endsWith(JsonAnnotations.TYPE)) {
// Validate that the type specified in the annotation is exactly the type declared in the EDM.
const propertyName = name.substring(0, name.length - JsonAnnotations.TYPE.length)
let expectedType = edmType
let isCollection = false
if (propertyName) {
const edmProperty = edmType.getProperty(propertyName)
this._assertPropertyExists(edmProperty, edmType, propertyName)
expectedType = edmProperty.getType ? edmProperty.getType() : edmProperty.getEntityType()
isCollection = edmProperty.isCollection()
}
const expectedTypeName =
expectedType.getKind() === EdmTypeKind.PRIMITIVE ? expectedType.getName() : expectedType.getFullQualifiedName()
const typeName =
typeof value === 'string' &&
value.startsWith(isCollection ? '#Collection(' : '#') &&
value.endsWith(isCollection ? ')' : '')
? value.substring(isCollection ? 12 : 1, value.length - (isCollection ? 1 : 0))
: null
// The type name could be an alias-qualified name; for that case we have to do an EDM look-up.
const fullQualifiedName =
typeName && typeName.indexOf('.') > 0 && typeName.lastIndexOf('.') < typeName.length - 1
? FullQualifiedName.createFromNameSpaceAndName(typeName)
: null
if (
typeName !== expectedTypeName &&
(!fullQualifiedName ||
(this._edm.getEntityType(fullQualifiedName) ||
this._edm.getComplexType(fullQualifiedName) ||
this._edm.getEnumType(fullQualifiedName) ||
this._edm.getTypeDefinition(fullQualifiedName)) !== expectedType)
) {
throw new DeserializationError(
"The value of '" + name + "' must describe correctly the type '" + expectedType.getFullQualifiedName() + "'."
)
}
} else if (name.endsWith(JsonAnnotations.BIND) && !isDelta) {
const navigationPropertyName = name.substring(0, name.length - JsonAnnotations.BIND.length)
const edmNavigationProperty = edmType.getNavigationProperty(navigationPropertyName)
this._assertPropertyExists(edmNavigationProperty, edmType, navigationPropertyName)
this._assertPropertyIsCollection(edmNavigationProperty, value)
this._assertPropertyNullable(edmNavigationProperty, value)
const edmEntityType = edmNavigationProperty.getEntityType()
structureValue[name] = Array.isArray(value)
? value.map(uri => this._parseEntityUri(edmEntityType, uri))
: this._parseEntityUri(edmEntityType, value)
} else if (name.endsWith(JsonAnnotations.DELTA)) {
const navigationPropertyName = name.substring(0, name.length - JsonAnnotations.DELTA.length)
this._deserializeDelta(edmType, navigationPropertyName, value, additionalInformation)
additionalInformation.hasDelta = true // eslint-disable-line no-param-reassign
} else if (name === JsonAnnotations.REMOVED && isDelta) {
if (
typeof value !== 'object' ||
Array.isArray(value) ||
Object.keys(value).length > 1 ||
(Object.keys(value).length === 1 && value.reason !== 'changed' && value.reason !== 'deleted')
) {
throw new DeserializationError(
"The value of '" +
JsonAnnotations.REMOVED +
"' must be an object with an " +
"optional property 'reason' with value 'changed' or 'deleted'."
)
}
if (
!structureValue[JsonAnnotations.ID] &&
!Array.from(edmType.getKeyPropertyRefs().keys()).every(keyName => structureValue[keyName])
) {
throw new DeserializationError("'" + JsonAnnotations.REMOVED + "' must identify an entity.")
}
} else {
throw new DeserializationError("Annotation '" + name + "' is not supported.")
}
}
/**
* Deserializes a navigation property and fills an expand item for deep inserts.
* @param {EdmNavigationProperty} edmProperty the EDM navigation property to deserialize
* @param {Object|Object[]} value the value of the navigation property
* @param {EdmProperty[]} nesting the complex properties the navigation property is nested in
* @param {ExpandItem[]} expandArray the current expand items
* @param {Object} additionalInformation additional information to be set in the deserializer
* @private
*/
_deserializeNavigation (edmProperty, value, nesting, expandArray, additionalInformation) {
this._assertPropertyNullable(edmProperty, value)
if (value === null) return
let currentExpandItem = expandArray.find(expandItem => {
const segments = expandItem.getPathSegments()
return segments.every((segment, index) =>
index < segments.length - 1
? segment.getProperty() === nesting[index]
: segment.getNavigationProperty() === edmProperty
)
})
if (!currentExpandItem) {
currentExpandItem = this._createExpandItem(nesting, edmProperty)
expandArray.push(currentExpandItem)
}
const type = edmProperty.getEntityType()
let newExpandOptionArray = []
if (edmProperty.isCollection()) {
for (let entity of value) {
this._deserializeStructuralType(type, entity, [], false, newExpandOptionArray, additionalInformation)
}
} else {
this._deserializeStructuralType(type, value, [], false, newExpandOptionArray, additionalInformation)
}
let innerExpandItems = currentExpandItem.getOption(UriInfo.QueryOptions.EXPAND) || []
for (const newExpand of newExpandOptionArray) innerExpandItems.push(newExpand)
if (innerExpandItems.length) currentExpandItem.setOption(UriInfo.QueryOptions.EXPAND, innerExpandItems)
}
/**
* Deserializes a primitive and primitive collection value.
* @param {EdmProperty} edmProperty the EDM property of this primitive value
* @param {?(number|string|boolean|Object|Array)} propertyValue the JSON value
* @returns {?(number|string|boolean|Buffer|Object|Array)} the deserialized result
* @throws {DeserializationError} if provided data can not be deserialized
* @private
*/
_deserializePrimitive (edmProperty, propertyValue) {
// OASIS issue 1177: "Streams that are annotated as the application/json media type [...]
// are represented as native JSON in JSON requests and responses [...]
// The odata.mediaContentType control information is only necessary if the embedded JSON happens to be a
// JSON string, in all other cases it can be heuristically determined that the stream value is JSON."
// TODO: Check that JSON is an acceptable media type for this stream property.
// TODO: Validate the JSON content against the JSON schema if there is one in the metadata.
let type = edmProperty.getType()
if (type.getKind() === EdmTypeKind.DEFINITION) type = type.getUnderlyingType()
if (type === EdmPrimitiveTypeKind.Stream) return propertyValue
return edmProperty.isCollection()
? propertyValue && propertyValue.map(value => this._decoder.decodeJson(value, edmProperty))
: this._decoder.decodeJson(propertyValue, edmProperty)
}
/**
* Deserializes a complex and complex collection value.
* @param {EdmProperty} edmProperty the EDM property of this complex value
* @param {?(Object|Object[])} propertyValue the JSON value
* @param {EdmProperty[]} nesting the complex properties the complex value is nested in
* @param {ExpandItem[]} expand the current expand items
* @param {Object} additionalInformation additional information to be set in the deserializer
* @throws {DeserializationError} if provided data can not be deserialized
* @private
*/
_deserializeComplex (edmProperty, propertyValue, nesting, expand, additionalInformation) {
const type = edmProperty.getType()
if (edmProperty.isCollection()) {
for (let value of propertyValue) {
this._assertPropertyNullable(edmProperty, value)
if (value === null) continue
this._deserializeStructuralType(type, value, nesting, false, expand, additionalInformation)
}
} else {
this._assertPropertyNullable(edmProperty, propertyValue)
if (propertyValue === null) return
this._deserializeStructuralType(type, propertyValue, nesting, false, expand, additionalInformation)
}
}
/**
* Deserializes a delta annotation for a navigation property.
* @param {EdmEntityType} edmType the EDM type of the parent entity
* @param {string} propertyName the name of the navigation property
* @param {any} value the value of the delta annotation of the navigation property
* @param {Object} additionalInformation additional information to be set in the deserializer
* @private
*/
_deserializeDelta (edmType, propertyName, value, additionalInformation) {
const edmNavigationProperty = edmType.getNavigationProperty(propertyName)
this._assertPropertyExists(edmNavigationProperty, edmType, propertyName)
if (!edmNavigationProperty.isCollection()) {
throw new DeserializationError("'" + propertyName + "' must not have a delta annotation.")
}
if (!Array.isArray(value)) {
throw new DeserializationError(
"The value of the delta annotation of '" + propertyName + "' must be a collection."
)
}
const innerEdmType = edmNavigationProperty.getEntityType()
for (const entity of value) {
this._deserializeStructuralType(innerEdmType, entity, [], true, [], additionalInformation)
}
}
/**
* Asserts that the provided property value is a collection if the corresponding EDM property is a collection.
* @param {EdmProperty|EdmNavigationProperty} edmProperty the EDM property for the corresponding property value
* @param {*} propertyValue the value of the property
* @throws {DeserializationError} if the property value is a collection while EDM property is not and vice versa
* @private
*/
_assertPropertyIsCollection (edmProperty, propertyValue) {
if (edmProperty.isCollection() && propertyValue && !Array.isArray(propertyValue)) {
const type = edmProperty.getType ? edmProperty.getType() : edmProperty.getEntityType()
throw new DeserializationError(
`'${edmProperty.getName()}' must be a collection of type '${type.getFullQualifiedName()}'.`
)
}
if (!edmProperty.isCollection() && Array.isArray(propertyValue)) {
throw new DeserializationError(`'${edmProperty.getName()}' must not be a collection.`)
}
}
/**
* Asserts that the provided EDM property is defined.
* @param {EdmProperty|EdmNavigationProperty} edmProperty the EDM property to check
* @param {EdmType} edmType the EDM type in which the EDM property is defined
* @param {string} propertyName the name of the property
* @throws {DeserializationError} if the provided EDM property is not defined
* @private
*/
_assertPropertyExists (edmProperty, edmType, propertyName) {
if (!edmProperty) {
const fqn = edmType.getFullQualifiedName()
throw new DeserializationError(`'${propertyName}' does not exist in type '${fqn}'.`)
}
}
/**
* Asserts that the provided EDM property is nullable if it has a null value.
* @param {EdmProperty|EdmNavigationProperty} edmProperty the EDM property to check
* @param {*} propertyValue the value of the property
* @throws {DeserializationError} if null is not allowed
* @private
*/
_assertPropertyNullable (edmProperty, propertyValue) {
if (propertyValue === null && !edmProperty.isNullable()) {
throw new DeserializationError(
`The property '${edmProperty.getName()}' is not nullable and must not have a null value.`
)
}
}
/**
* Parses and checks a URI given as reference to an entity.
* @param {EdmEntityType} edmEntityType the EDM type of the entity
* @param {string} uri the URI
* @returns {UriInfo} the parsed URI
* @private
*/
_parseEntityUri (edmEntityType, uri) {
if (uri === null) return null
if (typeof uri !== 'string') {
throw new DeserializationError(
`The reference URI for type '${edmEntityType.getFullQualifiedName()}' must be a string.`
)
}
const uriInfo = new UriParser(this._edm).parseRelativeUri(uri)
if (
!uriInfo
.getPathSegments()
.every(
segment =>
segment.getKind() === UriResource.ResourceKind.ENTITY ||
(segment.getKind() === UriResource.ResourceKind.NAVIGATION_TO_ONE &&
segment.getNavigationProperty().containsTarget())
) ||
uriInfo.getFinalEdmType() !== edmEntityType
) {
throw new DeserializationError(
`The reference URI '${uri}' is not suitable for type '${edmEntityType.getFullQualifiedName()}'.`
)
}
return uriInfo
}
/**
* Deserializes a provided entity-reference object.
* @param {EdmType} edmType the EDM type of the entity
* @param {Object} value the reference object to deserialize
* @returns {UriInfo} the deserialized result
* @throws {DeserializationError} if provided data can not be deserialized
* @private
*/
_deserializeReference (edmType, value) {
const objectKeys = Object.keys(value)
if (objectKeys.length === 0) {
throw new DeserializationError(`Value for type '${edmType.getFullQualifiedName()}' has no properties.`)
}
let uriInfo
for (const propertyName of objectKeys) {
if (propertyName === JsonAnnotations.ID) {
uriInfo = this._parseEntityUri(edmType, value[propertyName])
if (uriInfo === null) {
throw new DeserializationError(
`The reference URI for type '${edmType.getFullQualifiedName()}' must be a string.`
)
}
} else if (odataAnnotations.has(propertyName) || propertyName === JsonAnnotations.TYPE) {
this._deserializeAnnotation(edmType, value, propertyName, value[propertyName])
} else {
throw new DeserializationError(`Property or annotation '${propertyName}' is not supported.`)
}
}
return uriInfo
}
/**
* Creates an expand item for a navigation property.
* @param {EdmProperty[]} nesting the complex properties the navigation property is nested in
* @param {EdmNavigationProperty} edmNavigationProperty the EDM navigation property
* @returns {ExpandItem} the expand item
* @private
*/
_createExpandItem (nesting, edmNavigationProperty) {
return new ExpandItem().setPathSegments(
nesting
.map(complexProperty =>
new UriResource().setKind(UriResource.ResourceKind.COMPLEX_PROPERTY).setProperty(complexProperty)
)
.concat([
new UriResource()
.setKind(
edmNavigationProperty.isCollection()
? UriResource.ResourceKind.NAVIGATION_TO_MANY
: UriResource.ResourceKind.NAVIGATION_TO_ONE
)
.setNavigationProperty(edmNavigationProperty)
.setIsCollection(edmNavigationProperty.isCollection())
])
)
}
} |
JavaScript | class Wire {
constructor(node1, node2, scope) {
this.objectType = 'Wire';
this.node1 = node1;
this.scope = scope;
this.node2 = node2;
this.type = 'horizontal';
this.updateData();
this.scope.wires.push(this);
forceResetNodesSet(true);
}
// if data changes
updateData() {
this.x1 = this.node1.absX();
this.y1 = this.node1.absY();
this.x2 = this.node2.absX();
this.y2 = this.node2.absY();
if (this.x1 === this.x2) this.type = 'vertical';
}
updateScope(scope) {
this.scope = scope;
this.checkConnections();
}
// to check if nodes are disconnected
checkConnections() {
var check = this.node1.deleted || this.node2.deleted || !this.node1.connections.contains(this.node2) || !this.node2.connections.contains(this.node1);
if (check) this.delete();
return check;
}
dblclick() {
if(this.node1.parent == globalScope.root && this.node2.parent == globalScope.root) {
simulationArea.multipleObjectSelections = [this.node1, this.node2];
simulationArea.lastSelected = undefined;
}
}
update() {
var updated = false;
if (embed) return updated;
if (this.node1.absX() === this.node2.absX()) {
this.x1 = this.x2 = this.node1.absX();
this.type = 'vertical';
} else if (this.node1.absY() === this.node2.absY()) {
this.y1 = this.y2 = this.node1.absY();
this.type = 'horizontal';
}
// if (wireToBeChecked && this.checkConnections()) {
// this.delete();
// return updated;
// } // SLOW , REMOVE
if (simulationArea.shiftDown === false && simulationArea.mouseDown === true && simulationArea.selected === false && this.checkWithin(simulationArea.mouseDownX, simulationArea.mouseDownY)) {
simulationArea.selected = true;
simulationArea.lastSelected = this;
updated = true;
} else if (simulationArea.mouseDown && simulationArea.lastSelected === this && !this.checkWithin(simulationArea.mouseX, simulationArea.mouseY)) {
var n = new Node(simulationArea.mouseDownX, simulationArea.mouseDownY, 2, this.scope.root);
n.clicked = true;
n.wasClicked = true;
simulationArea.lastSelected = n;
this.converge(n);
}
// eslint-disable-next-line no-empty
if (simulationArea.lastSelected === this) {
}
if (this.node1.deleted || this.node2.deleted) {
this.delete();
return updated;
} // if either of the nodes are deleted
if (simulationArea.mouseDown === false) {
if (this.type === 'horizontal') {
if (this.node1.absY() !== this.y1) {
// if(this.checkConnections()){this.delete();return;}
n = new Node(this.node1.absX(), this.y1, 2, this.scope.root);
this.converge(n);
updated = true;
} else if (this.node2.absY() !== this.y2) {
// if(this.checkConnections()){this.delete();return;}
n = new Node(this.node2.absX(), this.y2, 2, this.scope.root);
this.converge(n);
updated = true;
}
} else if (this.type === 'vertical') {
if (this.node1.absX() !== this.x1) {
// if(this.checkConnections()){this.delete();return;}
n = new Node(this.x1, this.node1.absY(), 2, this.scope.root);
this.converge(n);
updated = true;
} else if (this.node2.absX() !== this.x2) {
// if(this.checkConnections()){this.delete();return;}
n = new Node(this.x2, this.node2.absY(), 2, this.scope.root);
this.converge(n);
updated = true;
}
}
}
return updated;
}
draw() {
// for calculating min-max Width,min-max Height
//
const ctx = simulationArea.context;
var color;
if (simulationArea.lastSelected == this) {
color = colors['color_wire_sel'];
} else if (this.node1.value == undefined || this.node2.value == undefined) {
color = colors['color_wire_lose'];
} else if (this.node1.bitWidth == 1) {
color = [colors['color_wire_lose'], colors['color_wire_con'], colors['color_wire_pow']][this.node1.value + 1];
} else {
color = colors['color_wire'];
}
drawLine(ctx, this.node1.absX(), this.node1.absY(), this.node2.absX(), this.node2.absY(), color, 3);
}
// checks if node lies on wire
checkConvergence(n) {
return this.checkWithin(n.absX(), n.absY());
}
// fn checks if coordinate lies on wire
checkWithin(x, y) {
if ((this.type === 'horizontal') && (this.node1.absX() < this.node2.absX()) && (x > this.node1.absX()) && (x < this.node2.absX()) && (y === this.node2.absY())) return true;
if ((this.type === 'horizontal') && (this.node1.absX() > this.node2.absX()) && (x < this.node1.absX()) && (x > this.node2.absX()) && (y === this.node2.absY())) return true;
if ((this.type === 'vertical') && (this.node1.absY() < this.node2.absY()) && (y > this.node1.absY()) && (y < this.node2.absY()) && (x === this.node2.absX())) return true;
if ((this.type === 'vertical') && (this.node1.absY() > this.node2.absY()) && (y < this.node1.absY()) && (y > this.node2.absY()) && (x === this.node2.absX())) return true;
return false;
}
// add intermediate node between these 2 nodes
converge(n) {
this.node1.connect(n);
this.node2.connect(n);
this.delete();
}
delete() {
forceResetNodesSet(true);
updateSimulationSet(true);
this.node1.connections.clean(this.node2);
this.node2.connections.clean(this.node1);
this.scope.wires.clean(this);
this.node1.checkDeleted();
this.node2.checkDeleted();
}
} |
JavaScript | class RevisionDetailsModel {
/**
* Constructor for RevisionDetails Model.
*/
constructor() {
this._idbHelper = new IDBHelper(dbName, dbVersion, dbStorename);
}
/**
* This method gets the revision details for a given entryID.
* @param {String} entryID The ID of the revision.
* @return {Promise<String|null>} Returns a revision string or
* null if there is no revision information.
*/
get(entryID) {
return this._idbHelper.get(entryID);
}
/**
* This method saves the revision details to indexedDB.
* @param {String} entryID The ID of the revision.
* @param {String} revision The current revision for this entryID.
* @return {Promise} Promise that resolves once the data has been saved.
*/
put(entryID, revision) {
return this._idbHelper.put(entryID, revision);
}
/**
* This method closes the indexdDB helper. This is only used for unit testing
* to ensure clean state between tests.
*
* @private
*/
_close() {
this._idbHelper.close();
}
} |
JavaScript | class AutonomousDatabaseView extends OkitDesignerArtefactView {
constructor(artefact=null, json_view) {
super(artefact, json_view);
}
get parent_id() {
let subnet = this.getJsonView().getSubnet(this.artefact.subnet_id);
if (subnet && subnet.compartment_id === this.artefact.compartment_id) {
console.info('Using Subnet as parent');
return this.subnet_id;
} else {
console.info('Using Compartment as parent');
return this.compartment_id;
}
}
get parent() {return this.getJsonView().getSubnet(this.parent_id) ? this.getJsonView().getSubnet(this.parent_id) : this.getJsonView().getCompartment(this.parent_id);}
get minimum_width() {return 135;}
get minimum_height() {return 100;}
/*
** Clone Functionality
*/
clone() {
return new AutonomousDatabaseView(this.artefact, this.getJsonView());
}
/*
** SVG Processing
*/
// Additional draw Processing
draw1() {
console.log('Drawing ' + this.getArtifactReference() + ' : ' + this.getArtefact().id + ' [' + this.parent_id + ']');
let svg = super.draw();
/*
** Add Properties Load Event to created svg. We require the definition of the local variable "me" so that it can
** be used in the function dur to the fact that using "this" in the function will refer to the function not the
** Artifact.
*/
// Get Inner Rect to attach Connectors
let rect = svg.select("rect[id='" + safeId(this.id) + "']");
if (rect && rect.node()) {
let boundingClientRect = rect.node().getBoundingClientRect();
// Add Connector Data
svg.attr("data-compartment-id", this.compartment_id)
.attr("data-connector-start-y", boundingClientRect.y + (boundingClientRect.height / 2))
.attr("data-connector-start-x", boundingClientRect.x)
.attr("data-connector-end-y", boundingClientRect.y + (boundingClientRect.height / 2))
.attr("data-connector-end-x", boundingClientRect.x)
.attr("data-connector-id", this.id)
.attr("dragable", true)
.selectAll("*")
.attr("data-connector-start-y", boundingClientRect.y + (boundingClientRect.height / 2))
.attr("data-connector-start-x", boundingClientRect.x)
.attr("data-connector-end-y", boundingClientRect.y + (boundingClientRect.height / 2))
.attr("data-connector-end-x", boundingClientRect.x)
.attr("data-connector-id", this.id)
.attr("dragable", true);
}
console.log();
return svg;
}
// Return Artifact Specific Definition.
getSvgDefinition() {
let definition = this.newSVGDefinition(this, this.getArtifactReference());
let first_child = this.getParent().getChildOffset(this.getArtifactReference());
definition['svg']['x'] = first_child.dx;
definition['svg']['y'] = first_child.dy;
definition['svg']['align'] = "center";
definition['svg']['width'] = this.dimensions['width'];
definition['svg']['height'] = this.dimensions['height'];
definition['rect']['stroke']['colour'] = stroke_colours.bark;
definition['rect']['stroke']['dash'] = 1;
definition['rect']['height_adjust'] = (Math.round(icon_height / 2) * -1);
definition['name']['show'] = true;
definition['name']['align'] = "center";
return definition;
}
/*
** Property Sheet Load function
*/
loadProperties() {
let okitJson = this.getOkitJson();
let me = this;
$(jqId(PROPERTIES_PANEL)).load("propertysheets/autonomous_database.html", () => {
$('#is_free_tier').on('change', () => {
if($('#is_free_tier').is(':checked')) {
$('#license_model').val("LICENSE_INCLUDED");
$('#is_auto_scaling_enabled').prop('checked', false);
$('#license_model').attr('disabled', true);
$('#is_auto_scaling_enabled').attr('disabled', true);
} else {
$('#license_model').removeAttr('disabled');
$('#is_auto_scaling_enabled').removeAttr('disabled');
}
});
if (me.is_free_tier) {
me.artefact.license_model = "LICENSE_INCLUDED";
me.artefact.is_auto_scaling_enabled = false;
$('#license_model').attr('disabled', true);
$('#is_auto_scaling_enabled').attr('disabled', true);
}
// Load Reference Ids
// Network Security Groups
this.loadNetworkSecurityGroups('nsg_ids', this.subnet_id);
/*
let network_security_groups_select = d3.select(d3Id('nsg_ids'));
for (let network_security_group of okitJson.network_security_groups) {
let div = network_security_groups_select.append('div');
div.append('input')
.attr('type', 'checkbox')
.attr('id', safeId(network_security_group.id))
.attr('value', network_security_group.id);
div.append('label')
.attr('for', safeId(network_security_group.id))
.text(network_security_group.display_name);
}
*/
// Subnets
let subnet_select = $(jqId('subnet_id'));
subnet_select.append($('<option>').attr('value', '').text(''));
for (let subnet of okitJson.subnets) {
subnet_select.append($('<option>').attr('value', subnet.id).text(subnet.display_name));
}
loadPropertiesSheet(me.artefact);
});
}
/*
** Load and display Value Proposition
*/
loadValueProposition() {
$(jqId(VALUE_PROPOSITION_PANEL)).load("valueproposition/autonomous_database.html");
}
/*
** Static Functionality
*/
static getArtifactReference() {
return AutonomousDatabase.getArtifactReference();
}
static getDropTargets() {
return [Compartment.getArtifactReference(), Subnet.getArtifactReference()];
}
} |
JavaScript | class MailToLink {
/**
* Create link from obscured element
* @param {object} el - dom node
*/
constructor(el) {
this.el = el;
let link, dataAttr, href;
// Generate mailto href
try {
dataAttr = el.getAttribute("data-email");
href = `mailto:${this.replaceObscuredString(dataAttr)}`;
} catch (e) {
throw Error("MailToLink: constructor requires a DOM node object");
}
// Replace [at] with @ in link text
let linkHtml = el.innerHTML;
if (linkHtml.indexOf(obscureString) > 0) {
linkHtml = this.replaceObscuredString(linkHtml);
el.innerHTML = linkHtml;
}
// Add mailto href to link tags
if (el.nodeName === "A") {
el.setAttribute("href", href);
} else {
// Create link tag, remove original element
const classNames = el.getAttribute("class");
link = this.createLinkReplacement(href, linkHtml, classNames);
// Insert link and remove original element
el.insertAdjacentHTML("beforebegin", link.outerHTML);
el.parentNode.removeChild(el);
// replace instance el with new element
this.el = link;
}
}
/**
* Create link to replace the original element
* @param {string} href - value to apply to link
* @param {string} body - body to insert to link
* @param {string} classNames - values to add to the link
* @returns {object} link - DOM element
*/
createLinkReplacement(href, body, classNames = "") {
let link = document.createElement("a");
link.setAttribute("href", href);
if (classNames) {
link.setAttribute("class", classNames);
}
link.innerHTML = body;
return link;
}
/**
* Replace obscured string with valid email address
* @param {string} str - obscured email string
* @return {string} newStr - valid email string
*/
replaceObscuredString(str) {
let newStr;
try {
newStr = str.replace(obscureString, "@");
} catch (e) {
throw Error(
"MailToLink: `data-email` attribute for mailto replacement. Link not created"
);
}
return newStr;
}
} |
JavaScript | class Edit_DueDate extends Component {
onPressBack(){
this.props.navigation.navigate('Main1')
}
render() {
return (
<Container>
<Header >
<View style = { styles.MainContainer1}>
<Button transparent onPress={()=>this.onPressBack()}>
<Icon name='ios-arrow-back' style={{color:'#DBDBDB'}} />
</Button>
</View>
<View style = { styles.MainContainer2 }>
<Title>Edit</Title>
</View>
<View style={{flex: 1, alignItems: 'center',justifyContent: 'center', left: 15}}>
<Image style={{width: 20, height: 20}}source={{uri: 'https://sv1.picz.in.th/images/2020/01/24/RrBuNt.png' }}/>
</View>
</Header>
{/* <ActionButton buttonColor="rgba(75,21,184,2)" position="center"></ActionButton> */}
<View style={{flex:1,flexDirection:'column',backgroundColor:'#F6F6F6'}} >
<TouchableOpacity style={{flex:0.08,flexDirection:'row',marginTop:20,backgroundColor:'#ffffff', alignItems:'center'}}>
<Image style={{marginLeft:30, marginRight:10 ,width:25,height:25}} source={{uri:'https://sv1.picz.in.th/images/2020/01/24/Rr9eWe.png'}}/>
<View style={{flexDirection: 'column'}} >
<Text style={{fontSize:20,fontWeight:'bold' ,color:'#171D33',marginLeft:10,marginEnd:3,alignItems:'center',justifyContent:'center'}}>Get a Haircut</Text>
</View>
<Text style={{fontSize:16 , color:'#D4D4D4', marginLeft:140}}></Text>
<Image style={{marginLeft:30, marginRight:10 ,width:15,height:15}} source={{uri:'https://sv1.picz.in.th/images/2020/01/24/RrTgsz.png'}}/>
</TouchableOpacity>
<TouchableOpacity style={{flex:0.08,flexDirection:'row',marginTop:20,backgroundColor:'#ffffff', alignItems:'center'}}>
<Image style={{marginLeft:25, marginRight:10 ,width:28,height:28}} source={{uri:'https://sv1.picz.in.th/images/2020/01/24/RrkimE.png'}}/>
<View style={{flexDirection: 'column'}} >
<Text style={{fontSize:18,color:'#171D33',marginLeft:10,marginEnd:3,alignItems:'center',justifyContent:'center'}}>Pomodoro Number</Text>
</View>
<Text style={{fontSize:16 , color:'#D4D4D4', marginLeft:135}}>1</Text>
</TouchableOpacity>
<TouchableOpacity style={{flex:0.08,flexDirection:'row', backgroundColor:'#ffffff', alignItems:'center'}}>
<Image style={{marginLeft:25, marginRight:10 ,width:30,height:30}} source={{uri:'https://sv1.picz.in.th/images/2020/01/24/Rr3Loy.png'}}/>
<View style={{flexDirection: 'column'}} >
<Text style={{fontSize:18,color:'#171D33',marginLeft:10,marginEnd:3,alignItems:'center',justifyContent:'center'}}>Due Date</Text>
</View>
<Text style={{fontSize:16 , color:'#D4D4D4', marginLeft:170}}>Today</Text>
</TouchableOpacity>
<TouchableOpacity style={{flex:0.1,flexDirection:'column',marginTop:20,backgroundColor:'#F6F6F6', alignItems:'center'}}>
<View style={{flexDirection: 'column'}} >
<Text style={{fontSize:18,color:'#0000000',marginLeft:10,marginEnd:3,alignItems:'center',justifyContent:'center'}}>Today</Text>
<Text style={{fontSize:15,color:'#A2A2A2',marginLeft:3,marginEnd:3,alignItems:'center',justifyContent:'center'}}>Tomorrow</Text>
<Text style={{fontSize:12,color:'#D4D4D4',marginLeft:5,marginEnd:3,alignItems:'center',justifyContent:'center'}}>Fri, 24 Jan</Text>
</View>
</TouchableOpacity>
<TouchableOpacity style={{flex:0.08,flexDirection:'row',marginTop:20,backgroundColor:'#ffffff', alignItems:'center'}}>
<Image style={{marginLeft:25, marginRight:10 ,width:25,height:25}} source={{uri:'https://sv1.picz.in.th/images/2020/01/24/Rr3eJD.png'}}/>
<View style={{flexDirection: 'column'}} >
<Text style={{fontSize:18,color:'#171D33',marginLeft:10,marginEnd:3,alignItems:'center',justifyContent:'center'}}>Reminder</Text>
</View>
<Text style={{fontSize:16 , color:'#D4D4D4', marginLeft:192}}>None</Text>
</TouchableOpacity>
<TouchableOpacity style={{flex:0.08,flexDirection:'row',backgroundColor:'#ffffff', alignItems:'center'}}>
<Image style={{marginLeft:25, marginRight:10 ,width:25,height:25}} source={{uri:'https://sv1.picz.in.th/images/2020/01/24/Rr3F5J.png'}}/>
<View style={{flexDirection: 'column'}} >
<Text style={{fontSize:18,color:'#171D33',marginLeft:10,marginEnd:3,alignItems:'center',justifyContent:'center'}}>Repeat</Text>
</View>
<Text style={{fontSize:16 , color:'#D4D4D4', marginLeft:210}}>None</Text>
</TouchableOpacity>
<TouchableOpacity style={{flex:0.08,flexDirection:'row',marginTop:20,backgroundColor:'#ffffff',alignItems:'center'}}>
<Text style={{fontSize:18 , color:'#D4D4D4', marginLeft:25, }}>Add a note...</Text>
</TouchableOpacity>
</View>
</Container>
);
}
} |
JavaScript | class LinearRegression {
constructor(features, labels, options) {
this.features = this.processFeatures(features);
this.labels = tf.tensor(labels);
this.mseHistory = [];
this.options = Object.assign({
learningRate: 0.1,
iterations: 1000
},
options
);
this.weights = tf.zeros([this.features.shape[1], 1]);
}
gradientDescent(features, labels) {
const currentGuesses = features.matMul(this.weights);
const differences = currentGuesses.sub(labels);
const slopes = features
.transpose()
.matMul(differences)
.div(features.shape[0]);
this.weights = this.weights.sub(slopes.mul(this.options.learningRate));
}
train() {
const batchQuantity = Math.floor(
this.features.shape[0] / this.options.batchSize
);
for (let i = 0; i < this.options.iterations; i++) {
for (let j = 0; j < batchQuantity; j++) {
const startIndex = j * this.options.batchSize;
const {
batchSize
} = this.options;
const featureSlice = this.features.slice(
[startIndex, 0],
[batchSize, -1]
);
const labelSlice = this.labels.slice([startIndex, 0], [batchSize, -1]);
//console.log(featureSlice.arraySync(), labelSlice.arraySync());
this.gradientDescent(featureSlice, labelSlice);
}
this.recordMSE();
this.updateLearningRate();
}
}
predict(observations) {
return this.processFeatures(observations).matMul(this.weights);
}
test(testFeatures, testLabels) {
testFeatures = this.processFeatures(testFeatures);
testLabels = tf.tensor(testLabels);
const predictions = testFeatures.matMul(this.weights);
//console.log('predictions = ', predictions.arraySync());
const res = testLabels
.sub(predictions)
.pow(2)
.sum()
.arraySync();
const tot = testLabels
.sub(testLabels.mean())
.pow(2)
.sum()
.arraySync();
//console.log('Res fractions = ', res, tot);
return 1 - res / tot;
}
processFeatures(features) {
features = tf.tensor(features);
features = tf.ones([features.shape[0], 1]).concat(features, 1);
if (this.mean && this.variance) {
features = features.sub(this.mean).div(this.variance.pow(0.5));
} else {
features = this.standardize(features);
}
return features;
}
standardize(features) {
const {
mean,
variance
} = tf.moments(features, 0);
this.mean = mean;
this.variance = variance;
return features.sub(mean).div(variance.pow(0.5));
}
recordMSE() {
const mse = this.features
.matMul(this.weights)
.sub(this.labels)
.pow(2)
.sum()
.div(this.features.shape[0])
.arraySync();
this.mseHistory.unshift(mse);
}
updateLearningRate() {
if (this.mseHistory.length < 2) {
return;
}
if (this.mseHistory[0] > this.mseHistory[1]) {
this.options.learningRate /= 2;
} else {
this.options.learningRate *= 1.05;
}
}
} |
JavaScript | class StreamReader {
constructor(string, start, end) {
if (end == null && typeof string === 'string') {
end = string.length;
}
this.string = string;
this.pos = this.start = start || 0;
this.end = end;
}
/**
* Returns true only if the stream is at the end of the file.
* @returns {Boolean}
*/
eof() {
return this.pos >= this.end;
}
/**
* Creates a new stream instance which is limited to given `start` and `end`
* range. E.g. its `eof()` method will look at `end` property, not actual
* stream end
* @param {Point} start
* @param {Point} end
* @return {StreamReader}
*/
limit(start, end) {
return new this.constructor(this.string, start, end);
}
/**
* Returns the next character code in the stream without advancing it.
* Will return NaN at the end of the file.
* @returns {Number}
*/
peek() {
return this.string.charCodeAt(this.pos);
}
/**
* Returns the next character in the stream and advances it.
* Also returns <code>undefined</code> when no more characters are available.
* @returns {Number}
*/
next() {
if (this.pos < this.string.length) {
return this.string.charCodeAt(this.pos++);
}
}
/**
* `match` can be a character code or a function that takes a character code
* and returns a boolean. If the next character in the stream 'matches'
* the given argument, it is consumed and returned.
* Otherwise, `false` is returned.
* @param {Number|Function} match
* @returns {Boolean}
*/
eat(match) {
const ch = this.peek();
const ok = typeof match === 'function' ? match(ch) : ch === match;
if (ok) {
this.next();
}
return ok;
}
/**
* Repeatedly calls <code>eat</code> with the given argument, until it
* fails. Returns <code>true</code> if any characters were eaten.
* @param {Object} match
* @returns {Boolean}
*/
eatWhile(match) {
const start = this.pos;
while (!this.eof() && this.eat(match)) {}
return this.pos !== start;
}
/**
* Backs up the stream n characters. Backing it up further than the
* start of the current token will cause things to break, so be careful.
* @param {Number} n
*/
backUp(n) {
this.pos -= (n || 1);
}
/**
* Get the string between the start of the current token and the
* current stream position.
* @returns {String}
*/
current() {
return this.substring(this.start, this.pos);
}
/**
* Returns substring for given range
* @param {Number} start
* @param {Number} [end]
* @return {String}
*/
substring(start, end) {
return this.string.slice(start, end);
}
/**
* Creates error object with current stream state
* @param {String} message
* @return {Error}
*/
error(message) {
const err = new Error(`${message} at char ${this.pos + 1}`);
err.originalMessage = message;
err.pos = this.pos;
err.string = this.string;
return err;
}
} |
JavaScript | class Pelerin {
/**
* Initialize the pelerin server
*/
constructor(opts = {}) {
// set the server options
this.options = utils.getDefaultOptions(opts)
// initialize the grpc server
this.server = new grpc.Server()
// internal server description
this._description = {}
// internal chains
this._globalchains = []
}
/**
* Returns the handler.
*
* @param {Function} - User's callback.
* @returns {Function} - Handler.
*/
_generateHandler(callback) {
return async (call, grpcCallback) => {
return callback(
new Request(call),
new Response(call, grpcCallback),
() => { } // next execution function
)
}
}
/**
* Adds a global middleware to the chain.
*
* @param {Function} callback - middleware function.
* @returns {object} - this
*/
_chainGlobalMiddleware(callback) {
// generate the handler
const handler = this._generateHandler(callback)
// push to global chains for future embedding
this._globalchains.push(handler)
// chain to existing definitions
for (const [serviceName, handlers] of Object.entries(this._description)) {
for (const handlerName of Object.keys(handlers)) {
this._description[serviceName][handlerName].chains.push(handler)
}
}
}
/**
* Add a service and a handler to the description.
*
* @param {string} path - The path to the service and handler.
* @param {Function} callback - Handler.
* @returns {object} - this
*/
_chainHandlerWithCallback(path, callback) {
// generate the handler
const handler = this._generateHandler(callback)
// split the service path
const splittedPath = path.split("/")
// check if provided path is valid
if (splittedPath.length === 2) {
// get service and handler names
const [serviceName, handlerName] = splittedPath
// create service and handlers if missing
if (!this._description[serviceName]) this._description[serviceName] = {}
if (!this._description[serviceName][handlerName]) this._description[serviceName][handlerName] = {
chains: [],
options: {}
}
// append global chains
if (this._globalchains.length) {
this._description[serviceName][handlerName].chains.push(...this._globalchains)
this._globalchains = []
}
// chain handler
this._description[serviceName][handlerName].chains.push(handler)
} else {
throw new Error("path must be of the following structure {serviceName}/{handlerName}")
}
}
/**
* Add an handler with special settings.
*
* @param {string} path - THe path to the service and handler.
* @param {object} settings - Endpoint settings.
* @param {Function} callback - Handler.
* @returns {object} - this
*/
_chainHandlerWithSettings(path, settings, callback) {
// chain handler
this._chainHandlerWithCallback(path, callback)
// get service and handler name
const [serviceName, handlerName] = path.split("/")
// append settings
this._description[serviceName][handlerName].options = {
...this._description[serviceName][handlerName].options,
...settings
}
}
/**
* Chain splitted code base.
*
* @param {string} service - Service name.
* @param {Router} router - Pelerin router instance.
*/
service(service, router) {
// check if service has a valid value
if (service && service.constructor === String) {
// check if router are instance of pelerin router
if (router && router.constructor === Router) {
// chain each service
for (const [handlerPath, handlerArgs] of Object.entries(router.routes)) {
this.chain(`${service}/${handlerPath}`, ...handlerArgs)
}
} else {
// handle invalid router
throw new Error("handlers are required and must be an instance of Pelerin Router")
}
} else {
// handle invalid service name
throw new Error("service is required and must be of type string")
}
}
/**
* Chain another middleware or service to the server.
*/
chain() {
// get the amount of arguments
const argumentsLen = arguments.length
// recieve only callback - global middleware
if (argumentsLen === 1 && utils.isFunction(arguments[0]))
return this._chainGlobalMiddleware(...arguments)
// receive path and callback
else if (argumentsLen === 2 && arguments[0].constructor === String && utils.isFunction(arguments[1]))
return this._chainHandlerWithCallback(...arguments)
// receive path, settings, and callback
else if (argumentsLen === 3 && arguments[0].constructor === String && arguments[1].constructor === Object && utils.isFunction(arguments[2]))
return this._chainHandlerWithSettings(...arguments)
// unexpected attributes
throw new Error("unexpected values to chain function")
}
/**
* Sign the services and handlers.
*/
_signServices() {
// map services
for (const [serviceName, handlers] of Object.entries(this._description)) {
const service = {}
const executions = {}
// for each handler define the service and executions
for (const [handlerName, handlerDef] of Object.entries(handlers)) {
// define the service definition
service[handlerName] = {
...utils.getDefaultServiceDefinition(),
...this._description[serviceName][handlerName].options,
path: `/${this.options.protoName}.${serviceName}/${handlerName}`
}
// set execution map
executions[handlerName] = (call, callback) => {
for (const cb of handlerDef.chains) {
cb(call, callback)
}
}
}
// add service
this.server.addService(service, executions)
}
}
/**
* Bind the host and port.
*
* @param {Number} port - The port number.
* @param {string} host - The host.
*/
bind(port, host = "0.0.0.0") {
// sign the services
this._signServices()
// bind the server
this.server.bind(`${host}:${port}`, grpc.ServerCredentials.createInsecure())
this.server.start()
// resolve the bind
return Promise.resolve({ port, host })
}
} |
JavaScript | class Painter extends Class {
/**
* @param {Geometry} geometry - geometry to paint
*/
constructor(geometry) {
super();
this.geometry = geometry;
this.symbolizers = this._createSymbolizers();
this._altAtGLZoom = this._getGeometryAltitude();
}
getMap() {
return this.geometry.getMap();
}
getLayer() {
return this.geometry.getLayer();
}
/**
* create symbolizers
*/
_createSymbolizers() {
const geoSymbol = this.getSymbol(),
symbolizers = [],
regSymbolizers = registerSymbolizers;
let symbols = geoSymbol;
if (!Array.isArray(geoSymbol)) {
symbols = [geoSymbol];
}
for (let ii = symbols.length - 1; ii >= 0; ii--) {
const symbol = symbols[ii];
for (let i = regSymbolizers.length - 1; i >= 0; i--) {
if (regSymbolizers[i].test(symbol, this.geometry)) {
const symbolizer = new regSymbolizers[i](symbol, this.geometry, this);
symbolizers.push(symbolizer);
if (symbolizer instanceof Symbolizers.PointSymbolizer) {
this._hasPoint = true;
}
}
}
}
if (!symbolizers.length) {
if (console) {
const id = this.geometry.getId();
console.warn('invalid symbol for geometry(' + (this.geometry ? this.geometry.getType() + (id ? ':' + id : '') : '') + ') to draw : ' + JSON.stringify(geoSymbol));
}
// throw new Error('no symbolizers can be created to draw, check the validity of the symbol.');
}
this._debugSymbolizer = new Symbolizers.DebugSymbolizer(geoSymbol, this.geometry, this);
return symbolizers;
}
hasPoint() {
return !!this._hasPoint;
}
/**
* for point symbolizers
* @return {Point[]} points to render
*/
getRenderPoints(placement) {
if (!this._renderPoints) {
this._renderPoints = {};
}
if (!placement) {
placement = 'center';
}
if (!this._renderPoints[placement]) {
this._renderPoints[placement] = this.geometry._getRenderPoints(placement);
}
return this._renderPoints[placement];
}
/**
* for strokeAndFillSymbolizer
* @return {Object[]} resources to render vector
*/
getPaintParams(dx, dy, ignoreAltitude) {
const map = this.getMap(),
geometry = this.geometry,
res = map.getResolution(),
pitched = (map.getPitch() !== 0),
rotated = (map.getBearing() !== 0);
let params = this._cachedParams;
const paintAsPath = geometry._paintAsPath && geometry._paintAsPath();
if (paintAsPath && this._unsimpledParams && res <= this._unsimpledParams._res) {
//if res is smaller, return unsimplified params directly
params = this._unsimpledParams;
} else if (!params ||
// refresh paint params
// simplified, but not same zoom
params._res !== map.getResolution() ||
// refresh if requested by geometry
this._pitched !== pitched && geometry._redrawWhenPitch() ||
this._rotated !== rotated && geometry._redrawWhenRotate()
) {
//render resources geometry returned are based on 2d points.
params = geometry._getPaintParams();
if (!params) {
return null;
}
params._res = res;
if (!geometry._simplified && paintAsPath) {
if (!this._unsimpledParams) {
this._unsimpledParams = params;
}
if (res > this._unsimpledParams._res) {
this._unsimpledParams._res = res;
}
}
this._cachedParams = params;
}
if (!params) {
return null;
}
this._pitched = pitched;
this._rotated = rotated;
const zoomScale = map.getGLScale(),
// paintParams = this._paintParams,
tr = [], // transformed params
points = params[0];
const mapExtent = map.getContainerExtent();
const cPoints = this._pointContainerPoints(points, dx, dy, ignoreAltitude, this._hitPoint && !mapExtent.contains(this._hitPoint));
if (!cPoints) {
return null;
}
tr.push(cPoints);
for (let i = 1, l = params.length; i < l; i++) {
if (isNumber(params[i]) || (params[i] instanceof Size)) {
if (isNumber(params[i])) {
tr.push(params[i] / zoomScale);
} else {
tr.push(params[i].multi(1 / zoomScale));
}
} else {
tr.push(params[i]);
}
}
return tr;
}
_pointContainerPoints(points, dx, dy, ignoreAltitude, disableClip, pointPlacement) {
const cExtent = this.getContainerExtent();
if (!cExtent) {
return null;
}
const map = this.getMap(),
glZoom = map.getGLZoom(),
containerOffset = this.containerOffset;
let cPoints;
function pointContainerPoint(point, alt) {
const p = map._pointToContainerPoint(point, glZoom, alt)._sub(containerOffset);
if (dx || dy) {
p._add(dx || 0, dy || 0);
}
return p;
}
let altitude = this.getAltitude();
//convert 2d points to container points needed by canvas
if (Array.isArray(points)) {
const geometry = this.geometry;
let clipped;
if (!disableClip && geometry.options['enableClip']) {
clipped = this._clip(points, altitude);
} else {
clipped = {
points : points,
altitude : altitude
};
}
const clipPoints = clipped.points;
altitude = clipped.altitude;
if (ignoreAltitude) {
altitude = 0;
}
let alt = altitude;
cPoints = [];
for (let i = 0, l = clipPoints.length; i < l; i++) {
const c = clipPoints[i];
if (Array.isArray(c)) {
const cring = [];
//polygon rings or clipped line string
for (let ii = 0, ll = c.length; ii < ll; ii++) {
const cc = c[ii];
if (Array.isArray(altitude)) {
if (altitude[i]) {
alt = altitude[i][ii];
} else {
alt = 0;
}
}
cring.push(pointContainerPoint(cc, alt));
}
cPoints.push(cring);
} else {
//line string
if (Array.isArray(altitude)) {
// altitude of different placement for point symbolizers
if (pointPlacement === 'vertex-last') {
alt = altitude[altitude.length - 1 - i];
} else if (pointPlacement === 'line') {
alt = (altitude[i] + altitude[i + 1]) / 2;
} else {
//vertex, vertex-first
alt = altitude[i];
}
}
cPoints.push(pointContainerPoint(c, alt));
}
}
} else if (points instanceof Point) {
if (ignoreAltitude) {
altitude = 0;
}
cPoints = map._pointToContainerPoint(points, glZoom, altitude)._sub(containerOffset);
if (dx || dy) {
cPoints._add(dx, dy);
}
}
return cPoints;
}
_clip(points, altitude) {
const map = this.getMap(),
geometry = this.geometry,
glZoom = map.getGLZoom();
let lineWidth = this.getSymbol()['lineWidth'];
if (!isNumber(lineWidth)) {
lineWidth = 4;
}
const containerExtent = map.getContainerExtent();
let extent2D = containerExtent.expand(lineWidth).convertTo(p => map._containerPointToPoint(p, glZoom));
if (map.getPitch() > 0 && altitude) {
const c = map.cameraLookAt;
const pos = map.cameraPosition;
//add [1px, 1px] towards camera's lookAt
extent2D = extent2D.combine(new Point(pos)._add(sign(c[0] - pos[0]), sign(c[1] - pos[1])));
}
const e = this.get2DExtent();
let clipPoints = points;
if (e.within(extent2D)) {
// if (this.geometry.getJSONType() === 'LineString') {
// // clip line with altitude
// return this._clipLineByAlt(clipPoints, altitude);
// }
return {
points : clipPoints,
altitude : altitude
};
}
const smoothness = geometry.options['smoothness'];
// if (this.geometry instanceof Polygon) {
if (geometry.getShell && this.geometry.getHoles && !smoothness) {
// clip the polygon to draw less and improve performance
if (!Array.isArray(points[0])) {
clipPoints = clipPolygon(points, extent2D);
} else {
clipPoints = [];
for (let i = 0; i < points.length; i++) {
const part = clipPolygon(points[i], extent2D);
if (part.length) {
clipPoints.push(part);
}
}
}
} else if (geometry.getJSONType() === 'LineString') {
// clip the line string to draw less and improve performance
if (!Array.isArray(points[0])) {
clipPoints = clipLine(points, extent2D, false, !!smoothness);
} else {
clipPoints = [];
for (let i = 0; i < points.length; i++) {
pushIn(clipPoints, clipLine(points[i], extent2D, false, !!smoothness));
}
}
//interpolate line's segment's altitude if altitude is an array
return this._interpolateSegAlt(clipPoints, points, altitude);
// const segs = this._interpolateSegAlt(clipPoints, points, altitude);
// return this._clipLineByAlt(segs.points, segs.altitude);
}
return {
points : clipPoints,
altitude : altitude
};
}
// _clipLineByAlt(clipSegs, altitude) {
// const frustumAlt = this.getMap().getFrustumAltitude();
// if (!Array.isArray(altitude) || this.maxAltitude <= frustumAlt) {
// return {
// points : clipSegs,
// altitude : altitude
// };
// }
// return clipByALt(clipSegs, altitude, frustumAlt);
// }
/**
* interpolate clipped line segs's altitude
* @param {Point[]|Point[][]} clipSegs
* @param {Point[]|Point[][]} orig
* @param {Number|Number[]} altitude
* @private
*/
_interpolateSegAlt(clipSegs, orig, altitude) {
if (!Array.isArray(altitude)) {
const fn = cc => cc.point;
return {
points : clipSegs.map(c => {
if (Array.isArray(c)) {
return c.map(fn);
}
return c.point;
}),
altitude : altitude
};
}
const segsWithAlt = interpolateAlt(clipSegs, orig, altitude);
altitude = [];
const points = segsWithAlt.map(p => {
if (Array.isArray(p)) {
const alt = [];
const cp = p.map(pp => {
alt.push(pp.altitude);
return pp.point;
});
altitude.push(alt);
return cp;
}
altitude.push(p.altitude);
return p.point;
});
return {
points : points,
altitude : altitude
};
}
getSymbol() {
return this.geometry._getInternalSymbol();
}
paint(extent, context, offset) {
if (!this.symbolizers) {
return;
}
const renderer = this.getLayer()._getRenderer();
if (!renderer || !renderer.context && !context) {
return;
}
//reduce geos to paint when drawOnInteracting
if (extent && !extent.intersects(this.get2DExtent(renderer.resources))) {
return;
}
const map = this.getMap();
const minAltitude = this.getMinAltitude();
const frustumAlt = map.getFrustumAltitude();
if (minAltitude && frustumAlt && frustumAlt < minAltitude) {
return;
}
this.containerOffset = offset || map._pointToContainerPoint(renderer.southWest)._add(0, -map.height);
this._beforePaint();
const ctx = context || renderer.context;
const contexts = [ctx, renderer.resources];
for (let i = this.symbolizers.length - 1; i >= 0; i--) {
this._prepareShadow(ctx, this.symbolizers[i].symbol);
this.symbolizers[i].symbolize.apply(this.symbolizers[i], contexts);
}
this._afterPaint();
this._painted = true;
this._debugSymbolizer.symbolize.apply(this._debugSymbolizer, contexts);
}
getSprite(resources, canvasClass) {
if (this.geometry.type !== 'Point') {
return null;
}
this._spriting = true;
if (!this._sprite && this.symbolizers.length > 0) {
const extent = new PointExtent();
this.symbolizers.forEach(s => {
const markerExtent = s.getFixedExtent(resources);
extent._combine(markerExtent);
});
const origin = extent.getMin().multi(-1);
const clazz = canvasClass || (this.getMap() ? this.getMap().CanvasClass : null);
const canvas = Canvas.createCanvas(extent.getWidth(), extent.getHeight(), clazz);
let bak;
if (this._renderPoints) {
bak = this._renderPoints;
}
const ctx = canvas.getContext('2d');
const contexts = [ctx, resources];
for (let i = this.symbolizers.length - 1; i >= 0; i--) {
const dxdy = this.symbolizers[i].getDxDy();
this._renderPoints = {
'center': [
[origin.add(dxdy)]
]
};
this._prepareShadow(ctx, this.symbolizers[i].symbol);
this.symbolizers[i].symbolize.apply(this.symbolizers[i], contexts);
}
if (bak) {
this._renderPoints = bak;
}
this._sprite = {
'canvas': canvas,
'offset': extent.getCenter()
};
}
this._spriting = false;
return this._sprite;
}
isSpriting() {
return !!this._spriting;
}
hitTest(cp, tolerance) {
if (!tolerance || tolerance < 0.5) {
tolerance = 0.5;
}
if (!testCanvas) {
testCanvas = Canvas.createCanvas(1, 1);
}
Canvas.setHitTesting(true);
testCanvas.width = testCanvas.height = 2 * tolerance;
const ctx = testCanvas.getContext('2d');
this._hitPoint = cp.sub(tolerance, tolerance);
try {
this.paint(null, ctx, this._hitPoint);
} catch (e) {
throw e;
} finally {
Canvas.setHitTesting(false);
}
delete this._hitPoint;
const imgData = ctx.getImageData(0, 0, testCanvas.width, testCanvas.height).data;
for (let i = 3, l = imgData.length; i < l; i += 4) {
if (imgData[i] > 0) {
return true;
}
}
return false;
}
isHitTesting() {
return !!this._hitPoint;
}
_prepareShadow(ctx, symbol) {
if (symbol['shadowBlur']) {
ctx.shadowBlur = symbol['shadowBlur'];
ctx.shadowColor = symbol['shadowColor'] || '#000';
ctx.shadowOffsetX = symbol['shadowOffsetX'] || 0;
ctx.shadowOffsetY = symbol['shadowOffsetY'] || 0;
} else if (ctx.shadowBlur) {
ctx.shadowBlur = null;
ctx.shadowColor = null;
ctx.shadowOffsetX = null;
ctx.shadowOffsetY = null;
}
}
_eachSymbolizer(fn, context) {
if (!this.symbolizers) {
return;
}
if (!context) {
context = this;
}
for (let i = this.symbolizers.length - 1; i >= 0; i--) {
fn.apply(context, [this.symbolizers[i]]);
}
}
get2DExtent(resources) {
this._verifyProjection();
const map = this.getMap();
resources = resources || this.getLayer()._getRenderer().resources;
const zoom = map.getZoom();
if (!this._extent2D || this._extent2D._zoom !== zoom) {
delete this._extent2D;
delete this._fixedExtent;
if (this.symbolizers) {
const extent = this._extent2D = new PointExtent();
const fixedExt = this._fixedExtent = new PointExtent();
for (let i = this.symbolizers.length - 1; i >= 0; i--) {
const symbolizer = this.symbolizers[i];
extent._combine(symbolizer.get2DExtent());
if (symbolizer.getFixedExtent) {
fixedExt._combine(symbolizer.getFixedExtent(resources));
}
}
extent._zoom = zoom;
}
}
return this._extent2D.add(this._fixedExtent);
}
getContainerExtent() {
this._verifyProjection();
const map = this.getMap();
const zoom = map.getZoom();
const glScale = map.getGLScale();
if (!this._extent2D || this._extent2D._zoom !== zoom) {
this.get2DExtent();
}
const altitude = this.getMinAltitude();
const frustumAlt = map.getFrustumAltitude();
if (altitude && frustumAlt && frustumAlt < altitude) {
return null;
}
const extent = this._extent2D.convertTo(c => map._pointToContainerPoint(c, zoom, altitude / glScale));
const maxAltitude = this.getMaxAltitude();
if (maxAltitude !== altitude) {
const extent2 = this._extent2D.convertTo(c => map._pointToContainerPoint(c, zoom, maxAltitude / glScale));
extent._combine(extent2);
}
const layer = this.geometry.getLayer();
if (this.geometry.type === 'LineString' && maxAltitude && layer.options['drawAltitude']) {
const groundExtent = this._extent2D.convertTo(c => map._pointToContainerPoint(c, zoom, 0));
extent._combine(groundExtent);
}
if (extent) {
extent._add(this._fixedExtent);
}
const smoothness = this.geometry.options['smoothness'];
if (smoothness) {
extent._expand(extent.getWidth() * 0.15);
}
return extent;
}
getFixedExtent() {
const map = this.getMap();
const zoom = map.getZoom();
if (!this._extent2D || this._extent2D._zoom !== zoom) {
this.get2DExtent();
}
return this._fixedExtent;
}
setZIndex(change) {
this._eachSymbolizer(function (symbolizer) {
symbolizer.setZIndex(change);
});
}
show() {
if (!this._painted) {
const layer = this.getLayer();
if (!layer.isCanvasRender()) {
this.paint();
}
} else {
this.removeCache();
this._eachSymbolizer(function (symbolizer) {
symbolizer.show();
});
}
}
hide() {
this._eachSymbolizer(function (symbolizer) {
symbolizer.hide();
});
}
repaint() {
this._altAtGLZoom = this._getGeometryAltitude();
this.removeCache();
const layer = this.getLayer();
if (!layer) {
return;
}
const renderer = layer.getRenderer();
if (!renderer || !renderer.setToRedraw()) {
return;
}
renderer.setToRedraw();
}
/**
* refresh symbolizers when symbol changed
*/
refreshSymbol() {
this.removeCache();
this._removeSymbolizers();
this.symbolizers = this._createSymbolizers();
}
remove() {
this.removeCache();
this._removeSymbolizers();
}
_removeSymbolizers() {
this._eachSymbolizer(function (symbolizer) {
delete symbolizer.painter;
symbolizer.remove();
});
delete this.symbolizers;
}
/**
* delete painter's caches
*/
removeCache() {
delete this._renderPoints;
delete this._paintParams;
delete this._sprite;
delete this._extent2D;
delete this._fixedExtent;
delete this._cachedParams;
delete this._unsimpledParams;
if (this.geometry) {
delete this.geometry[Symbolizers.TextMarkerSymbolizer.CACHE_KEY];
}
}
getAltitude() {
const propAlt = this._getAltitudeProperty();
if (propAlt !== this._propAlt) {
this._altAtGLZoom = this._getGeometryAltitude();
}
if (!this._altAtGLZoom) {
return 0;
}
return this._altAtGLZoom;
}
getMinAltitude() {
if (!this.minAltitude) {
return 0;
}
return this.minAltitude;
}
getMaxAltitude() {
if (!this.maxAltitude) {
return 0;
}
return this.maxAltitude;
}
_getGeometryAltitude() {
const map = this.getMap();
if (!map) {
return 0;
}
const altitude = this._getAltitudeProperty();
this._propAlt = altitude;
if (!altitude) {
this.minAltitude = this.maxAltitude = 0;
return 0;
}
const center = this.geometry.getCenter();
if (!center) {
return 0;
}
if (Array.isArray(altitude)) {
this.minAltitude = Number.MAX_VALUE;
this.maxAltitude = Number.MIN_VALUE;
return altitude.map(alt => {
const a = this._meterToPoint(center, alt);
if (a < this.minAltitude) {
this.minAltitude = a;
}
if (a > this.maxAltitude) {
this.maxAltitude = a;
}
return a;
});
} else {
this.minAltitude = this.maxAltitude = this._meterToPoint(center, altitude);
return this.minAltitude;
}
}
_meterToPoint(center, altitude) {
const map = this.getMap();
const z = map.getGLZoom();
const target = map.locate(center, altitude, 0);
const p0 = map.coordToPoint(center, z),
p1 = map.coordToPoint(target, z);
return Math.abs(p1.x - p0.x) * sign(altitude);
}
_getAltitudeProperty() {
const geometry = this.geometry,
layerOpts = geometry.getLayer().options,
properties = geometry.getProperties();
const altitude = layerOpts['enableAltitude'] ? properties ? properties[layerOpts['altitudeProperty']] : 0 : 0;
return altitude;
}
_verifyProjection() {
const projection = this.geometry._getProjection();
if (this._projCode && this._projCode !== projection.code) {
this.removeCache();
}
this._projCode = projection.code;
}
_beforePaint() {
const textcache = this.geometry[Symbolizers.TextMarkerSymbolizer.CACHE_KEY];
if (!textcache) {
return;
}
for (const p in textcache) {
if (hasOwn(textcache, p)) {
textcache[p].active = false;
}
}
}
_afterPaint() {
const textcache = this.geometry[Symbolizers.TextMarkerSymbolizer.CACHE_KEY];
if (!textcache) {
return;
}
for (const p in textcache) {
if (hasOwn(textcache, p)) {
if (!textcache[p].active) {
delete textcache[p];
}
}
}
}
} |
JavaScript | class TagLengthValue extends Transform {
constructor(options) {
super(options);
this.position = 0;
this.header = Buffer.alloc(2);
this.value = undefined;
this.parsingHeader = true;
this.length = 0;
this.message = {
value: Buffer.alloc(0),
length: 0,
};
}
_transform(chunk, encoding, cb) {
let cursor = 0;
while (this.parsingHeader && cursor < chunk.length) {
this.header[this.position] = chunk[cursor];
cursor++;
this.position++;
if (this.position === 2) {
this.parsingHeader = false;
this.length = this.header[1];
this.value = Buffer.alloc(this.length);
this.position = 0;
}
}
while (!this.parsingHeader && cursor < chunk.length) {
this.value[this.position] = chunk[cursor];
cursor++;
this.position++;
if (this.position === this.length) {
const length = this.header[1] + 2;
this.message = {
value: Buffer.concat([this.header, this.value], length),
length,
};
this.push(this.message.value);
this.parsingHeader = true;
this.length = 0;
this.header = Buffer.alloc(2);
this.value = undefined;
}
}
cb();
}
_flush(cb) {
this.push(this.message.value.slice(0, this.position));
this.message.value = Buffer.alloc(0);
cb();
}
} |
JavaScript | class SimpleRequest extends EventEmitter {
// Options are the same options you'd pass to request()
constructor(options = {}) {
// Build the EventEmitter.
super()
// Add some default values.
this[s.value] = null
this[s.complete] = false
// Break out the desired request function.
const request = options.port === 443 ? https_request : http_request
// Handle the request.
const result = request(options, res => {
// Colect data as it streams in.
const data = []
res.on('data', d => data.push(d))
// Emit the final data result when compelte.
res.on('end', () => {
// Grab the final result and bind it to the objects value.
const info = data.toString()
this[s.value] = info
// Emit the result.
this.emit('end', info)
})
})
// Forward the request error onto this object for handling.
result.on('error', error => this.emit('error', error))
// Mark the object as complete when the result ends.
result.on('end', () => this[s.complete] = true)
// Finish the request.
result.end()
}
// Use the above as a promise.
static promise(options = {}) {
return new Promise((accept, reject) => {
const request = new SimpleRequest(options)
request.on('end', data => accept(data))
request.on('error', error => reject(error))
})
}
// Getters.
get value() { return this[s.value] }
get complete() { return this[s.complete] }
} |
JavaScript | class Trie {
constructor() {
this.val = '';
this.branches = 0;
this.children = {};
}
addWord(string) {
// Iterate through the letters and check if they exist in the trie
// Add new letters to the existing prefix as new nodes
var currentNode = this;
for (var i = 0; i < string.length; i++) {
var letter = string[i];
if (!currentNode.children[letter]) {
var node = new Node(letter);
currentNode.children[letter] = node;
currentNode.branches++;
currentNode = node;
} else {
currentNode = currentNode.children[letter];
}
}
return true;
}
removeWord(string) {
// Go through the trie until you hit a non-branching node
// Non-branching would mean there is only one child letter
// Delete that to remove the word
// Ensure that you do not delete prefixes that extend to other words
// If the input string is a substring of an existing word, don't delete it
if (!this.isMember(string)) { return false; }
var mostRecentBranch = [this, string[0]];
var currentNode = this;
for (var i = 0; i < string.length; i++) {
var letter = string[i];
if (currentNode.branches > 1) {
mostRecentBranch = [currentNode, letter];
}
currentNode = currentNode.children[letter];
}
if (currentNode.branches) {
// if the input string does not end on a leaf in the tree (it's not a complete word)
// use removePrefix instead to remove all words with a given prefix
return false;
}
delete mostRecentBranch[0].children[mostRecentBranch[1]];
mostRecentBranch[0].branches--;
return string;
}
isMember(string) {
// Verify if the word exists in the trie
// Iterate through the letters and trace it in the trie
if (typeof string !== 'string') { return false; }
var currentNode = this;
for (var i = 0; i < string.length; i++) {
var letter = string[i];
if (!currentNode.children[letter]) {
return false;
} else {
currentNode = currentNode.children[letter];
}
}
return true;
}
predict(prefix = '') {
// Iterate to the last letter/node
// Record all complete branches of the node (down to the leaves)
if (!this.isMember(prefix)) { return false; }
var predictions = [];
var currentNode = this;
for (var i = 0; i < prefix.length; i++) {
currentNode = currentNode.children[prefix[i]];
}
this._gatherWords(currentNode, prefix.slice(0, prefix.length - 1), predictions, this);
return predictions;
}
removePrefix(prefix) { // TODO
// Remove all words with a given prefix, including the prefix itself
if (!this.isMember(prefix) || !prefix.length) { return false; }
var deletedWords = this.predict(prefix);
var currentNode = this;
for (var i = 0; i < prefix.length; i++) {
var letter = prefix[i];
if (i === prefix.length - 1) {
delete currentNode.children[letter];
currentNode.branches--;
} else {
currentNode = currentNode.children[letter];
}
}
return deletedWords;
}
_gatherWords(node, string, res = [], context = this) {
var word = string + node.val;
if (!node.branches) {
res.push(word);
} else {
for (var prop in node.children) {
context._gatherWords(node.children[prop], word, res, context);
}
}
}
} |
JavaScript | class NgbModalConfig {
constructor() {
this.backdrop = true;
this.keyboard = true;
}
} |
JavaScript | class GalleryPreviewLayout extends React.Component {
constructor(props) {
super(props)
this.state = {
isOpen: false
}
}
handleOpen = () => {
this.setState({
isOpen: !this.state.isOpen
})
}
render() {
const { item, gridLayout } = this.props
console.log(
'🚀 ~ file: gallery-preview.js ~ line 29 ~ GalleryPreviewLayout ~ render ~ item',
item
)
return (
<div className={cn(styles.itemWrapper, gridLayout && styles.gridLayout)}>
<div className={styles.inner}>
<div className={styles.image}>
{!item.mainVideo && item.mainImage && item.mainImage.asset && (
<Image isZoomable fluid={item.mainImage.asset.fluid} />
)}
{/* {item.mainVideo && (
<div className={styles.Video}>
<Video controls={false} src={item.mainVideo.asset.url} />
</div>
)} */}
</div>
</div>
<div className={styles.titleWrapper}>
<h3 className={cn(responsiveTitle5, styles.title)}>{item.title}</h3>
{item._rawBody && item._rawBody.length > 0 && (
<button to="#" className={styles.readMore} onClick={this.handleOpen}>
{' '}
{this.state.isOpen ? 'Close' : 'Read More'}
</button>
)}
</div>
<div className={styles.descriptionWrapper}>
{item._rawExcerpt && <BlockText blocks={item._rawExcerpt || []} />}
{item._rawBody && (
<div className={this.state.isOpen ? styles.open : styles.closed}>
<BlockContent blocks={item._rawBody || []} />
</div>
)}
</div>
</div>
)
}
} |
JavaScript | class PopupService {
constructor(applicationRef, componentFactoryResolver, injector, container) {
this.applicationRef = applicationRef;
this.componentFactoryResolver = componentFactoryResolver;
this.injector = injector;
this.container = container;
}
/**
* Gets the root view container into which the component will be injected.
*
* @returns {ComponentRef<any>}
*/
get rootViewContainer() {
// https://github.com/angular/angular/blob/4.0.x/packages/core/src/application_ref.ts#L571
const rootComponents = this.applicationRef.components || [];
if (rootComponents[0]) {
return rootComponents[0];
}
throw new Error(`
View Container not found! Inject the POPUP_CONTAINER or define a specific ViewContainerRef via the appendTo option.
See http://www.telerik.com/kendo-angular-ui/components/popup/api/POPUP_CONTAINER/ for more details.
`);
}
/**
* Sets or gets the HTML element of the root component container.
*
* @returns {HTMLElement}
*/
get rootViewContainerNode() {
return this.container ? this.container.nativeElement : this.getComponentRootNode(this.rootViewContainer);
}
/**
* Opens a Popup component. Created Popups are mounted
* in the DOM directly in the root application component.
*
* @param {PopupSettings} options - The options which define the Popup.
* @returns {ComponentRef<PopupComponent>} - A reference to the Popup object.
*
* @example
*
* ```ts-no-run
* _@Component({
* selector: 'my-app',
* template: `
* <ng-template #template>
* Popup content
* </ng-template>
* <button #anchor kendoButton (click)="open(anchor, template)">Open</button>
* `
* })
* export class AppComponent {
* public popupRef: PopupRef;
*
* constructor( private popupService: PopupService ) {}
*
* public open(anchor: ElementRef, template: TemplateRef<any>): void {
* if (this.popupRef) {
* this.popupRef.close();
* this.popupRef = null;
* return;
* }
*
* this.popupRef = this.popupService.open({
* anchor: anchor,
* content: template
* });
* }
* }
* ```
*/
open(options = {}) {
const { component, nodes } = this.contentFrom(options.content);
const popupComponentRef = this.appendPopup(nodes, options.appendTo);
const popupInstance = popupComponentRef.instance;
this.projectComponentInputs(popupComponentRef, options);
popupComponentRef.changeDetectorRef.detectChanges();
if (component) {
component.changeDetectorRef.detectChanges();
}
const popupElement = this.getComponentRootNode(popupComponentRef);
return {
close: () => {
// XXX: Destroy is required due to this bug:
// https://github.com/angular/angular/issues/15578
//
if (component) {
component.destroy();
}
else if (!popupComponentRef.hostView.destroyed) {
popupComponentRef.instance.content = null;
popupComponentRef.changeDetectorRef.detectChanges();
}
popupComponentRef.destroy();
// Angular will not remove the element unless the change detection is triggered
removeElement(popupElement);
},
content: component,
popup: popupComponentRef,
popupAnchorViewportLeave: popupInstance.anchorViewportLeave,
popupClose: popupInstance.close,
popupElement: popupElement,
popupOpen: popupInstance.open,
popupPositionChange: popupInstance.positionChange
};
}
appendPopup(nodes, container) {
const popupComponentRef = this.createComponent(PopupComponent, nodes, container);
if (!container) {
this.rootViewContainerNode.appendChild(this.getComponentRootNode(popupComponentRef));
}
return popupComponentRef;
}
/**
* Gets the HTML element for a component reference.
*
* @param {ComponentRef<any>} componentRef
* @returns {HTMLElement}
*/
getComponentRootNode(componentRef) {
return componentRef.hostView.rootNodes[0];
}
/**
* Gets the `ComponentFactory` instance by its type.
*
* @param {*} componentClass
* @param {*} nodes
* @returns {ComponentRef<any>}
*/
getComponentFactory(componentClass) {
return this.componentFactoryResolver.resolveComponentFactory(componentClass);
}
/**
* Creates a component reference from a `Component` type class.
*
* @param {*} componentClass
* @param {*} nodes
* @returns {ComponentRef<any>}
*/
createComponent(componentClass, nodes, container) {
const factory = this.getComponentFactory(componentClass);
if (container) {
return container.createComponent(factory, undefined, this.injector, nodes);
}
else {
const component = factory.create(this.injector, nodes);
this.applicationRef.attachView(component.hostView);
return component;
}
}
/**
* Projects the inputs on the component.
*
* @param {ComponentRef<any>} component
* @param {*} options
* @returns {ComponentRef<any>}
*/
projectComponentInputs(component, options) {
Object.getOwnPropertyNames(options)
.filter(prop => prop !== 'content' || options.content instanceof TemplateRef)
.map((prop) => {
component.instance[prop] = options[prop];
});
return component;
}
/**
* Gets the component and the nodes to append from the `content` option.
*
* @param {*} content
* @returns {any}
*/
contentFrom(content) {
if (!content || content instanceof TemplateRef) {
return { component: null, nodes: [[]] };
}
const component = this.createComponent(content);
const nodes = component ? [component.location.nativeElement] : [];
return {
component: component,
nodes: [
nodes // <ng-content>
]
};
}
} |
JavaScript | class TableCellPropertiesEditing extends Plugin {
/**
* @inheritDoc
*/
static get pluginName() {
return 'TableCellPropertiesEditing';
}
/**
* @inheritDoc
*/
static get requires() {
return [ TableEditing ];
}
/**
* @inheritDoc
*/
init() {
const editor = this.editor;
const schema = editor.model.schema;
const conversion = editor.conversion;
editor.config.define( 'table.tableCellProperties.defaultProperties', {} );
const defaultTableCellProperties = getNormalizedDefaultProperties(
editor.config.get( 'table.tableCellProperties.defaultProperties' ),
{
includeVerticalAlignmentProperty: true,
includeHorizontalAlignmentProperty: true,
includePaddingProperty: true,
isRightToLeftContent: editor.locale.contentLanguageDirection === 'rtl'
}
);
editor.data.addStyleProcessorRules( addBorderRules );
enableBorderProperties( schema, conversion, {
color: defaultTableCellProperties.borderColor,
style: defaultTableCellProperties.borderStyle,
width: defaultTableCellProperties.borderWidth
} );
editor.commands.add( 'tableCellBorderStyle', new TableCellBorderStyleCommand( editor, defaultTableCellProperties.borderStyle ) );
editor.commands.add( 'tableCellBorderColor', new TableCellBorderColorCommand( editor, defaultTableCellProperties.borderColor ) );
editor.commands.add( 'tableCellBorderWidth', new TableCellBorderWidthCommand( editor, defaultTableCellProperties.borderWidth ) );
enableProperty( schema, conversion, {
modelAttribute: 'tableCellWidth',
styleName: 'width',
defaultValue: defaultTableCellProperties.width
} );
editor.commands.add( 'tableCellWidth', new TableCellWidthCommand( editor, defaultTableCellProperties.width ) );
enableProperty( schema, conversion, {
modelAttribute: 'tableCellHeight',
styleName: 'height',
defaultValue: defaultTableCellProperties.height
} );
editor.commands.add( 'tableCellHeight', new TableCellHeightCommand( editor, defaultTableCellProperties.height ) );
editor.data.addStyleProcessorRules( addPaddingRules );
enableProperty( schema, conversion, {
modelAttribute: 'tableCellPadding',
styleName: 'padding',
reduceBoxSides: true,
defaultValue: defaultTableCellProperties.padding
} );
editor.commands.add( 'tableCellPadding', new TableCellPaddingCommand( editor, defaultTableCellProperties.padding ) );
editor.data.addStyleProcessorRules( addBackgroundRules );
enableProperty( schema, conversion, {
modelAttribute: 'tableCellBackgroundColor',
styleName: 'background-color',
defaultValue: defaultTableCellProperties.backgroundColor
} );
editor.commands.add(
'tableCellBackgroundColor',
new TableCellBackgroundColorCommand( editor, defaultTableCellProperties.backgroundColor )
);
enableHorizontalAlignmentProperty( schema, conversion, defaultTableCellProperties.horizontalAlignment );
editor.commands.add(
'tableCellHorizontalAlignment',
new TableCellHorizontalAlignmentCommand( editor, defaultTableCellProperties.horizontalAlignment )
);
enableVerticalAlignmentProperty( schema, conversion, defaultTableCellProperties.verticalAlignment );
editor.commands.add(
'tableCellVerticalAlignment',
new TableCellVerticalAlignmentCommand( editor, defaultTableCellProperties.verticalAlignment )
);
}
} |
JavaScript | class SmartdomElement_ {
// delete childs
x() {
this.html("");
return this;
}
// add event listener
ae(kind, callback) {
this.e.addEventListener(kind, callback);
return this;
}
// set from state
setFromState(state) {
// abstract
return this;
}
// get stored state
getStoredState(def) {
if (this.storePath) {
return getLocal(this.storePath, null);
} else {
return def || null;
}
}
// get state
getState() {
return this.getStoredState();
}
// store state
storeState(state) {
if (this.storePath) {
storeLocal(this.storePath, state || this.getState());
}
return this;
}
// set store path
sp(path) {
this.storePath = path;
return this.setFromState(this.getStoredState());
}
// set attribute
sa(key, value) {
this.e.setAttribute(key, value);
return this;
}
// remove attribute
ra(key, value) {
this.e.removeAttribute(key, value);
return this;
}
// value
value(value) {
this.e.value = value;
return this;
}
// id
id(id) {
return this.sa("id", id).sa("name", id);
}
// flatten props
flattenProps(props) {
// a terminal is something that is not an array
if (!Array.isArray(props)) return props;
let accum = [];
for (let prop of props) {
if (Array.isArray(prop)) {
// flatten array
for (let item of prop) {
accum = accum.concat(this.flattenProps(item));
}
} else {
accum.push(prop);
}
}
return accum;
}
constructor(tag, ...props) {
// create dom element from tag, default = div
this.e = document.createElement(tag || "div");
// props
this.props = props || [];
// flatten props
this.props = this.flattenProps(this.props);
// string props
this.stringProps = [];
// other props
this.otherProps = [];
// sort out props
for (let prop of this.props) {
if (typeof prop == "string") {
this.stringProps.push(prop);
} else {
this.otherProps.push(prop);
}
}
// config
this.config = this.otherProps[0] || {};
// add all string props as classes
for (let sprop of this.stringProps) {
this.ac(sprop);
}
}
// add classes
ac(...classes) {
// add classes to element classList
for (let klass of this.flattenProps(classes)) {
this.e.classList.add(klass);
}
return this;
}
// remove classes
rc(...classes) {
// remove classes from element classList
for (let klass of this.flattenProps(classes)) {
this.e.classList.remove(klass);
}
return this;
}
// add style
as(key, value) {
this.e.style[key] = value;
return this;
}
// add style in px
aspx(key, value) {
return this.as(key, value + "px");
}
// set innerHTML
html(content) {
this.e.innerHTML = content;
return this;
}
// append childs
a(...childs) {
for (let child of this.flattenProps(childs)) {
this.e.appendChild(child.e);
}
return this;
}
// drag over behavior
dragover(delay) {
this.ae("dragover", (e) => {
e.stopPropagation();
e.preventDefault();
this.ac("dragover");
if (this.dragoverTimeout) {
clearTimeout(this.dragoverTimeout);
this.dragoverTimeout = null;
}
this.dragoverTimeout = setTimeout(
(_) => this.rc("dragover"),
delay || 1000
);
});
return this;
}
} |
JavaScript | class DropImage_ extends SmartdomElement_ {
constructor(...props) {
super("div", props);
this.ac("dropimage").dragover();
this.ae("mouseout", (_) => this.rc("dragover"));
this.ae("mouseover", (_) => this.ac("dragover"));
this.ae("drop", this.drop.bind(this));
this.width(150).height(150);
}
width(w) {
this.width = w;
this.aspx("width", w);
return this;
}
height(h) {
this.height = h;
this.aspx("height", h);
return this;
}
setFromState(state) {
if (state) {
this.as("background-image", `url(${state.url})`).as(
"background-size",
"100% 100%"
);
}
return this;
}
setDropCallback(callback) {
this.dropCallback = callback;
return this;
}
drop(e) {
e.stopPropagation();
e.preventDefault();
const files = e.dataTransfer.files;
if (files.length > 0) {
const file = files[0];
const reader = new FileReader();
reader.onload = (e) => {
const result = e.target.result;
const b64 = btoa(result);
const parts = file.name.split(".");
const ext = parts[parts.length - 1];
parts.pop();
const name = parts.length ? parts.join(".") : "";
reader.onload = (e) => {
const url = e.target.result;
const state = {
b64: b64,
url: url,
fullName: file.name,
name: name,
ext: ext,
size: result.length,
};
this.storeState(state).setFromState(state);
if (this.dropCallback) {
this.dropCallback(state);
}
};
reader.readAsDataURL(file);
};
reader.readAsBinaryString(file);
}
}
} |
JavaScript | class tr_ extends SmartdomElement_ {
constructor(...props) {
super("tr", props);
}
} |
JavaScript | class td_ extends SmartdomElement_ {
constructor(...props) {
super("td", props);
}
} |
JavaScript | class TextInput_ extends SmartdomElement_ {
constructor(...props) {
super("input", props);
this.sa("type", "text");
this.ac("textinput");
this.ae("input", this.input.bind(this));
}
getState() {
const value = this.e.value;
return {
value: value,
};
}
input() {
this.storeState();
}
setFromState(state) {
if (state) {
this.e.value = state.value;
}
return this;
}
} |
JavaScript | class TextArea_ extends SmartdomElement_ {
constructor(...props) {
super("textarea", props);
this.ac("textarea");
this.ae("input", this.input.bind(this));
}
getState() {
const value = this.e.value;
return {
value: value,
};
}
input() {
this.storeState();
}
setFromState(state) {
if (state) {
this.e.value = state.value;
}
return this;
}
} |
JavaScript | class LogItem_ extends SmartdomElement_ {
constructor(...props) {
super("div", props);
// determine record properties, supply reasonable default
this.record = this.config.record || {};
if (typeof this.record == "string") {
try {
this.record = JSON.parse(this.record);
} catch (err) {
this.record = {
msg: this.record,
};
}
}
// set record defaults
this.record.time = this.record.time || new Date().getTime();
this.record.msg = this.record.msg || this.record.toString();
this.level = this.record.level || "Raw";
this.timeDiv = div("time").html(
this.record.timeFormatted ||
this.record.naiveTime ||
new Date(this.record.time).toLocaleString()
);
this.moduleDiv = div("module").html(this.record.modulePath || "");
this.levelDiv = div("level").html(this.level);
this.msgDiv = div("msg").html(this.record.msg);
this.fileDiv = div("file").html(this.record.file || "");
this.msgContainerDiv = div("messagecont").a(this.msgDiv, this.fileDiv);
this.ac("logitem", this.level.toLowerCase());
this.timeAndModuleDiv = div("timeandmodule").a(
this.timeDiv,
this.moduleDiv
);
this.container = div()
.as("display", "flex")
.as("align-items", "center")
.a(this.timeAndModuleDiv, this.levelDiv, this.msgContainerDiv);
this.as("display", "inline-block").a(this.container);
}
} |
JavaScript | class TypeScriptLanguageServiceHost {
constructor(libs, files, compilerOptions) {
this._libs = libs;
this._files = files;
this._compilerOptions = compilerOptions;
}
// --- language service host ---------------
getCompilationSettings() {
return this._compilerOptions;
}
getScriptFileNames() {
return ([]
.concat(Object.keys(this._libs))
.concat(Object.keys(this._files)));
}
getScriptVersion(_fileName) {
return '1';
}
getProjectVersion() {
return '1';
}
getScriptSnapshot(fileName) {
if (this._files.hasOwnProperty(fileName)) {
return ts.ScriptSnapshot.fromString(this._files[fileName]);
}
else if (this._libs.hasOwnProperty(fileName)) {
return ts.ScriptSnapshot.fromString(this._libs[fileName]);
}
else {
return ts.ScriptSnapshot.fromString('');
}
}
getScriptKind(_fileName) {
return ts.ScriptKind.TS;
}
getCurrentDirectory() {
return '';
}
getDefaultLibFileName(_options) {
return 'defaultLib:lib.d.ts';
}
isDefaultLibFileName(fileName) {
return fileName === this.getDefaultLibFileName(this._compilerOptions);
}
} |
JavaScript | class Idle extends React.Component {
static propTypes = {
/** @ignore */
setPassword: PropTypes.func.isRequired,
/** @ignore */
timeout: PropTypes.number.isRequired,
/** @ignore */
isAuthorised: PropTypes.bool.isRequired,
};
state = {
locked: false,
};
componentDidMount() {
this.restartLockTimeout = debounce(this.handleEvent, 500);
this.attachEvents();
this.onSetIdle = this.lock.bind(this);
Electron.onEvent('lockScreen', this.onSetIdle);
}
componentWillReceiveProps(nextProps) {
if (!this.props.isAuthorised && nextProps.isAuthorised) {
this.handleEvent();
}
}
componentWillUnmount() {
this.removeEvents();
Electron.removeEvent('lockScreen', this.onSetIdle);
}
handleEvent = () => {
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
if (this.props.isAuthorised) {
this.lock();
} else {
this.handleEvent();
}
}, this.props.timeout * 60 * 1000);
};
lock() {
if (this.props.isAuthorised) {
this.props.setPassword({});
this.setState({ locked: true });
Electron.updateMenu('enabled', false);
}
}
unlock(password) {
this.props.setPassword(password);
this.setState({
locked: false,
});
Electron.updateMenu('enabled', true);
}
attachEvents() {
events.forEach((event) => {
window.addEventListener(event, this.restartLockTimeout, true);
});
}
removeEvents() {
events.forEach((event) => {
window.removeEventListener(event, this.restartLockTimeout, true);
});
}
render() {
if (!this.state.locked) {
return null;
}
return <ModalPassword isOpen isForced content={{}} onSuccess={(password) => this.unlock(password)} />;
}
} |
JavaScript | class PlaceImagesStacked extends React.Component {
constructor(props) {
super(props);
this.defaultImageHeight = 300;
this.state = {
galleryImages: this.getImages(),
imageNewHeight: this.defaultImageHeight,
isBoxVisible: true
};
this.handleImageStackClick = this.handleImageStackClick.bind(this);
this.handleMovedOutComplete = this.handleMovedOutComplete.bind(this);
this.handleSwipedLeft = this.handleSwipedLeft.bind(this);
this.handleSwipedRight = this.handleSwipedRight.bind(this);
}
componentDidMount() {
// this.setState({
// imageNewHeight: this.calculateImageHeight()
// });
// window.addEventListener("resize", this.handleResize);
}
componentWillUnmount() {
// window.removeEventListener("resize", this.handleResize);
}
// handleResize(e) {
// let imageNewHeight = this.calculateImageHeight();
// this.setState({
// imageNewHeight
// });
// }
handleSwipedLeft(e) {
this.handleImageStackClick(e, {
direction: "left"
});
}
handleSwipedRight(e) {
this.handleImageStackClick(e, {
direction: "right"
});
}
handleMovedOutComplete(image, pose) {
// Image is moved out of stack.
// Add it to the bottom = set to lowest z index and make visible again.
let { galleryImages } = this.state;
let galleryImagesNew = [...galleryImages];
let movedImageIndex = galleryImages.findIndex(
img => img.public_id === image.public_id
);
// Find image at bottom = image with lowest zIndex.
let bottomImage = galleryImages.reduce((prev, current) =>
prev.styles.zIndex < current.styles.zIndex ? prev : current
);
// Move moved image to bottom of stack and make visible again.
galleryImagesNew[movedImageIndex].styles.zIndex =
bottomImage.styles.zIndex - 1;
galleryImagesNew[movedImageIndex].isMovingOut = false;
this.setState({ galleryImages: galleryImagesNew });
}
/**
* When a user clicks the image stack,
* we move away the topmost image (image with highest zIndex)
* to show the image that previosly had the next-highest index
* and now has the highest.
*/
handleImageStackClick(e, args = {}) {
// Move out topmost image.
let { galleryImages } = this.state;
let { direction = "right" } = args;
// Bail if only one image.
if (galleryImages.length <= 1) {
return;
}
// Topmost image = image with highest zIndex.
let topmostImage = galleryImages.reduce((prev, current) =>
prev.styles.zIndex > current.styles.zIndex ? prev : current
);
//let topmostImage = galleryImages.filter
// console.log('topmostImage', topmostImage);
topmostImage.isMovingOut = true;
topmostImage.movingOutDirection = direction;
this.setState({
galleryImages
});
}
calculateImageHeight() {
let { galleryImages } = this.state;
if (!galleryImages.length) {
return this.defaultImageHeight;
}
// Base image size on first image, so we see part of first image and second image.
const firstImage = galleryImages[0];
const clientWidth = window.innerWidth;
const clientHeight = window.innerHeight;
// New image width = on smaller screen make it almost full width,
// but keep a bit space so we will see a bit of the next image.
// On larger screens don't let it grow to big, like half of the screen height.
let newImageWidth = clientWidth - 80;
if (newImageWidth > clientHeight / 2.75) {
newImageWidth = clientHeight / 2.75;
}
const imageNewWidth = newImageWidth;
const imageNewHeight =
(firstImage.height / firstImage.width) * imageNewWidth;
return imageNewHeight;
}
getImages() {
let { images, image } = this.props;
let galleryImages = [];
// Add main image as first image.
image && galleryImages.push(image);
// Add the other images.
images && galleryImages.push(...images);
// Keep only images with thumbs (some old api responses can return without thumb)
galleryImages = galleryImages.filter(image => image.thumb);
// Make thumb our wanted size.
let ImageGalleryImages = galleryImages.map(image => {
// Image is like https://res.cloudinary.com/vegogo/image/upload/w_640/lrzhnjazq7h9t2k7gzn8".
// Replace so becomes like https://res.cloudinary.com/vegogo/image/upload/w_640,h_300,c_fit/ufwvkpfrt0ep9i9wfq9g
image.thumb = image.thumb.replace("/w_640/", "/w_1280,h_600,c_fit/");
return image;
});
// If no images found lets fake some, beacuse we really want to test with some images.
// if (!ImageGalleryImages.length) {
// ImageGalleryImages = [...ImageGalleryImages, ...this.getDummyImages()];
// console.warn('No place ImageGalleryImages found');
// }
// Add styles (z-indexes and transforms).
let zIndex = ImageGalleryImages.length;
ImageGalleryImages = ImageGalleryImages.map(image => {
// https://stackoverflow.com/questions/13455042/random-number-between-negative-and-positive-value
var randomRotateDeg = Math.floor(Math.random() * 6) + 1; // this will get a number between 1 and 99;
randomRotateDeg *= Math.floor(Math.random() * 2) === 1 ? 1 : -1; // this will add minus sign in 50% of cases
image.isMovingOut = false;
image.styles = {
zIndex: zIndex--,
randomRotateDeg,
transform: `translateX(-50%) translateY(-50%) scale(1) rotate(${randomRotateDeg}deg)`
};
return image;
});
return ImageGalleryImages;
}
getDummyImages() {
// List of images avilable:
// https://picsum.photos/images
const imageIds = [
835,
437,
// 429,
// 425,
946,
// 1047,
1059,
// 1080,
30,
42
// 48,
// 63,
// 75,
// 163,
// 292
];
let images = imageIds.map(imageId => {
return {
width: 450,
height: 600,
thumb: `https://picsum.photos/450/600/?image=${imageId}&xblur`,
public_id: `dummy_img_${imageId}`
};
});
images.push({
width: 600,
height: 450,
thumb: `https://picsum.photos/600/450/?image=429&xblur`,
public_id: `dummy_img_429`
});
images.push({
width: 450,
height: 600,
thumb: `https://picsum.photos/450/600/?image=1047&xblur`,
public_id: `dummy_img_1047`
});
return images;
}
render() {
let { images, image } = this.props;
let { imageNewHeight } = this.state;
if (!images && !image) {
return null;
}
let ImageGalleryImages = this.state.galleryImages;
return (
<React.Fragment>
<Swipeable
onSwipedLeft={this.handleSwipedLeft}
onSwipedRight={this.handleSwipedRight}
onClick={this.handleImageStackClick}
className="ImageStack"
>
<div className="ImageStack-wrap">
{ImageGalleryImages.map(image => {
return (
<StackImage
handleMovedOutComplete={this.handleMovedOutComplete.bind(
this,
image
)}
key={image.thumb}
image={image}
imageNewHeight={imageNewHeight}
/>
);
})}
</div>
</Swipeable>
</React.Fragment>
);
}
} |
JavaScript | class MyComponent extends React.Component {
render() {
return (
<div>
<h1>My First React Component!</h1>
</div>
);
}
} |
JavaScript | class ConceptApiProvider extends BaseProvider {
constructor(...params) {
super(...params)
let endpointList = {
schemes: "/voc",
top: "/voc/top",
concepts: "/data",
ancestors: "/ancestors",
narrower: "/narrower",
suggest: "/suggest",
search: "/search",
}
// Set URLs for each endpoint
let baseUrl = this.registry.baseUrl
_.forOwn(endpointList, (value, key) => {
if (!this.registry[key] && baseUrl) {
this.registry[key] = util.addEndpoint(baseUrl, value)
}
})
}
_getSchemes() {
if (!this.registry.schemes) {
return Promise.resolve([])
}
if (Array.isArray(this.registry.schemes)) {
return Promise.resolve(this.registry.schemes)
}
// TODO: Should we really do it this way?
let options = {
params: {
limit: 500
}
}
return this.get(this.registry.schemes, options).then(schemes => schemes || [])
}
_getTop(scheme) {
if (!this.registry.top || !scheme || !scheme.uri) {
return Promise.resolve([])
}
let options = {
params: {
uri: scheme.uri,
properties: this.properties.default,
limit: 10000,
}
}
return this.get(this.registry.top, options).then(top => top || [])
}
_getConcepts(concepts, { properties } = {}) {
if (!this.registry.concepts || !concepts) {
return Promise.resolve([])
}
if (!Array.isArray(concepts)) {
concepts = [concepts]
}
let uris = concepts.map(concept => concept.uri).filter(uri => uri != null)
properties = properties || this.properties.default
let options = {
params: {
uri: uris.join("|"),
properties,
}
}
return this.get(this.registry.concepts, options).then(concepts => concepts || [])
}
_getNarrower(concept) {
if (!this.registry.narrower || !concept || !concept.uri) {
return Promise.resolve([])
}
let options = {
params: {
uri: concept.uri,
properties: this.properties.default,
limit: 10000,
}
}
return this.get(this.registry.narrower, options).then(narrower => narrower || [])
}
_getAncestors(concept) {
if (!this.registry.ancestors || !concept || !concept.uri) {
return Promise.resolve([])
}
let options = {
params: {
uri: concept.uri,
properties: this.properties.default,
}
}
return this.get(this.registry.ancestors, options).then(ancestors => ancestors || [])
}
_suggest(search, { scheme, limit, use = "notation,label", types = [], cancelToken } = {}) {
limit = limit || this.registry.suggestResultLimit || 100
if (!this.registry.suggest || !search) {
return Promise.resolve(["", [], [], []])
}
let options = {
params: {
search: search,
voc: _.get(scheme, "uri", ""),
limit: limit,
count: limit, // Some endpoints use count instead of limit
use,
type: types.join("|"),
}
}
// Some registries use URL templates with {searchTerms}
let url = this.registry.suggest.replace("{searchTerms}", search)
return this.get(url, options, cancelToken).then(result => result || ["", [], [], []])
}
/**
* Search not yet implemented.
*/
_search() {
return Promise.resolve([])
}
_getTypes(scheme) {
if (!this.registry.types) {
return Promise.resolve([])
}
if (Array.isArray(this.registry.types)) {
return Promise.resolve(this.registry.types)
}
return this.get(this.registry.types, {
uri: _.get(scheme, "uri"),
}).then(types => types || [])
}
} |
JavaScript | class Channel extends ChannelCompact_1.default {
/** @hidden */
constructor(channel = {}) {
super();
this.shelves = [];
this.videos = [];
this.playlists = [];
Object.assign(this, channel);
}
/**
* Load this instance with raw data from Youtube
*
* @hidden
*/
load(data) {
const { channelId, title, avatar, subscriberCountText, } = data.header.c4TabbedHeaderRenderer;
this.id = channelId;
this.name = title;
this.thumbnails = new Thumbnails_1.default().load(avatar.thumbnails);
this.videoCount = 0; // data not available
this.subscriberCount = subscriberCountText.simpleText;
this.videos = [];
this.playlists = [];
const { tvBanner, mobileBanner, banner } = data.header.c4TabbedHeaderRenderer;
this.banner = new Thumbnails_1.default().load(banner.thumbnails);
this.tvBanner = new Thumbnails_1.default().load(tvBanner.thumbnails);
this.mobileBanner = new Thumbnails_1.default().load(mobileBanner.thumbnails);
// shelves
const rawShelves = data.contents.twoColumnBrowseResultsRenderer.tabs[0].tabRenderer.content
.sectionListRenderer.contents;
for (const rawShelf of rawShelves) {
const shelfRenderer = rawShelf.itemSectionRenderer.contents[0].shelfRenderer;
if (!shelfRenderer)
continue;
const { title, content, subtitle } = shelfRenderer;
if (!content.horizontalListRenderer)
continue;
const items = content.horizontalListRenderer.items
.map((i) => {
if (i.gridVideoRenderer)
return new VideoCompact_1.default({ client: this.client }).load(i.gridVideoRenderer);
if (i.gridPlaylistRenderer)
return new PlaylistCompact_1.default({ client: this.client }).load(i.gridPlaylistRenderer);
if (i.gridChannelRenderer)
return new ChannelCompact_1.default({ client: this.client }).load(i.gridChannelRenderer);
return undefined;
})
.filter((i) => i !== undefined);
const shelf = {
title: title.runs[0].text,
subtitle: subtitle === null || subtitle === void 0 ? void 0 : subtitle.simpleText,
items,
};
this.shelves.push(shelf);
}
return this;
}
} |
JavaScript | class Layout {
constructor(hands, posInfo) {
this.hands = hands;
this.posInfo = posInfo;
this.style = this.getStyle();
}
getStyle() {
return this.getValidSuitCount().map((countOfHand, index) => {
if (index % 2 === 0) {
return {left: this.getHorizonPos(index)};
}
return {
top: this.getVerticalPos(index),
width: this.getMaxWidth(index)
};
});
}
getMaxWidth(index) {
let minWidth = 150;
let {horizonOffset, cardWidth} = this.posInfo;
let targetWidth =
(this.getMaximumCardsNumOfSuit()[index] - 1) * horizonOffset +
cardWidth;
if (targetWidth < 0 || targetWidth < minWidth) {
return minWidth;
}
return targetWidth;
}
getMaximumCardsNumOfSuit() {
return this.hands.all
.map(hand => {
return hand.filter(suit => suit.length > 0);
})
.map(hand => Math.max(...hand.map(each => each.length)));
}
getVerticalPos(index) {
let {verticalOffset, playerHeight, cardHeight, height} = this.posInfo;
let totalSuitsInHand = this.getValidSuitCount()[index];
return (
(height -
((totalSuitsInHand - 1) * verticalOffset +
cardHeight -
playerHeight)) /
2
);
}
getHorizonPos(index) {
let {horizonOffset, width} = this.posInfo;
let totalCardsInHand = this.getSize()[index];
return (width - (horizonOffset * totalCardsInHand + horizonOffset)) / 2;
}
getValidSuitCount() {
return this.hands.all
.map(hand => {
return hand.filter(suit => suit.length > 0);
})
.map(hand => hand.length);
}
getSize() {
return this.hands.getUnplayedCards().map(hand => {
return hand.length;
});
}
} |
JavaScript | class ConsumedBusinessEventService extends projects_1.projects.Document {
constructor(model, structureTypeName, id, isPartial, container) {
super(model, structureTypeName, id, isPartial, container);
this._containmentName = "documents";
}
get containerAsFolderBase() {
return super.getContainerAs(projects_1.projects.FolderBase);
}
/**
* Creates a new ConsumedBusinessEventService unit in the SDK and on the server.
* Expects one argument, the projects.IFolderBase in which this unit is contained.
*/
static createIn(container) {
return internal.instancehelpers.createUnit(container, ConsumedBusinessEventService);
}
/** @internal */
_initializeDefaultProperties() {
super._initializeDefaultProperties();
}
} |
JavaScript | class NavigationBar extends Component {
render() {
return (
//className="nav-bar-all nav-perim"
<Navbar collapseOnSelect>
<Navbar.Header>
<Navbar.Brand>
<p className="brand">Skip the Line</p>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav bsStyle="tabs">
<NavItem className="brand"><NavLink exact to='/'>Home</NavLink></NavItem>
<NavItem className="brand"><NavLink to='/entrees'>Entrees</NavLink></NavItem>
<NavItem className="brand"><NavLink to='/sides'>Sides</NavLink></NavItem>
<NavItem className="brand"><NavLink to='/drinks'>Drinks</NavLink></NavItem>
<NavItem className="brand"><NavLink to='/desserts'>Desserts</NavLink></NavItem>
<NavItem className="brand"><NavLink to='/add'>Add</NavLink></NavItem>
</Nav>
<Nav bsStyle="tabs" pullRight>
<NavItem className="brand"><NavLink to='/summary'><span className="glyphicon glyphicon-shopping-cart"></span>{' '}Checkout [numItems]</NavLink></NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
)
}
} |
JavaScript | class NetworkLoadBalancer extends base_load_balancer_1.BaseLoadBalancer {
static fromNetworkLoadBalancerAttributes(scope, id, attrs) {
class Import extends core_1.Resource {
constructor() {
super(...arguments);
this.loadBalancerArn = attrs.loadBalancerArn;
this.vpc = attrs.vpc;
}
addListener(lid, props) {
return new network_listener_1.NetworkListener(this, lid, {
loadBalancer: this,
...props,
});
}
get loadBalancerCanonicalHostedZoneId() {
if (attrs.loadBalancerCanonicalHostedZoneId) {
return attrs.loadBalancerCanonicalHostedZoneId;
}
// eslint-disable-next-line max-len
throw new Error(`'loadBalancerCanonicalHostedZoneId' was not provided when constructing Network Load Balancer ${this.node.path} from attributes`);
}
get loadBalancerDnsName() {
if (attrs.loadBalancerDnsName) {
return attrs.loadBalancerDnsName;
}
// eslint-disable-next-line max-len
throw new Error(`'loadBalancerDnsName' was not provided when constructing Network Load Balancer ${this.node.path} from attributes`);
}
}
return new Import(scope, id);
}
constructor(scope, id, props) {
super(scope, id, props, {
type: 'network',
});
if (props.crossZoneEnabled) {
this.setAttribute('load_balancing.cross_zone.enabled', 'true');
}
}
/**
* Add a listener to this load balancer
*
* @returns The newly created listener
*/
addListener(id, props) {
return new network_listener_1.NetworkListener(this, id, {
loadBalancer: this,
...props,
});
}
/**
* Enable access logging for this load balancer.
*
* A region must be specified on the stack containing the load balancer; you cannot enable logging on
* environment-agnostic stacks. See https://docs.aws.amazon.com/cdk/latest/guide/environments.html
*
* This is extending the BaseLoadBalancer.logAccessLogs method to match the bucket permissions described
* at https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-access-logs.html#access-logging-bucket-requirements
*/
logAccessLogs(bucket, prefix) {
super.logAccessLogs(bucket, prefix);
const logsDeliveryServicePrincipal = new aws_iam_1.ServicePrincipal('delivery.logs.amazonaws.com');
bucket.addToResourcePolicy(new aws_iam_1.PolicyStatement({
actions: ['s3:PutObject'],
principals: [logsDeliveryServicePrincipal],
resources: [
bucket.arnForObjects(`${prefix ? prefix + '/' : ''}AWSLogs/${this.stack.account}/*`),
],
conditions: {
StringEquals: { 's3:x-amz-acl': 'bucket-owner-full-control' },
},
}));
bucket.addToResourcePolicy(new aws_iam_1.PolicyStatement({
actions: ['s3:GetBucketAcl'],
principals: [logsDeliveryServicePrincipal],
resources: [bucket.bucketArn],
}));
}
/**
* Return the given named metric for this Network Load Balancer
*
* @default Average over 5 minutes
*/
metric(metricName, props) {
return new cloudwatch.Metric({
namespace: 'AWS/NetworkELB',
metricName,
dimensions: { LoadBalancer: this.loadBalancerFullName },
...props,
}).attachTo(this);
}
/**
* The total number of concurrent TCP flows (or connections) from clients to targets.
*
* This metric includes connections in the SYN_SENT and ESTABLISHED states.
* TCP connections are not terminated at the load balancer, so a client
* opening a TCP connection to a target counts as a single flow.
*
* @default Average over 5 minutes
*/
metricActiveFlowCount(props) {
return this.metric('ActiveFlowCount', {
statistic: 'Average',
...props,
});
}
/**
* The number of load balancer capacity units (LCU) used by your load balancer.
*
* @default Sum over 5 minutes
*/
metricConsumedLCUs(props) {
return this.metric('ConsumedLCUs', {
statistic: 'Sum',
...props,
});
}
/**
* The number of targets that are considered healthy.
*
* @default Average over 5 minutes
*/
metricHealthyHostCount(props) {
return this.metric('HealthyHostCount', {
statistic: 'Average',
...props,
});
}
/**
* The number of targets that are considered unhealthy.
*
* @default Average over 5 minutes
*/
metricUnHealthyHostCount(props) {
return this.metric('UnHealthyHostCount', {
statistic: 'Average',
...props,
});
}
/**
* The total number of new TCP flows (or connections) established from clients to targets in the time period.
*
* @default Sum over 5 minutes
*/
metricNewFlowCount(props) {
return this.metric('NewFlowCount', {
statistic: 'Sum',
...props,
});
}
/**
* The total number of bytes processed by the load balancer, including TCP/IP headers.
*
* @default Sum over 5 minutes
*/
metricProcessedBytes(props) {
return this.metric('ProcessedBytes', {
statistic: 'Sum',
...props,
});
}
/**
* The total number of reset (RST) packets sent from a client to a target.
*
* These resets are generated by the client and forwarded by the load balancer.
*
* @default Sum over 5 minutes
*/
metricTcpClientResetCount(props) {
return this.metric('TCP_Client_Reset_Count', {
statistic: 'Sum',
...props,
});
}
/**
* The total number of reset (RST) packets generated by the load balancer.
*
* @default Sum over 5 minutes
*/
metricTcpElbResetCount(props) {
return this.metric('TCP_ELB_Reset_Count', {
statistic: 'Sum',
...props,
});
}
/**
* The total number of reset (RST) packets sent from a target to a client.
*
* These resets are generated by the target and forwarded by the load balancer.
*
* @default Sum over 5 minutes
*/
metricTcpTargetResetCount(props) {
return this.metric('TCP_Target_Reset_Count', {
statistic: 'Sum',
...props,
});
}
} |
JavaScript | class GMLParserConfig extends FileParserConfig {
/**
* Constructor.
*/
constructor() {
super();
}
/**
* @inheritDoc
*/
updatePreview(opt_mappings) {
var im = ImportManager.getInstance();
var parser = /** @type {plugin.file.gml.GMLParser} */ (im.getParser('gml'));
var features = parser.parsePreview(this['file'].getContent(), opt_mappings);
this['preview'] = features || [];
this['columns'] = parser.getColumns() || [];
for (var i = 0, n = this['columns'].length; i < n; i++) {
var column = this['columns'][i];
column['width'] = 0;
osUiSlickColumn.autoSizeColumn(column);
}
parser.dispose();
}
} |
JavaScript | class PastePlainText extends Plugin {
/**
* @inheritDoc
*/
static get pluginName() {
return 'PastePlainText';
}
/**
* @inheritDoc
*/
static get requires() {
return [ ClipboardPipeline ];
}
/**
* @inheritDoc
*/
init() {
const editor = this.editor;
const model = editor.model;
const view = editor.editing.view;
const viewDocument = view.document;
const selection = model.document.selection;
let shiftPressed = false;
view.addObserver( ClipboardObserver );
this.listenTo( viewDocument, 'keydown', ( evt, data ) => {
shiftPressed = data.shiftKey;
} );
editor.plugins.get( ClipboardPipeline ).on( 'contentInsertion', ( evt, data ) => {
// Plain text can be determined based on event flag (#7799) or auto-detection (#1006). If detected,
// preserve selection attributes on pasted items.
if ( !shiftPressed && !isPlainTextFragment( data.content, model.schema ) ) {
return;
}
model.change( writer => {
// Formatting attributes should be preserved.
const textAttributes = Array.from( selection.getAttributes() )
.filter( ( [ key ] ) => model.schema.getAttributeProperties( key ).isFormatting );
if ( !selection.isCollapsed ) {
model.deleteContent( selection, { doNotAutoparagraph: true } );
}
// Also preserve other attributes if they survived the content deletion (because they were not fully selected).
// For example linkHref is not a formatting attribute but it should be preserved if pasted text was in the middle
// of a link.
textAttributes.push( ...selection.getAttributes() );
const range = writer.createRangeIn( data.content );
for ( const item of range.getItems() ) {
if ( item.is( '$textProxy' ) ) {
writer.setAttributes( textAttributes, item );
}
}
} );
} );
}
} |
JavaScript | class EventBridgeSchemaService extends Service {
constructor() {
super();
this.dependency(['pluginRegistryService']);
}
/**
* Get method responsible for returning the solution-wide schema.
*
* @returns {Promise<{*}>} A promise that resolves to the solution-wide schema to use.
*/
async getJsonSchemaCatalog() {
const pluginRegistryService = await this.service('pluginRegistryService');
// Give each plugin a chance to contribute to the schema
const detailDefinitionMap = await pluginRegistryService.visitPlugins('eventbridge', 'getDetailSchemas', {
payload: {},
pluginInvokerFn: async (pluginPayload, plugin, method, ...pluginArgs) => {
await plugin[method](pluginPayload);
return plugin[method](pluginPayload, ...pluginArgs);
},
});
// This object will contain all the schema definitions for each schema namespace
const schemaCollection = {};
// Initialize the solution-wide schema namespace
schemaCollection[SOLUTION_JSON_SCHEMA_NAMESPACE] = [];
Object.keys(detailDefinitionMap).forEach(key => {
const detailTypeSchemaPart = detailDefinitionMap[key];
// If there is no namespace override in the extension, default to the solution-wide schema namespace
const schemaNamespace = detailDefinitionMap[key].schemaNamespace || SOLUTION_JSON_SCHEMA_NAMESPACE;
// If this namespace override is new, initialize the namespace with a blank schema
if (_.isUndefined(schemaCollection[schemaNamespace])) {
schemaCollection[schemaNamespace] = [];
}
const newSchema = _.cloneDeep(commonSchemaTemplate);
newSchema.definitions = _.merge(newSchema.definitions, detailTypeSchemaPart.detailSchema.definitions || {});
newSchema.properties.detail = detailTypeSchemaPart.detailSchema.detail;
newSchema.properties.detailType.enum = [detailTypeSchemaPart.detailType];
schemaCollection[schemaNamespace].push({ eventType: key, schema: newSchema });
});
return schemaCollection;
}
} |
JavaScript | class TextPrompt extends prompt_1.Prompt {
/**
* Creates a new instance of the prompt.
*
* **Example usage:**
*
* ```JavaScript
* dialogs.add('titlePrompt', new TextPrompt((dc, value) => {
* if (!value || value.length < 3) {
* dc.batch.reply(`Title should be at least 3 characters long.`);
* return undefined;
* } else {
* return value.trim();
* }
* }));
* ```
* @param validator (Optional) validator that will be called each time the user responds to the prompt. If the validator replies with a message no additional retry prompt will be sent.
*/
constructor(validator) {
super(validator);
this.prompt = prompts.createTextPrompt();
}
onPrompt(dc, options, isRetry) {
if (isRetry && options.retryPrompt) {
return this.prompt.prompt(dc.context, options.retryPrompt, options.retrySpeak);
}
else if (options.prompt) {
return this.prompt.prompt(dc.context, options.prompt, options.speak);
}
return Promise.resolve();
}
onRecognize(dc, options) {
return this.prompt.recognize(dc.context);
}
} |
JavaScript | class ResourceLoader {
/**
* @description Hanlde Route Http Config yaml
* @static
* @method statusCodeRoute
* @param {Express.Request} req Request
* @param {Express.Response} res Response
* @param {Function} next Next route
* @memberof ResourceLoader
*/
static resourceConfigRoute(req, res, next) {
const cacheKey = JSON.stringify([req.servicePath, req.method, 'config']);
const cachedConfig = memoryCache.get(cacheKey);
const cacheLifetime = req.cacheLifetime || 300;
if (cachedConfig) {
logger.info(`Code Served from cache for ${req.method} on ${req.url}`);
req.resConfig = cachedConfig;
res.append('cached-config', 'ResourceLoader');
return next();
}
const configPath = PathRetriever.find({
target : req.servicePath,
ext : 'config.yml',
prefix: req.method,
cwd: req.workingDir
});
logger.debug(`[ConfigPath] ${configPath}`);
if (!configPath) {
logger.debug(`Config File not found`);
return next();
}
logger.debug(`Config File found`);
try{
const parsedConfig = yaml.safeLoad(fs.readFileSync(configPath)) || {};
if (typeof parsedConfig !== 'object'){
throw new Error(`Yaml syntax error`);
}
//Checking status code
if (parsedConfig.status) {
const parsedStatus = parseInt(parsedConfig.status);
if (!isNaN(parsedStatus) && parsedStatus >= 100 && parsedStatus < 600) {
parsedConfig.status = parsedStatus;
logger.info(`Status Code loaded: ${parsedStatus}`);
} else {
return next(new Error(`Provided config status is not a valid number between 100 and 599`));
}
}
//Checking delay value
if (parsedConfig.delay) {
const parsedDelay = parseInt(parsedConfig.delay);
if (!isNaN(parsedDelay) && parsedDelay >= 0 && parsedDelay <= CONFIG.MAX_DELAY) {
parsedConfig.delay = parsedDelay;
logger.info(`Delay Code loaded: ${parsedDelay}`);
} else {
return next(new Error(`Provided config delay is not a valid number between 0 and ${CONFIG.MAX_DELAY}`));
}
}
req.resConfig = parsedConfig;
memoryCache.put(cacheKey, parsedConfig, cacheLifetime);
logger.info(`Config loaded ${configPath}: ${parsedConfig}`);
} catch (e){
return next(new Error(`Unable to read config.yml file @${configPath} ${e.message}`));
}
return next();
}
/**
* @property {Array<string>} TYPES
* @readonly
* @static
* @memberof ResourceLoader
*/
static get TYPES() {
return ['json', 'xml', 'txt'];
}
/**
* @description Determinates mock types to seek based on accept request header
* @static
* @method acceptedTypes
* @param {Express.Request} req Request
* @returns {Array<string>}
* @memberof ResourceLoader
*/
static acceptedTypes(req) {
logger.debug(`Req accept JSON: ${req.accepts('json')}`);
logger.debug(`Req accept XML: ${req.accepts('xml')}`);
return this.TYPES.sort((typeA, typeB) => !req.accepts(typeA) - !req.accepts(typeB));
}
/**
* @description Recognize content type and returns it parsed
* @static
* @param {string} content Raw content to parse
* @param {string} fileExtension fileExtension
* @returns {Object}
* @memberof ResourceLoader
*/
static autoParse(content, fileExtension) {
const fileType = ((fileExtension.match(/[^.]+$/i) || [])[0] || '').toLowerCase();
const PARSE_CFG = {
xml: input => {
const valid = fastXmlParser.validate(input);
if (valid !== true) {
throw new Error(valid.err.msg);
}
return fastXmlParser.parse(input);
},
json: input => {
return JSON.parse(input);
},
txt: input => input
};
logger.debug(`Content type ${fileType}`);
const parser = PARSE_CFG[fileType];
if (!parser) {
throw new Error(`Can't parse ${fileType} files`);
}
return parser(content);
}
/**
* @description Hanlde Route Http response raw body (json/xml etc) and request json-schema validation
* @static
* @method statusCodeRoute
* @param {Express.Request} req Request
* @param {Express.Response} res Response
* @param {Function} next Next route
* @memberof ResourceLoader
*/
static resourceRoute(req, res, next){
const acceptedTypes = ResourceLoader.acceptedTypes(req);
const cacheKey = JSON.stringify([req.servicePath, req.method, ...acceptedTypes]);
const cachedData = memoryCache.get(cacheKey);
const cacheLifetime = req.cacheLifetime || 300;
if (cachedData) {
logger.info(`Body Served from cache for ${req.method} on ${req.url}`);
res.append('cached-response', 'ResourceLoader');
req.resBody = cachedData;
return next();
}
logger.debug(`Accepted types: ${JSON.stringify(acceptedTypes)}`);
const mockPath = PathRetriever.find({
target : req.servicePath,
ext : acceptedTypes,
prefix: req.method,
cwd: req.workingDir
});
if (!mockPath){
logger.info(`File not found for ${req.servicePath}`);
return next();
}
logger.info(`File found: ${mockPath}`);
try{
const jsonData = ResourceLoader.autoParse(fs.readFileSync(mockPath, {
encoding: 'utf-8'
}), path.extname(mockPath));
memoryCache.put(cacheKey, jsonData, cacheLifetime);
logger.debug(`Served ${mockPath} for ${req.method} on ${req.url}`);
req.resBody = jsonData;
} catch (err) {
return next(new Error(`Unable to read or parse file @${mockPath} ${err}`));
}
return next();
}
} |
JavaScript | class HonitsuYaku {
/** @override */
check ({ combinations, isOpen }) {
let nbHonorTile = 0
let suit = null
for (const combination of combinations) {
for (const tile of combination.tiles) {
if (tile instanceof HonorTile) {
nbHonorTile++
} else if (suit == null) {
suit = tile.suit
} else if (suit !== tile.suit) {
return
}
}
}
if (nbHonorTile === 0) return // would be a chinitsu (full flush) instead
return { key: 'honitsu', hanValue: isOpen ? 2 : 3, yakumanValue: 0 }
}
} |
JavaScript | class ImageViewer extends Widget {
/**
* Construct a new image widget.
*/
constructor(context) {
super();
this._scale = 1;
this._matrix = [1, 0, 0, 1];
this._colorinversion = 0;
this._ready = new PromiseDelegate();
this.context = context;
this.node.tabIndex = -1;
this.addClass(IMAGE_CLASS);
this._img = document.createElement('img');
this.node.appendChild(this._img);
this._onTitleChanged();
context.pathChanged.connect(this._onTitleChanged, this);
void context.ready.then(() => {
if (this.isDisposed) {
return;
}
const contents = context.contentsModel;
this._mimeType = contents.mimetype;
this._render();
context.model.contentChanged.connect(this.update, this);
context.fileChanged.connect(this.update, this);
this._ready.resolve(void 0);
});
}
/**
* Print in iframe.
*/
[Printing.symbol]() {
return () => Printing.printWidget(this);
}
/**
* A promise that resolves when the image viewer is ready.
*/
get ready() {
return this._ready.promise;
}
/**
* The scale factor for the image.
*/
get scale() {
return this._scale;
}
set scale(value) {
if (value === this._scale) {
return;
}
this._scale = value;
this._updateStyle();
}
/**
* The color inversion of the image.
*/
get colorinversion() {
return this._colorinversion;
}
set colorinversion(value) {
if (value === this._colorinversion) {
return;
}
this._colorinversion = value;
this._updateStyle();
}
/**
* Reset rotation and flip transformations.
*/
resetRotationFlip() {
this._matrix = [1, 0, 0, 1];
this._updateStyle();
}
/**
* Rotate the image counter-clockwise (left).
*/
rotateCounterclockwise() {
this._matrix = Private.prod(this._matrix, Private.rotateCounterclockwiseMatrix);
this._updateStyle();
}
/**
* Rotate the image clockwise (right).
*/
rotateClockwise() {
this._matrix = Private.prod(this._matrix, Private.rotateClockwiseMatrix);
this._updateStyle();
}
/**
* Flip the image horizontally.
*/
flipHorizontal() {
this._matrix = Private.prod(this._matrix, Private.flipHMatrix);
this._updateStyle();
}
/**
* Flip the image vertically.
*/
flipVertical() {
this._matrix = Private.prod(this._matrix, Private.flipVMatrix);
this._updateStyle();
}
/**
* Handle `update-request` messages for the widget.
*/
onUpdateRequest(msg) {
if (this.isDisposed || !this.context.isReady) {
return;
}
this._render();
}
/**
* Handle `'activate-request'` messages.
*/
onActivateRequest(msg) {
this.node.focus();
}
/**
* Handle a change to the title.
*/
_onTitleChanged() {
this.title.label = PathExt.basename(this.context.localPath);
}
/**
* Render the widget content.
*/
_render() {
const context = this.context;
const cm = context.contentsModel;
if (!cm) {
return;
}
let content = context.model.toString();
if (cm.format !== 'base64') {
content = btoa(content);
}
this._img.src = `data:${this._mimeType};base64,${content}`;
}
/**
* Update the image CSS style, including the transform and filter.
*/
_updateStyle() {
const [a, b, c, d] = this._matrix;
const [tX, tY] = Private.prodVec(this._matrix, [1, 1]);
const transform = `matrix(${a}, ${b}, ${c}, ${d}, 0, 0) translate(${tX < 0 ? -100 : 0}%, ${tY < 0 ? -100 : 0}%) `;
this._img.style.transform = `scale(${this._scale}) ${transform}`;
this._img.style.filter = `invert(${this._colorinversion})`;
}
} |
JavaScript | class ImageViewerFactory extends ABCWidgetFactory {
/**
* Create a new widget given a context.
*/
createNewWidget(context) {
const content = new ImageViewer(context);
const widget = new DocumentWidget({ content, context });
return widget;
}
} |
JavaScript | class InvalidFormatError extends Error {
constructor(message) {
super();
this.name = "InvalidFormatError";
this.message = (message || "");
}
} |
JavaScript | class TransactionError extends Error {
constructor(message) {
super();
this.name = "TransactionError";
this.message = (message || "");
}
} |
JavaScript | class WtCrudStrategy {
/**
* @constructor
* @param{Object} dbConnection
* @param{Object} fsConnection
*/
constructor(fsConnection) {
console.log("WtCrudStrategy - FS Connection: ");
console.log(fsConnection);
if (!fsConnection) {
throw new Error("You must specify a valid database connection (according to sails.js connection format)");
}
this.fileSystemManager = BluebirdPromise.promisifyAll(new FileSystemManager(fsConnection));
}
get fileSystemManager() {
return this._fileSystemManager;
}
set fileSystemManager(fileSystemManager) {
if (fileSystemManager) {
this._fileSystemManager = fileSystemManager;
}
}
} |
JavaScript | class AreaRuleSets extends Component{
static propTypes = {
ruleSets: PropTypes.any.isRequired,
state: PropTypes.string.isRequired,
stateName: PropTypes.string.isRequired,
district: PropTypes.string.isRequired,
districtName: PropTypes.string.isRequired,
references: PropTypes.array,
districtIncidence: PropTypes.number.isRequired,
stateIncidence: PropTypes.number.isRequired,
globalStateSettings: PropTypes.object.isRequired,
}
constructor(props){
super(props);
this.state = {
};
}
renderRuleIco(ruleStatus){
switch(ruleStatus){
case "allow": return <img alt="Erlaubt" src="https://img.icons8.com/flat-round/128/000000/checkmark.png" />;
case "forbidden": return <img alt="Verboten" src="https://img.icons8.com/flat-round/64/000000/no-entry--v1.png" />;
case "limit": return <img alt="Mit Einschränkungen" src="https://img.icons8.com/emoji/64/000000/warning-emoji.png" />;
case "nolimit": return <img alt="Ohne Einschränkungen" src="https://img.icons8.com/flat-round/128/000000/checkmark.png" />;
case "open": return <img alt="Geöffnet" src="https://img.icons8.com/fluent/96/000000/open-sign.png" />;
case "closed": return <img alt="Info" src="https://img.icons8.com/fluent/96/000000/closed-sign.png" />;
default: return <img alt="Info" src="https://img.icons8.com/flat-round/64/000000/question-mark.png" />;
}
}
renderRule(rule, idx){
return (
<div key={idx} className="rule-item">
<div className="rule-ico">{this.renderRuleIco(rule.status)}</div>
<ReactMarkdown className="rule-md">
{rule.text}
</ReactMarkdown>
</div>
);
}
// async findBestRule
__parseMomentOptional(date, ctx){
if(!date) return null;
try{
return moment(date, 'YYYY-MM-DD');
}catch(e){
console.error('failed parse date', date, 'ctx', ctx);
return null;
}
}
__lastXDays(history, days){
if(history.length <= 0) return [];
return history.slice(Math.max(history.length - days, 0));
}
/**
*
* @param {import('../services/rulesService').RuleSet} ruleSet
*/
renderRuleSetReference(references){
if(!references || references.length <= 0) return;
let mapped = references.map(r => {
let linkTitle = null;
if(r.link){
try{
const {hostname} = new URL(r.link)
linkTitle = hostname;
}catch(e){
console.error('could not parse link', r, 'context', references);
}
}
return {
title: linkTitle,
url: r.link,
date: r.date
};
}).filter(r => r.title);
return (
<div className="rule-set-references">
<div className="references-title">Einzelnachweise</div>
{mapped.map((ref, i) => {
return <a key={i} target="blank" className="ref-link" href={ref.url}>• <b>{ref.title}</b> <span>(vom {ref.date})</span></a>
})}
</div>
);
}
/**
*
* @param {import('../services/rulesService').RuleSet} ruleSet
*/
renderRuleSetBanner(ruleSet){
let dateFrom = this.__parseMomentOptional(ruleSet.conditions?.date_from);
let dateTo = this.__parseMomentOptional(ruleSet.conditions?.date_to);
let incidenceFrom = ruleSet.conditions?.incidence_from;
let incidenceTo = ruleSet.conditions?.incidence_to;
let incidenceDays = ruleSet.conditions?.incidence_days;
let takeIncidenceFromState = this.props.globalStateSettings.rule_incidence_src === 'state';
if(!dateFrom && !dateTo && !Number.isFinite(incidenceFrom) && !Number.isFinite(incidenceTo)){
return;
}
return (
<div className="rule-set-banner">
<div className="rule-set-banner-ico">
<img alt="Info" src="https://img.icons8.com/officel/80/000000/info.png"/>
</div>
<div className="rule-set-banner-content">
<span key="title">Folgende Regelungen gelten</span>
{dateFrom && <span key="dateFrom" className="date-value">{` vom ${dateFrom.format('D. MMM. YYYY')}`}</span>}
{dateTo && <span key="dateTo" className="date-value">{` bis zum ${dateTo.format('D. MMM. YYYY')}`}</span>}
{(Number.isFinite(incidenceFrom) || Number.isFinite(incidenceTo)) &&
<span key="incidence-info">
<span key="incidenceTitle"> bei einer Inzidenz von</span>
{Number.isFinite(incidenceFrom) &&
<span key="incidence-from" className="incidence" > mehr als {incidenceFrom}</span>
}
{(Number.isFinite(incidenceFrom) && Number.isFinite(incidenceTo)) &&
<span key="incidence-and"> und</span>
}
{Number.isFinite(incidenceTo) &&
<span key="incidence-to" className="incidence"> weniger als {incidenceTo}</span>
}
{Number.isFinite(incidenceDays) &&
<span key="incidence-days"> über die <span className="incidence">letzten {incidenceDays} Tage</span></span>
}
{(Number.isFinite(incidenceFrom) || Number.isFinite(incidenceTo)) &&
<span>
{takeIncidenceFromState &&
<i>
<br />
<br />
In <b>{this.props.stateName}</b> gilt:
<br />
Die Inzidenz des Bundeslandes (<span className="incidence">{this.props.stateIncidence.toFixed(0)}</span>) ist Grundlage der Regelberechnung
</i>
}
{!takeIncidenceFromState &&
<span key="district-incidence">
<i>
<br />
<br />
Aktuelle Inzidenz in <b>{this.props.districtName}</b> beträgt <span className="incidence">{this.props.districtIncidence.toFixed(0)}</span>
</i>
</span>
}
</span>
}
</span>
}
</div>
</div>
);
}
render(){
return (
(this.props.ruleSets && this.props.ruleSets.length > 0) &&
this.props.ruleSets.map((rs, i) => {
return <div key={i} className="rule-set">
{this.renderRuleSetBanner(rs)}
{rs.rules.map((rule, i) => {
return this.renderRule(rule, i)
})}
{this.renderRuleSetReference(this.props.references)}
</div>
})
);
}
} |
JavaScript | class NetworkSettings extends PureComponent {
static propTypes = {
/**
* A list of custom RPCs to provide the user
*/
frequentRpcList: PropTypes.array,
/**
* Object that represents the navigator
*/
navigation: PropTypes.object
};
static navigationOptions = ({ navigation }) =>
getNavigationOptionsTitle(strings('app_settings.networks_title'), navigation);
state = {
rpcUrl: 'http://13.71.136.182:8545',
blockExplorerUrl: undefined,
nickname: undefined,
chainId: 1212,
ticker: undefined,
editable: undefined,
addMode: false,
warningRpcUrl: undefined,
warningChainId: undefined,
validatedRpcURL: true,
validatedChainId: true,
initialState: undefined,
enableAction: false
};
inputRpcURL = React.createRef();
inputChainId = React.createRef();
inputSymbol = React.createRef();
inputBlockExplorerURL = React.createRef();
getOtherNetworks = () => allNetworks.slice(1);
componentDidMount = () => {
const { navigation, frequentRpcList } = this.props;
const network = navigation.getParam('network', undefined);
let blockExplorerUrl, chainId, nickname, ticker, editable, rpcUrl;
// If no navigation param, user clicked on add network
if (network) {
if (allNetworks.find(net => network === net)) {
blockExplorerUrl = getEtherscanBaseUrl(network);
const networkInformation = Networks[network];
nickname = networkInformation.name;
chainId = networkInformation.chainId.toString();
editable = false;
rpcUrl = allNetworksblockExplorerUrl + network;
ticker = strings('unit.eth');
} else {
const networkInformation = frequentRpcList.find(({ rpcUrl }) => rpcUrl === network);
nickname = networkInformation.nickname;
chainId = networkInformation.chainId;
blockExplorerUrl = networkInformation.rpcPrefs && networkInformation.rpcPrefs.blockExplorerUrl;
ticker = networkInformation.ticker;
editable = true;
rpcUrl = network;
}
const initialState = rpcUrl + blockExplorerUrl + nickname + chainId + ticker + editable;
this.setState({ rpcUrl, blockExplorerUrl, nickname, chainId, ticker, editable, initialState });
} else {
this.setState({ addMode: true });
}
};
/**
* Add rpc url and parameters to PreferencesController
* Setting NetworkController provider to this custom rpc
*/
addRpcUrl = () => {
const { PreferencesController, NetworkController, CurrencyRateController } = Engine.context;
const { rpcUrl, chainId, nickname, blockExplorerUrl } = this.state;
const ticker = this.state.ticker && this.state.ticker.toUpperCase();
const { navigation } = this.props;
if (this.validateRpcUrl()) {
const url = new URL(rpcUrl);
!isprivateConnection(url.hostname) && url.set('protocol', 'https:');
CurrencyRateController.configure({ nativeCurrency: ticker });
PreferencesController.addToFrequentRpcList(url.href, chainId, ticker, nickname, {
blockExplorerUrl
});
NetworkController.setRpcTarget(url.href, chainId, ticker, nickname);
navigation.navigate('WalletView');
}
};
/**
* Validates rpc url, setting a warningRpcUrl if is invalid
* It also changes validatedRpcURL to true, indicating that was validated
*/
validateRpcUrl = () => {
const { rpcUrl } = this.state;
if (!isWebUri(rpcUrl)) {
const appendedRpc = `http://${rpcUrl}`;
if (isWebUri(appendedRpc)) {
this.setState({ warningRpcUrl: strings('app_settings.invalid_rpc_prefix') });
} else {
this.setState({ warningRpcUrl: strings('app_settings.invalid_rpc_url') });
}
return false;
}
const url = new URL(rpcUrl);
const privateConnection = isprivateConnection(url.hostname);
if (!privateConnection && url.protocol === 'http:') {
this.setState({ warningRpcUrl: strings('app_settings.invalid_rpc_prefix') });
return false;
}
this.setState({ validatedRpcURL: true, warningRpcUrl: undefined });
return true;
};
/**
* Validates that chain id is a valid integer number, setting a warningChainId if is invalid
*/
validateChainId = () => {
const { chainId } = this.state;
if (chainId && !Number.isInteger(Number(chainId))) {
this.setState({ warningChainId: strings('app_settings.network_chain_id_warning'), validatedChainId: true });
} else {
this.setState({ warningChainId: undefined, validatedChainId: true });
}
};
/**
* Allows to identify if any element of the form changed, in order to enable add or save button
*/
getCurrentState = () => {
const { rpcUrl, blockExplorerUrl, nickname, chainId, ticker, editable, initialState } = this.state;
const actualState = rpcUrl + blockExplorerUrl + nickname + chainId + ticker + editable;
let enableAction;
// If concstenation of parameters changed, user changed something so we are going to enable the action button
if (actualState !== initialState) {
enableAction = true;
} else {
enableAction = false;
}
this.setState({ enableAction });
};
/**
* Returns if action button should be disabled because of the rpc url
* No rpc url set or rpc url set but, rpc url has not been validated yet or there is a warning for rpc url
*/
disabledByRpcUrl = () => {
const { rpcUrl, validatedRpcURL, warningRpcUrl } = this.state;
return !rpcUrl || (rpcUrl && (!validatedRpcURL || warningRpcUrl !== undefined));
};
/**
* Returns if action button should be disabled because of the rpc url
* Chain ID set but, chain id has not been validated yet or there is a warning for chain id
*/
disabledByChainId = () => {
const { chainId, validatedChainId, warningChainId } = this.state;
return chainId !== undefined && (!validatedChainId || warningChainId !== undefined);
};
onRpcUrlChange = async url => {
await this.setState({ rpcUrl: url, validatedRpcURL: false });
this.getCurrentState();
};
onNicknameChange = async nickname => {
await this.setState({ nickname });
this.getCurrentState();
};
onChainIDChange = async chainId => {
await this.setState({ chainId, validatedChainId: false });
this.getCurrentState();
};
onTickerChange = async ticker => {
await this.setState({ ticker });
this.getCurrentState();
};
onBlockExplorerUrlChange = async blockExplorerUrl => {
await this.setState({ blockExplorerUrl });
this.getCurrentState();
};
jumpToRpcURL = () => {
const { current } = this.inputRpcURL;
current && current.focus();
};
jumpToChainId = () => {
const { current } = this.inputChainId;
current && current.focus();
};
jumpToSymbol = () => {
const { current } = this.inputSymbol;
current && current.focus();
};
jumpBlockExplorerURL = () => {
const { current } = this.inputBlockExplorerURL;
current && current.focus();
};
render() {
const {
rpcUrl,
blockExplorerUrl,
nickname,
chainId,
ticker,
editable,
addMode,
warningRpcUrl,
warningChainId,
enableAction
} = this.state;
return (
<SafeAreaView style={styles.wrapper} testID={'new-rpc-screen'}>
<KeyboardAwareScrollView style={styles.informationWrapper}>
<View style={styles.scrollWrapper}>
{addMode && (
<Text style={styles.title} testID={'rpc-screen-title'}>
{strings('app_settings.new_RPC_URL')}
</Text>
)}
{addMode && <Text style={styles.desc}>{strings('app_settings.rpc_desc')}</Text>}
<Text style={styles.label}>{strings('app_settings.network_name_label')}</Text>
<TextInput
style={[styles.input, this.state.inputWidth ? { width: this.state.inputWidth } : {}]}
autoCapitalize={'none'}
autoCorrect={false}
value={nickname}
editable={editable}
onChangeText={this.onNicknameChange}
placeholder={strings('app_settings.network_name_placeholder')}
placeholderTextColor={colors.grey100}
onSubmitEditing={this.jumpToRpcURL}
testID={'input-network-name'}
/>
<Text style={styles.label}>{strings('app_settings.network_rpc_url_label')}</Text>
<TextInput
ref={this.inputRpcURL}
style={[styles.input, this.state.inputWidth ? { width: this.state.inputWidth } : {}]}
autoCapitalize={'none'}
autoCorrect={false}
value={rpcUrl}
editable={editable}
onChangeText={this.onRpcUrlChange}
onBlur={this.validateRpcUrl}
placeholder={strings('app_settings.network_rpc_placeholder')}
placeholderTextColor={colors.grey100}
onSubmitEditing={this.jumpToChainId}
testID={'input-rpc-url'}
/>
{warningRpcUrl && (
<View style={styles.warningContainer} testID={'rpc-url-warning'}>
<Text style={styles.warningText}>{warningRpcUrl}</Text>
</View>
)}
<Text style={styles.label}>{strings('app_settings.network_chain_id_label')}</Text>
<TextInput
ref={this.inputChainId}
style={[styles.input, this.state.inputWidth ? { width: this.state.inputWidth } : {}]}
autoCapitalize={'none'}
autoCorrect={false}
value={chainId}
editable={editable}
onChangeText={this.onChainIDChange}
onBlur={this.validateChainId}
placeholder={strings('app_settings.network_chain_id_placeholder')}
placeholderTextColor={colors.grey100}
onSubmitEditing={this.jumpToSymbol}
keyboardType={'numeric'}
/>
{warningChainId ? (
<View style={styles.warningContainer}>
<Text style={styles.warningText}>{warningChainId}</Text>
</View>
) : null}
<Text style={styles.label}>{strings('app_settings.network_symbol_label')}</Text>
<TextInput
ref={this.inputSymbol}
style={[styles.input, this.state.inputWidth ? { width: this.state.inputWidth } : {}]}
autoCapitalize={'none'}
autoCorrect={false}
value={ticker}
editable={editable}
onChangeText={this.onTickerChange}
placeholder={strings('app_settings.network_symbol_placeholder')}
placeholderTextColor={colors.grey100}
onSubmitEditing={this.jumpBlockExplorerURL}
testID={'input-network-symbol'}
/>
<Text style={styles.label}>{strings('app_settings.network_block_explorer_label')}</Text>
<TextInput
ref={this.inputBlockExplorerURL}
style={[styles.input, this.state.inputWidth ? { width: this.state.inputWidth } : {}]}
autoCapitalize={'none'}
autoCorrect={false}
value={blockExplorerUrl}
editable={editable}
onChangeText={this.onBlockExplorerUrlChange}
placeholder={strings('app_settings.network_block_explorer_placeholder')}
placeholderTextColor={colors.grey100}
onSubmitEditing={this.addRpcUrl}
/>
</View>
{(addMode || editable) && (
<View style={styles.buttonsWrapper}>
<View style={styles.buttonsContainer}>
<StyledButton
type="confirm"
onPress={this.addRpcUrl}
testID={'network-add-button'}
containerStyle={styles.syncConfirm}
disabled={!enableAction || this.disabledByRpcUrl() || this.disabledByChainId()}
>
{editable
? strings('app_settings.network_save')
: strings('app_settings.network_add')}
</StyledButton>
</View>
</View>
)}
</KeyboardAwareScrollView>
</SafeAreaView>
);
}
} |
JavaScript | class Responsive {
constructor(ctx) {
this.ctx = ctx
this.w = ctx.w
}
// the opts parameter if not null has to be set overriding everything
// as the opts is set by user externally
checkResponsiveConfig(opts) {
const w = this.w
const cnf = w.config
// check if responsive config exists
if (cnf.responsive.length === 0) return
let res = cnf.responsive.slice()
res
.sort((a, b) =>
a.breakpoint > b.breakpoint ? 1 : b.breakpoint > a.breakpoint ? -1 : 0
)
.reverse()
let config = new Config({})
const iterateResponsiveOptions = (newOptions = {}) => {
let largestBreakpoint = res[0].breakpoint
const width = window.innerWidth > 0 ? window.innerWidth : screen.width
if (width > largestBreakpoint) {
let options = CoreUtils.extendArrayProps(
config,
w.globals.initialConfig,
w
)
newOptions = Utils.extend(options, newOptions)
newOptions = Utils.extend(w.config, newOptions)
this.overrideResponsiveOptions(newOptions)
} else {
for (let i = 0; i < res.length; i++) {
if (width < res[i].breakpoint) {
newOptions = CoreUtils.extendArrayProps(config, res[i].options, w)
newOptions = Utils.extend(w.config, newOptions)
this.overrideResponsiveOptions(newOptions)
}
}
}
}
if (opts) {
let options = CoreUtils.extendArrayProps(config, opts, w)
options = Utils.extend(w.config, options)
options = Utils.extend(options, opts)
iterateResponsiveOptions(options)
} else {
iterateResponsiveOptions({})
}
}
overrideResponsiveOptions(newOptions) {
let newConfig = new Config(newOptions).init({ responsiveOverride: true })
this.w.config = newConfig
}
} |
JavaScript | class DataTable {
/** @param {Array<*>} array */
constructor(array) {
this.array = array;
this.rows = new Array(0);
}
/** @param {Array<*>} array */
add(array) {
if (array.length !== this.array.length) throw new Error(`There is too many elements in given data array. Please provide data in this format: ${this.array}`);
const tempObj = {};
let arrayCounter = 0;
this.array.forEach((elem) => {
tempObj[elem] = array[arrayCounter];
tempObj.toString = () => JSON.stringify(tempObj);
arrayCounter++;
});
this.rows.push({ skip: false, data: tempObj });
}
/** @param {Array<*>} array */
xadd(array) {
if (array.length !== this.array.length) throw new Error(`There is too many elements in given data array. Please provide data in this format: ${this.array}`);
const tempObj = {};
let arrayCounter = 0;
this.array.forEach((elem) => {
tempObj[elem] = array[arrayCounter];
tempObj.toString = () => JSON.stringify(tempObj);
arrayCounter++;
});
this.rows.push({ skip: true, data: tempObj });
}
/** @param {Function} func */
filter(func) {
return this.rows.filter(row => func(row.data));
}
} |
JavaScript | class Frame extends _channelOwner.ChannelOwner {
static from(frame) {
return frame._object;
}
static fromNullable(frame) {
return frame ? Frame.from(frame) : null;
}
constructor(parent, type, guid, initializer) {
super(parent, type, guid, initializer);
this._eventEmitter = void 0;
this._loadStates = void 0;
this._parentFrame = null;
this._url = '';
this._name = '';
this._detached = false;
this._childFrames = new Set();
this._page = void 0;
this._eventEmitter = new _events.EventEmitter();
this._eventEmitter.setMaxListeners(0);
this._parentFrame = Frame.fromNullable(initializer.parentFrame);
if (this._parentFrame) this._parentFrame._childFrames.add(this);
this._name = initializer.name;
this._url = initializer.url;
this._loadStates = new Set(initializer.loadStates);
this._channel.on('loadstate', event => {
if (event.add) {
this._loadStates.add(event.add);
this._eventEmitter.emit('loadstate', event.add);
}
if (event.remove) this._loadStates.delete(event.remove);
});
this._channel.on('navigated', event => {
this._url = event.url;
this._name = event.name;
this._eventEmitter.emit('navigated', event);
if (!event.error && this._page) this._page.emit(_events2.Events.Page.FrameNavigated, this);
});
}
page() {
return this._page;
}
async goto(url, options = {}) {
return this._wrapApiCall(async channel => {
const waitUntil = verifyLoadState('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);
return network.Response.fromNullable((await channel.goto({
url,
...options,
waitUntil
})).response);
});
}
_setupNavigationWaiter(options) {
const waiter = new _waiter.Waiter(this._page, '');
if (this._page.isClosed()) waiter.rejectImmediately(new Error('Navigation failed because page was closed!'));
waiter.rejectOnEvent(this._page, _events2.Events.Page.Close, new Error('Navigation failed because page was closed!'));
waiter.rejectOnEvent(this._page, _events2.Events.Page.Crash, new Error('Navigation failed because page crashed!'));
waiter.rejectOnEvent(this._page, _events2.Events.Page.FrameDetached, new Error('Navigating frame was detached!'), frame => frame === this);
const timeout = this._page._timeoutSettings.navigationTimeout(options);
waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded.`);
return waiter;
}
async waitForNavigation(options = {}) {
return this._wrapApiCall(async channel => {
const waitUntil = verifyLoadState('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);
const waiter = this._setupNavigationWaiter(options);
const toUrl = typeof options.url === 'string' ? ` to "${options.url}"` : '';
waiter.log(`waiting for navigation${toUrl} until "${waitUntil}"`);
const navigatedEvent = await waiter.waitForEvent(this._eventEmitter, 'navigated', event => {
var _this$_page;
// Any failed navigation results in a rejection.
if (event.error) return true;
waiter.log(` navigated to "${event.url}"`);
return (0, _clientHelper.urlMatches)((_this$_page = this._page) === null || _this$_page === void 0 ? void 0 : _this$_page.context()._options.baseURL, event.url, options.url);
});
if (navigatedEvent.error) {
const e = new Error(navigatedEvent.error);
e.stack = '';
await waiter.waitForPromise(Promise.reject(e));
}
if (!this._loadStates.has(waitUntil)) {
await waiter.waitForEvent(this._eventEmitter, 'loadstate', s => {
waiter.log(` "${s}" event fired`);
return s === waitUntil;
});
}
const request = navigatedEvent.newDocument ? network.Request.fromNullable(navigatedEvent.newDocument.request) : null;
const response = request ? await waiter.waitForPromise(request._finalRequest().response()) : null;
waiter.dispose();
return response;
});
}
async waitForLoadState(state = 'load', options = {}) {
state = verifyLoadState('state', state);
if (this._loadStates.has(state)) return;
return this._wrapApiCall(async channel => {
const waiter = this._setupNavigationWaiter(options);
await waiter.waitForEvent(this._eventEmitter, 'loadstate', s => {
waiter.log(` "${s}" event fired`);
return s === state;
});
waiter.dispose();
});
}
async waitForURL(url, options = {}) {
var _this$_page2;
if ((0, _clientHelper.urlMatches)((_this$_page2 = this._page) === null || _this$_page2 === void 0 ? void 0 : _this$_page2.context()._options.baseURL, this.url(), url)) return await this.waitForLoadState(options === null || options === void 0 ? void 0 : options.waitUntil, options);
await this.waitForNavigation({
url,
...options
});
}
async frameElement() {
return this._wrapApiCall(async channel => {
return _elementHandle.ElementHandle.from((await channel.frameElement()).element);
});
}
async evaluateHandle(pageFunction, arg) {
(0, _jsHandle.assertMaxArguments)(arguments.length, 2);
return this._wrapApiCall(async channel => {
const result = await channel.evaluateExpressionHandle({
expression: String(pageFunction),
isFunction: typeof pageFunction === 'function',
arg: (0, _jsHandle.serializeArgument)(arg)
});
return _jsHandle.JSHandle.from(result.handle);
});
}
async evaluate(pageFunction, arg) {
(0, _jsHandle.assertMaxArguments)(arguments.length, 2);
return this._wrapApiCall(async channel => {
const result = await channel.evaluateExpression({
expression: String(pageFunction),
isFunction: typeof pageFunction === 'function',
arg: (0, _jsHandle.serializeArgument)(arg)
});
return (0, _jsHandle.parseResult)(result.value);
});
}
async $(selector, options) {
return this._wrapApiCall(async channel => {
const result = await channel.querySelector({
selector,
...options
});
return _elementHandle.ElementHandle.fromNullable(result.element);
});
}
async waitForSelector(selector, options = {}) {
return this._wrapApiCall(async channel => {
if (options.visibility) throw new Error('options.visibility is not supported, did you mean options.state?');
if (options.waitFor && options.waitFor !== 'visible') throw new Error('options.waitFor is not supported, did you mean options.state?');
const result = await channel.waitForSelector({
selector,
...options
});
return _elementHandle.ElementHandle.fromNullable(result.element);
});
}
async dispatchEvent(selector, type, eventInit, options = {}) {
return this._wrapApiCall(async channel => {
await channel.dispatchEvent({
selector,
type,
eventInit: (0, _jsHandle.serializeArgument)(eventInit),
...options
});
});
}
async $eval(selector, pageFunction, arg) {
(0, _jsHandle.assertMaxArguments)(arguments.length, 3);
return this._wrapApiCall(async channel => {
const result = await channel.evalOnSelector({
selector,
expression: String(pageFunction),
isFunction: typeof pageFunction === 'function',
arg: (0, _jsHandle.serializeArgument)(arg)
});
return (0, _jsHandle.parseResult)(result.value);
});
}
async $$eval(selector, pageFunction, arg) {
(0, _jsHandle.assertMaxArguments)(arguments.length, 3);
return this._wrapApiCall(async channel => {
const result = await channel.evalOnSelectorAll({
selector,
expression: String(pageFunction),
isFunction: typeof pageFunction === 'function',
arg: (0, _jsHandle.serializeArgument)(arg)
});
return (0, _jsHandle.parseResult)(result.value);
});
}
async $$(selector) {
return this._wrapApiCall(async channel => {
const result = await channel.querySelectorAll({
selector
});
return result.elements.map(e => _elementHandle.ElementHandle.from(e));
});
}
async content() {
return this._wrapApiCall(async channel => {
return (await channel.content()).value;
});
}
async setContent(html, options = {}) {
return this._wrapApiCall(async channel => {
const waitUntil = verifyLoadState('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);
await channel.setContent({
html,
...options,
waitUntil
});
});
}
name() {
return this._name || '';
}
url() {
return this._url;
}
parentFrame() {
return this._parentFrame;
}
childFrames() {
return Array.from(this._childFrames);
}
isDetached() {
return this._detached;
}
async addScriptTag(options = {}) {
return this._wrapApiCall(async channel => {
const copy = { ...options
};
if (copy.path) {
copy.content = (await _fs.default.promises.readFile(copy.path)).toString();
copy.content += '//# sourceURL=' + copy.path.replace(/\n/g, '');
}
return _elementHandle.ElementHandle.from((await channel.addScriptTag({ ...copy
})).element);
});
}
async addStyleTag(options = {}) {
return this._wrapApiCall(async channel => {
const copy = { ...options
};
if (copy.path) {
copy.content = (await _fs.default.promises.readFile(copy.path)).toString();
copy.content += '/*# sourceURL=' + copy.path.replace(/\n/g, '') + '*/';
}
return _elementHandle.ElementHandle.from((await channel.addStyleTag({ ...copy
})).element);
});
}
async click(selector, options = {}) {
return this._wrapApiCall(async channel => {
return await channel.click({
selector,
...options
});
});
}
async dblclick(selector, options = {}) {
return this._wrapApiCall(async channel => {
return await channel.dblclick({
selector,
...options
});
});
}
async dragAndDrop(source, target, options = {}) {
return this._wrapApiCall(async channel => {
return await channel.dragAndDrop({
source,
target,
...options
});
});
}
async tap(selector, options = {}) {
return this._wrapApiCall(async channel => {
return await channel.tap({
selector,
...options
});
});
}
async fill(selector, value, options = {}) {
return this._wrapApiCall(async channel => {
return await channel.fill({
selector,
value,
...options
});
});
}
locator(selector) {
return new _locator.Locator(this, selector);
}
async focus(selector, options = {}) {
return this._wrapApiCall(async channel => {
await channel.focus({
selector,
...options
});
});
}
async textContent(selector, options = {}) {
return this._wrapApiCall(async channel => {
const value = (await channel.textContent({
selector,
...options
})).value;
return value === undefined ? null : value;
});
}
async innerText(selector, options = {}) {
return this._wrapApiCall(async channel => {
return (await channel.innerText({
selector,
...options
})).value;
});
}
async innerHTML(selector, options = {}) {
return this._wrapApiCall(async channel => {
return (await channel.innerHTML({
selector,
...options
})).value;
});
}
async getAttribute(selector, name, options = {}) {
return this._wrapApiCall(async channel => {
const value = (await channel.getAttribute({
selector,
name,
...options
})).value;
return value === undefined ? null : value;
});
}
async inputValue(selector, options = {}) {
return this._wrapApiCall(async channel => {
return (await channel.inputValue({
selector,
...options
})).value;
});
}
async isChecked(selector, options = {}) {
return this._wrapApiCall(async channel => {
return (await channel.isChecked({
selector,
...options
})).value;
});
}
async isDisabled(selector, options = {}) {
return this._wrapApiCall(async channel => {
return (await channel.isDisabled({
selector,
...options
})).value;
});
}
async isEditable(selector, options = {}) {
return this._wrapApiCall(async channel => {
return (await channel.isEditable({
selector,
...options
})).value;
});
}
async isEnabled(selector, options = {}) {
return this._wrapApiCall(async channel => {
return (await channel.isEnabled({
selector,
...options
})).value;
});
}
async isHidden(selector, options = {}) {
return this._wrapApiCall(async channel => {
return (await channel.isHidden({
selector,
...options
})).value;
});
}
async isVisible(selector, options = {}) {
return this._wrapApiCall(async channel => {
return (await channel.isVisible({
selector,
...options
})).value;
});
}
async hover(selector, options = {}) {
return this._wrapApiCall(async channel => {
await channel.hover({
selector,
...options
});
});
}
async selectOption(selector, values, options = {}) {
return this._wrapApiCall(async channel => {
return (await channel.selectOption({
selector,
...(0, _elementHandle.convertSelectOptionValues)(values),
...options
})).values;
});
}
async setInputFiles(selector, files, options = {}) {
return this._wrapApiCall(async channel => {
await channel.setInputFiles({
selector,
files: await (0, _elementHandle.convertInputFiles)(files),
...options
});
});
}
async type(selector, text, options = {}) {
return this._wrapApiCall(async channel => {
await channel.type({
selector,
text,
...options
});
});
}
async press(selector, key, options = {}) {
return this._wrapApiCall(async channel => {
await channel.press({
selector,
key,
...options
});
});
}
async check(selector, options = {}) {
return this._wrapApiCall(async channel => {
await channel.check({
selector,
...options
});
});
}
async uncheck(selector, options = {}) {
return this._wrapApiCall(async channel => {
await channel.uncheck({
selector,
...options
});
});
}
async waitForTimeout(timeout) {
return this._wrapApiCall(async channel => {
await new Promise(fulfill => setTimeout(fulfill, timeout));
});
}
async waitForFunction(pageFunction, arg, options = {}) {
return this._wrapApiCall(async channel => {
if (typeof options.polling === 'string') (0, _utils.assert)(options.polling === 'raf', 'Unknown polling option: ' + options.polling);
const result = await channel.waitForFunction({ ...options,
pollingInterval: options.polling === 'raf' ? undefined : options.polling,
expression: String(pageFunction),
isFunction: typeof pageFunction === 'function',
arg: (0, _jsHandle.serializeArgument)(arg)
});
return _jsHandle.JSHandle.from(result.handle);
});
}
async title() {
return this._wrapApiCall(async channel => {
return (await channel.title()).value;
});
}
} |
JavaScript | class hex_Hex extends canvas_Canvas {
constructor() {
super();
this._spacingX = 0;
this._spacingY = 0;
this._hexSize = 0;
}
draw(data, clearBefore) {
let [x, y, ch, fg, bg] = data;
let px = [
(x + 1) * this._spacingX,
y * this._spacingY + this._hexSize
];
if (this._options.transpose) {
px.reverse();
}
if (clearBefore) {
this._ctx.fillStyle = bg;
this._fill(px[0], px[1]);
}
if (!ch) {
return;
}
this._ctx.fillStyle = fg;
let chars = [].concat(ch);
for (let i = 0; i < chars.length; i++) {
this._ctx.fillText(chars[i], px[0], Math.ceil(px[1]));
}
}
computeSize(availWidth, availHeight) {
if (this._options.transpose) {
availWidth += availHeight;
availHeight = availWidth - availHeight;
availWidth -= availHeight;
}
let width = Math.floor(availWidth / this._spacingX) - 1;
let height = Math.floor((availHeight - 2 * this._hexSize) / this._spacingY + 1);
return [width, height];
}
computeFontSize(availWidth, availHeight) {
if (this._options.transpose) {
availWidth += availHeight;
availHeight = availWidth - availHeight;
availWidth -= availHeight;
}
let hexSizeWidth = 2 * availWidth / ((this._options.width + 1) * Math.sqrt(3)) - 1;
let hexSizeHeight = availHeight / (2 + 1.5 * (this._options.height - 1));
let hexSize = Math.min(hexSizeWidth, hexSizeHeight);
// compute char ratio
let oldFont = this._ctx.font;
this._ctx.font = "100px " + this._options.fontFamily;
let width = Math.ceil(this._ctx.measureText("W").width);
this._ctx.font = oldFont;
let ratio = width / 100;
hexSize = Math.floor(hexSize) + 1; // closest larger hexSize
// FIXME char size computation does not respect transposed hexes
let fontSize = 2 * hexSize / (this._options.spacing * (1 + ratio / Math.sqrt(3)));
// closest smaller fontSize
return Math.ceil(fontSize) - 1;
}
_normalizedEventToPosition(x, y) {
let nodeSize;
if (this._options.transpose) {
x += y;
y = x - y;
x -= y;
nodeSize = this._ctx.canvas.width;
}
else {
nodeSize = this._ctx.canvas.height;
}
let size = nodeSize / this._options.height;
y = Math.floor(y / size);
if (Object(util["mod"])(y, 2)) { /* odd row */
x -= this._spacingX;
x = 1 + 2 * Math.floor(x / (2 * this._spacingX));
}
else {
x = 2 * Math.floor(x / (2 * this._spacingX));
}
return [x, y];
}
/**
* Arguments are pixel values. If "transposed" mode is enabled, then these two are already swapped.
*/
_fill(cx, cy) {
let a = this._hexSize;
let b = this._options.border;
const ctx = this._ctx;
ctx.beginPath();
if (this._options.transpose) {
ctx.moveTo(cx - a + b, cy);
ctx.lineTo(cx - a / 2 + b, cy + this._spacingX - b);
ctx.lineTo(cx + a / 2 - b, cy + this._spacingX - b);
ctx.lineTo(cx + a - b, cy);
ctx.lineTo(cx + a / 2 - b, cy - this._spacingX + b);
ctx.lineTo(cx - a / 2 + b, cy - this._spacingX + b);
ctx.lineTo(cx - a + b, cy);
}
else {
ctx.moveTo(cx, cy - a + b);
ctx.lineTo(cx + this._spacingX - b, cy - a / 2 + b);
ctx.lineTo(cx + this._spacingX - b, cy + a / 2 - b);
ctx.lineTo(cx, cy + a - b);
ctx.lineTo(cx - this._spacingX + b, cy + a / 2 - b);
ctx.lineTo(cx - this._spacingX + b, cy - a / 2 + b);
ctx.lineTo(cx, cy - a + b);
}
ctx.fill();
}
_updateSize() {
const opts = this._options;
const charWidth = Math.ceil(this._ctx.measureText("W").width);
this._hexSize = Math.floor(opts.spacing * (opts.fontSize + charWidth / Math.sqrt(3)) / 2);
this._spacingX = this._hexSize * Math.sqrt(3) / 2;
this._spacingY = this._hexSize * 1.5;
let xprop;
let yprop;
if (opts.transpose) {
xprop = "height";
yprop = "width";
}
else {
xprop = "width";
yprop = "height";
}
this._ctx.canvas[xprop] = Math.ceil((opts.width + 1) * this._spacingX);
this._ctx.canvas[yprop] = Math.ceil((opts.height - 1) * this._spacingY + 2 * this._hexSize);
}
} |
JavaScript | class rect_Rect extends canvas_Canvas {
constructor() {
super();
this._spacingX = 0;
this._spacingY = 0;
this._canvasCache = {};
}
setOptions(options) {
super.setOptions(options);
this._canvasCache = {};
}
draw(data, clearBefore) {
if (rect_Rect.cache) {
this._drawWithCache(data);
}
else {
this._drawNoCache(data, clearBefore);
}
}
_drawWithCache(data) {
let [x, y, ch, fg, bg] = data;
let hash = "" + ch + fg + bg;
let canvas;
if (hash in this._canvasCache) {
canvas = this._canvasCache[hash];
}
else {
let b = this._options.border;
canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = this._spacingX;
canvas.height = this._spacingY;
ctx.fillStyle = bg;
ctx.fillRect(b, b, canvas.width - b, canvas.height - b);
if (ch) {
ctx.fillStyle = fg;
ctx.font = this._ctx.font;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
let chars = [].concat(ch);
for (let i = 0; i < chars.length; i++) {
ctx.fillText(chars[i], this._spacingX / 2, Math.ceil(this._spacingY / 2));
}
}
this._canvasCache[hash] = canvas;
}
this._ctx.drawImage(canvas, x * this._spacingX, y * this._spacingY);
}
_drawNoCache(data, clearBefore) {
let [x, y, ch, fg, bg] = data;
if (clearBefore) {
let b = this._options.border;
this._ctx.fillStyle = bg;
this._ctx.fillRect(x * this._spacingX + b, y * this._spacingY + b, this._spacingX - b, this._spacingY - b);
}
if (!ch) {
return;
}
this._ctx.fillStyle = fg;
let chars = [].concat(ch);
for (let i = 0; i < chars.length; i++) {
this._ctx.fillText(chars[i], (x + 0.5) * this._spacingX, Math.ceil((y + 0.5) * this._spacingY));
}
}
computeSize(availWidth, availHeight) {
let width = Math.floor(availWidth / this._spacingX);
let height = Math.floor(availHeight / this._spacingY);
return [width, height];
}
computeFontSize(availWidth, availHeight) {
let boxWidth = Math.floor(availWidth / this._options.width);
let boxHeight = Math.floor(availHeight / this._options.height);
/* compute char ratio */
let oldFont = this._ctx.font;
this._ctx.font = "100px " + this._options.fontFamily;
let width = Math.ceil(this._ctx.measureText("W").width);
this._ctx.font = oldFont;
let ratio = width / 100;
let widthFraction = ratio * boxHeight / boxWidth;
if (widthFraction > 1) { /* too wide with current aspect ratio */
boxHeight = Math.floor(boxHeight / widthFraction);
}
return Math.floor(boxHeight / this._options.spacing);
}
_normalizedEventToPosition(x, y) {
return [Math.floor(x / this._spacingX), Math.floor(y / this._spacingY)];
}
_updateSize() {
const opts = this._options;
const charWidth = Math.ceil(this._ctx.measureText("W").width);
this._spacingX = Math.ceil(opts.spacing * charWidth);
this._spacingY = Math.ceil(opts.spacing * opts.fontSize);
if (opts.forceSquareRatio) {
this._spacingX = this._spacingY = Math.max(this._spacingX, this._spacingY);
}
this._ctx.canvas.width = opts.width * this._spacingX;
this._ctx.canvas.height = opts.height * this._spacingY;
}
} |
JavaScript | class tile_Tile extends canvas_Canvas {
constructor() {
super();
this._colorCanvas = document.createElement("canvas");
}
draw(data, clearBefore) {
let [x, y, ch, fg, bg] = data;
let tileWidth = this._options.tileWidth;
let tileHeight = this._options.tileHeight;
if (clearBefore) {
if (this._options.tileColorize) {
this._ctx.clearRect(x * tileWidth, y * tileHeight, tileWidth, tileHeight);
}
else {
this._ctx.fillStyle = bg;
this._ctx.fillRect(x * tileWidth, y * tileHeight, tileWidth, tileHeight);
}
}
if (!ch) {
return;
}
let chars = [].concat(ch);
let fgs = [].concat(fg);
let bgs = [].concat(bg);
for (let i = 0; i < chars.length; i++) {
let tile = this._options.tileMap[chars[i]];
if (!tile) {
throw new Error(`Char "${chars[i]}" not found in tileMap`);
}
if (this._options.tileColorize) { // apply colorization
let canvas = this._colorCanvas;
let context = canvas.getContext("2d");
context.globalCompositeOperation = "source-over";
context.clearRect(0, 0, tileWidth, tileHeight);
let fg = fgs[i];
let bg = bgs[i];
context.drawImage(this._options.tileSet, tile[0], tile[1], tileWidth, tileHeight, 0, 0, tileWidth, tileHeight);
if (fg != "transparent") {
context.fillStyle = fg;
context.globalCompositeOperation = "source-atop";
context.fillRect(0, 0, tileWidth, tileHeight);
}
if (bg != "transparent") {
context.fillStyle = bg;
context.globalCompositeOperation = "destination-over";
context.fillRect(0, 0, tileWidth, tileHeight);
}
this._ctx.drawImage(canvas, x * tileWidth, y * tileHeight, tileWidth, tileHeight);
}
else { // no colorizing, easy
this._ctx.drawImage(this._options.tileSet, tile[0], tile[1], tileWidth, tileHeight, x * tileWidth, y * tileHeight, tileWidth, tileHeight);
}
}
}
computeSize(availWidth, availHeight) {
let width = Math.floor(availWidth / this._options.tileWidth);
let height = Math.floor(availHeight / this._options.tileHeight);
return [width, height];
}
computeFontSize() {
throw new Error("Tile backend does not understand font size");
}
_normalizedEventToPosition(x, y) {
return [Math.floor(x / this._options.tileWidth), Math.floor(y / this._options.tileHeight)];
}
_updateSize() {
const opts = this._options;
this._ctx.canvas.width = opts.width * opts.tileWidth;
this._ctx.canvas.height = opts.height * opts.tileHeight;
this._colorCanvas.width = opts.tileWidth;
this._colorCanvas.height = opts.tileHeight;
}
} |
JavaScript | class display_Display {
constructor(options = {}) {
this._data = {};
this._dirty = false; // false = nothing, true = all, object = dirty cells
this._options = {};
options = Object.assign({}, DEFAULT_OPTIONS, options);
this.setOptions(options);
this.DEBUG = this.DEBUG.bind(this);
this._tick = this._tick.bind(this);
this._backend.schedule(this._tick);
}
/**
* Debug helper, ideal as a map generator callback. Always bound to this.
* @param {int} x
* @param {int} y
* @param {int} what
*/
DEBUG(x, y, what) {
let colors = [this._options.bg, this._options.fg];
this.draw(x, y, null, null, colors[what % colors.length]);
}
/**
* Clear the whole display (cover it with background color)
*/
clear() {
this._data = {};
this._dirty = true;
}
/**
* @see ROT.Display
*/
setOptions(options) {
Object.assign(this._options, options);
if (options.width || options.height || options.fontSize || options.fontFamily || options.spacing || options.layout) {
if (options.layout) {
let ctor = BACKENDS[options.layout];
this._backend = new ctor();
}
this._backend.setOptions(this._options);
this._dirty = true;
}
return this;
}
/**
* Returns currently set options
*/
getOptions() { return this._options; }
/**
* Returns the DOM node of this display
*/
getContainer() { return this._backend.getContainer(); }
/**
* Compute the maximum width/height to fit into a set of given constraints
* @param {int} availWidth Maximum allowed pixel width
* @param {int} availHeight Maximum allowed pixel height
* @returns {int[2]} cellWidth,cellHeight
*/
computeSize(availWidth, availHeight) {
return this._backend.computeSize(availWidth, availHeight);
}
/**
* Compute the maximum font size to fit into a set of given constraints
* @param {int} availWidth Maximum allowed pixel width
* @param {int} availHeight Maximum allowed pixel height
* @returns {int} fontSize
*/
computeFontSize(availWidth, availHeight) {
return this._backend.computeFontSize(availWidth, availHeight);
}
computeTileSize(availWidth, availHeight) {
let width = Math.floor(availWidth / this._options.width);
let height = Math.floor(availHeight / this._options.height);
return [width, height];
}
/**
* Convert a DOM event (mouse or touch) to map coordinates. Uses first touch for multi-touch.
* @param {Event} e event
* @returns {int[2]} -1 for values outside of the canvas
*/
eventToPosition(e) {
let x, y;
if ("touches" in e) {
x = e.touches[0].clientX;
y = e.touches[0].clientY;
}
else {
x = e.clientX;
y = e.clientY;
}
return this._backend.eventToPosition(x, y);
}
/**
* @param {int} x
* @param {int} y
* @param {string || string[]} ch One or more chars (will be overlapping themselves)
* @param {string} [fg] foreground color
* @param {string} [bg] background color
*/
draw(x, y, ch, fg, bg) {
if (!fg) {
fg = this._options.fg;
}
if (!bg) {
bg = this._options.bg;
}
let key = `${x},${y}`;
this._data[key] = [x, y, ch, fg, bg];
if (this._dirty === true) {
return;
} // will already redraw everything
if (!this._dirty) {
this._dirty = {};
} // first!
this._dirty[key] = true;
}
/**
* Draws a text at given position. Optionally wraps at a maximum length. Currently does not work with hex layout.
* @param {int} x
* @param {int} y
* @param {string} text May contain color/background format specifiers, %c{name}/%b{name}, both optional. %c{}/%b{} resets to default.
* @param {int} [maxWidth] wrap at what width?
* @returns {int} lines drawn
*/
drawText(x, y, text, maxWidth) {
let fg = null;
let bg = null;
let cx = x;
let cy = y;
let lines = 1;
if (!maxWidth) {
maxWidth = this._options.width - x;
}
let tokens = tokenize(text, maxWidth);
while (tokens.length) { // interpret tokenized opcode stream
let token = tokens.shift();
switch (token.type) {
case TYPE_TEXT:
let isSpace = false, isPrevSpace = false, isFullWidth = false, isPrevFullWidth = false;
for (let i = 0; i < token.value.length; i++) {
let cc = token.value.charCodeAt(i);
let c = token.value.charAt(i);
// Assign to `true` when the current char is full-width.
isFullWidth = (cc > 0xff00 && cc < 0xff61) || (cc > 0xffdc && cc < 0xffe8) || cc > 0xffee;
// Current char is space, whatever full-width or half-width both are OK.
isSpace = (c.charCodeAt(0) == 0x20 || c.charCodeAt(0) == 0x3000);
// The previous char is full-width and
// current char is nether half-width nor a space.
if (isPrevFullWidth && !isFullWidth && !isSpace) {
cx++;
} // add an extra position
// The current char is full-width and
// the previous char is not a space.
if (isFullWidth && !isPrevSpace) {
cx++;
} // add an extra position
this.draw(cx++, cy, c, fg, bg);
isPrevSpace = isSpace;
isPrevFullWidth = isFullWidth;
}
break;
case TYPE_FG:
fg = token.value || null;
break;
case TYPE_BG:
bg = token.value || null;
break;
case TYPE_NEWLINE:
cx = x;
cy++;
lines++;
break;
}
}
return lines;
}
/**
* Timer tick: update dirty parts
*/
_tick() {
this._backend.schedule(this._tick);
if (!this._dirty) {
return;
}
if (this._dirty === true) { // draw all
this._backend.clear();
for (let id in this._data) {
this._draw(id, false);
} // redraw cached data
}
else { // draw only dirty
for (let key in this._dirty) {
this._draw(key, true);
}
}
this._dirty = false;
}
/**
* @param {string} key What to draw
* @param {bool} clearBefore Is it necessary to clean before?
*/
_draw(key, clearBefore) {
let data = this._data[key];
if (data[4] != this._options.bg) {
clearBefore = true;
}
this._backend.draw(data, clearBefore);
}
} |
JavaScript | class stringgenerator_StringGenerator {
constructor(options) {
this._options = {
words: false,
order: 3,
prior: 0.001
};
Object.assign(this._options, options);
this._boundary = String.fromCharCode(0);
this._suffix = this._boundary;
this._prefix = [];
for (let i = 0; i < this._options.order; i++) {
this._prefix.push(this._boundary);
}
this._priorValues = {};
this._priorValues[this._boundary] = this._options.prior;
this._data = {};
}
/**
* Remove all learning data
*/
clear() {
this._data = {};
this._priorValues = {};
}
/**
* @returns {string} Generated string
*/
generate() {
let result = [this._sample(this._prefix)];
while (result[result.length - 1] != this._boundary) {
result.push(this._sample(result));
}
return this._join(result.slice(0, -1));
}
/**
* Observe (learn) a string from a training set
*/
observe(string) {
let tokens = this._split(string);
for (let i = 0; i < tokens.length; i++) {
this._priorValues[tokens[i]] = this._options.prior;
}
tokens = this._prefix.concat(tokens).concat(this._suffix); /* add boundary symbols */
for (let i = this._options.order; i < tokens.length; i++) {
let context = tokens.slice(i - this._options.order, i);
let event = tokens[i];
for (let j = 0; j < context.length; j++) {
let subcontext = context.slice(j);
this._observeEvent(subcontext, event);
}
}
}
getStats() {
let parts = [];
let priorCount = Object.keys(this._priorValues).length;
priorCount--; // boundary
parts.push("distinct samples: " + priorCount);
let dataCount = Object.keys(this._data).length;
let eventCount = 0;
for (let p in this._data) {
eventCount += Object.keys(this._data[p]).length;
}
parts.push("dictionary size (contexts): " + dataCount);
parts.push("dictionary size (events): " + eventCount);
return parts.join(", ");
}
/**
* @param {string}
* @returns {string[]}
*/
_split(str) {
return str.split(this._options.words ? /\s+/ : "");
}
/**
* @param {string[]}
* @returns {string}
*/
_join(arr) {
return arr.join(this._options.words ? " " : "");
}
/**
* @param {string[]} context
* @param {string} event
*/
_observeEvent(context, event) {
let key = this._join(context);
if (!(key in this._data)) {
this._data[key] = {};
}
let data = this._data[key];
if (!(event in data)) {
data[event] = 0;
}
data[event]++;
}
/**
* @param {string[]}
* @returns {string}
*/
_sample(context) {
context = this._backoff(context);
let key = this._join(context);
let data = this._data[key];
let available = {};
if (this._options.prior) {
for (let event in this._priorValues) {
available[event] = this._priorValues[event];
}
for (let event in data) {
available[event] += data[event];
}
}
else {
available = data;
}
return rng["a" /* default */].getWeightedValue(available);
}
/**
* @param {string[]}
* @returns {string[]}
*/
_backoff(context) {
if (context.length > this._options.order) {
context = context.slice(-this._options.order);
}
else if (context.length < this._options.order) {
context = this._prefix.slice(0, this._options.order - context.length).concat(context);
}
while (!(this._join(context) in this._data) && context.length > 0) {
context = context.slice(1);
}
return context;
}
} |
JavaScript | class simple_Simple extends scheduler_Scheduler {
add(item, repeat) {
this._queue.add(item, 0);
return super.add(item, repeat);
}
next() {
if (this._current && this._repeat.indexOf(this._current) != -1) {
this._queue.add(this._current, 0);
}
return super.next();
}
} |
JavaScript | class speed_Speed extends scheduler_Scheduler {
/**
* @param {object} item anything with "getSpeed" method
* @param {bool} repeat
* @param {number} [time=1/item.getSpeed()]
* @see ROT.Scheduler#add
*/
add(item, repeat, time) {
this._queue.add(item, time !== undefined ? time : 1 / item.getSpeed());
return super.add(item, repeat);
}
/**
* @see ROT.Scheduler#next
*/
next() {
if (this._current && this._repeat.indexOf(this._current) != -1) {
this._queue.add(this._current, 1 / this._current.getSpeed());
}
return super.next();
}
} |
JavaScript | class action_Action extends scheduler_Scheduler {
constructor() {
super();
this._defaultDuration = 1; /* for newly added */
this._duration = this._defaultDuration; /* for this._current */
}
/**
* @param {object} item
* @param {bool} repeat
* @param {number} [time=1]
* @see ROT.Scheduler#add
*/
add(item, repeat, time) {
this._queue.add(item, time || this._defaultDuration);
return super.add(item, repeat);
}
clear() {
this._duration = this._defaultDuration;
return super.clear();
}
remove(item) {
if (item == this._current) {
this._duration = this._defaultDuration;
}
return super.remove(item);
}
/**
* @see ROT.Scheduler#next
*/
next() {
if (this._current && this._repeat.indexOf(this._current) != -1) {
this._queue.add(this._current, this._duration || this._defaultDuration);
this._duration = this._defaultDuration;
}
return super.next();
}
/**
* Set duration for the active item
*/
setDuration(time) {
if (this._current) {
this._duration = time;
}
return this;
}
} |
JavaScript | class discrete_shadowcasting_DiscreteShadowcasting extends fov_FOV {
compute(x, y, R, callback) {
/* this place is always visible */
callback(x, y, 0, 1);
/* standing in a dark place. FIXME is this a good idea? */
if (!this._lightPasses(x, y)) {
return;
}
/* start and end angles */
let DATA = [];
let A, B, cx, cy, blocks;
/* analyze surrounding cells in concentric rings, starting from the center */
for (let r = 1; r <= R; r++) {
let neighbors = this._getCircle(x, y, r);
let angle = 360 / neighbors.length;
for (let i = 0; i < neighbors.length; i++) {
cx = neighbors[i][0];
cy = neighbors[i][1];
A = angle * (i - 0.5);
B = A + angle;
blocks = !this._lightPasses(cx, cy);
if (this._visibleCoords(Math.floor(A), Math.ceil(B), blocks, DATA)) {
callback(cx, cy, r, 1);
}
if (DATA.length == 2 && DATA[0] == 0 && DATA[1] == 360) {
return;
} /* cutoff? */
} /* for all cells in this ring */
} /* for all rings */
}
/**
* @param {int} A start angle
* @param {int} B end angle
* @param {bool} blocks Does current cell block visibility?
* @param {int[][]} DATA shadowed angle pairs
*/
_visibleCoords(A, B, blocks, DATA) {
if (A < 0) {
let v1 = this._visibleCoords(0, B, blocks, DATA);
let v2 = this._visibleCoords(360 + A, 360, blocks, DATA);
return v1 || v2;
}
let index = 0;
while (index < DATA.length && DATA[index] < A) {
index++;
}
if (index == DATA.length) { /* completely new shadow */
if (blocks) {
DATA.push(A, B);
}
return true;
}
let count = 0;
if (index % 2) { /* this shadow starts in an existing shadow, or within its ending boundary */
while (index < DATA.length && DATA[index] < B) {
index++;
count++;
}
if (count == 0) {
return false;
}
if (blocks) {
if (count % 2) {
DATA.splice(index - count, count, B);
}
else {
DATA.splice(index - count, count);
}
}
return true;
}
else { /* this shadow starts outside an existing shadow, or within a starting boundary */
while (index < DATA.length && DATA[index] < B) {
index++;
count++;
}
/* visible when outside an existing shadow, or when overlapping */
if (A == DATA[index - count] && count == 1) {
return false;
}
if (blocks) {
if (count % 2) {
DATA.splice(index - count, count, A);
}
else {
DATA.splice(index - count, count, A, B);
}
}
return true;
}
}
} |
JavaScript | class precise_shadowcasting_PreciseShadowcasting extends fov_FOV {
compute(x, y, R, callback) {
/* this place is always visible */
callback(x, y, 0, 1);
/* standing in a dark place. FIXME is this a good idea? */
if (!this._lightPasses(x, y)) {
return;
}
/* list of all shadows */
let SHADOWS = [];
let cx, cy, blocks, A1, A2, visibility;
/* analyze surrounding cells in concentric rings, starting from the center */
for (let r = 1; r <= R; r++) {
let neighbors = this._getCircle(x, y, r);
let neighborCount = neighbors.length;
for (let i = 0; i < neighborCount; i++) {
cx = neighbors[i][0];
cy = neighbors[i][1];
/* shift half-an-angle backwards to maintain consistency of 0-th cells */
A1 = [i ? 2 * i - 1 : 2 * neighborCount - 1, 2 * neighborCount];
A2 = [2 * i + 1, 2 * neighborCount];
blocks = !this._lightPasses(cx, cy);
visibility = this._checkVisibility(A1, A2, blocks, SHADOWS);
if (visibility) {
callback(cx, cy, r, visibility);
}
if (SHADOWS.length == 2 && SHADOWS[0][0] == 0 && SHADOWS[1][0] == SHADOWS[1][1]) {
return;
} /* cutoff? */
} /* for all cells in this ring */
} /* for all rings */
}
/**
* @param {int[2]} A1 arc start
* @param {int[2]} A2 arc end
* @param {bool} blocks Does current arc block visibility?
* @param {int[][]} SHADOWS list of active shadows
*/
_checkVisibility(A1, A2, blocks, SHADOWS) {
if (A1[0] > A2[0]) { /* split into two sub-arcs */
let v1 = this._checkVisibility(A1, [A1[1], A1[1]], blocks, SHADOWS);
let v2 = this._checkVisibility([0, 1], A2, blocks, SHADOWS);
return (v1 + v2) / 2;
}
/* index1: first shadow >= A1 */
let index1 = 0, edge1 = false;
while (index1 < SHADOWS.length) {
let old = SHADOWS[index1];
let diff = old[0] * A1[1] - A1[0] * old[1];
if (diff >= 0) { /* old >= A1 */
if (diff == 0 && !(index1 % 2)) {
edge1 = true;
}
break;
}
index1++;
}
/* index2: last shadow <= A2 */
let index2 = SHADOWS.length, edge2 = false;
while (index2--) {
let old = SHADOWS[index2];
let diff = A2[0] * old[1] - old[0] * A2[1];
if (diff >= 0) { /* old <= A2 */
if (diff == 0 && (index2 % 2)) {
edge2 = true;
}
break;
}
}
let visible = true;
if (index1 == index2 && (edge1 || edge2)) { /* subset of existing shadow, one of the edges match */
visible = false;
}
else if (edge1 && edge2 && index1 + 1 == index2 && (index2 % 2)) { /* completely equivalent with existing shadow */
visible = false;
}
else if (index1 > index2 && (index1 % 2)) { /* subset of existing shadow, not touching */
visible = false;
}
if (!visible) {
return 0;
} /* fast case: not visible */
let visibleLength;
/* compute the length of visible arc, adjust list of shadows (if blocking) */
let remove = index2 - index1 + 1;
if (remove % 2) {
if (index1 % 2) { /* first edge within existing shadow, second outside */
let P = SHADOWS[index1];
visibleLength = (A2[0] * P[1] - P[0] * A2[1]) / (P[1] * A2[1]);
if (blocks) {
SHADOWS.splice(index1, remove, A2);
}
}
else { /* second edge within existing shadow, first outside */
let P = SHADOWS[index2];
visibleLength = (P[0] * A1[1] - A1[0] * P[1]) / (A1[1] * P[1]);
if (blocks) {
SHADOWS.splice(index1, remove, A1);
}
}
}
else {
if (index1 % 2) { /* both edges within existing shadows */
let P1 = SHADOWS[index1];
let P2 = SHADOWS[index2];
visibleLength = (P2[0] * P1[1] - P1[0] * P2[1]) / (P1[1] * P2[1]);
if (blocks) {
SHADOWS.splice(index1, remove);
}
}
else { /* both edges outside existing shadows */
if (blocks) {
SHADOWS.splice(index1, remove, A1, A2);
}
return 1; /* whole arc visible! */
}
}
let arcLength = (A2[0] * A1[1] - A1[0] * A2[1]) / (A1[1] * A2[1]);
return visibleLength / arcLength;
}
} |
JavaScript | class arena_Arena extends map_Map {
create(callback) {
let w = this._width - 1;
let h = this._height - 1;
for (let i = 0; i <= w; i++) {
for (let j = 0; j <= h; j++) {
let empty = (i && j && i < w && j < h);
callback(i, j, empty ? 0 : 1);
}
}
return this;
}
} |
JavaScript | class dungeon_Dungeon extends map_Map {
constructor(width, height) {
super(width, height);
this._rooms = [];
this._corridors = [];
}
/**
* Get all generated rooms
* @returns {ROT.Map.Feature.Room[]}
*/
getRooms() { return this._rooms; }
/**
* Get all generated corridors
* @returns {ROT.Map.Feature.Corridor[]}
*/
getCorridors() { return this._corridors; }
} |
JavaScript | class uniform_Uniform extends dungeon_Dungeon {
constructor(width, height, options) {
super(width, height);
this._options = {
roomWidth: [3, 9],
roomHeight: [3, 5],
roomDugPercentage: 0.1,
timeLimit: 1000 /* we stop after this much time has passed (msec) */
};
Object.assign(this._options, options);
this._map = [];
this._dug = 0;
this._roomAttempts = 20; /* new room is created N-times until is considered as impossible to generate */
this._corridorAttempts = 20; /* corridors are tried N-times until the level is considered as impossible to connect */
this._connected = []; /* list of already connected rooms */
this._unconnected = []; /* list of remaining unconnected rooms */
this._digCallback = this._digCallback.bind(this);
this._canBeDugCallback = this._canBeDugCallback.bind(this);
this._isWallCallback = this._isWallCallback.bind(this);
}
/**
* Create a map. If the time limit has been hit, returns null.
* @see ROT.Map#create
*/
create(callback) {
let t1 = Date.now();
while (1) {
let t2 = Date.now();
if (t2 - t1 > this._options.timeLimit) {
return null;
} /* time limit! */
this._map = this._fillMap(1);
this._dug = 0;
this._rooms = [];
this._unconnected = [];
this._generateRooms();
if (this._rooms.length < 2) {
continue;
}
if (this._generateCorridors()) {
break;
}
}
if (callback) {
for (let i = 0; i < this._width; i++) {
for (let j = 0; j < this._height; j++) {
callback(i, j, this._map[i][j]);
}
}
}
return this;
}
/**
* Generates a suitable amount of rooms
*/
_generateRooms() {
let w = this._width - 2;
let h = this._height - 2;
let room;
do {
room = this._generateRoom();
if (this._dug / (w * h) > this._options.roomDugPercentage) {
break;
} /* achieved requested amount of free space */
} while (room);
/* either enough rooms, or not able to generate more of them :) */
}
/**
* Try to generate one room
*/
_generateRoom() {
let count = 0;
while (count < this._roomAttempts) {
count++;
let room = features_Room.createRandom(this._width, this._height, this._options);
if (!room.isValid(this._isWallCallback, this._canBeDugCallback)) {
continue;
}
room.create(this._digCallback);
this._rooms.push(room);
return room;
}
/* no room was generated in a given number of attempts */
return null;
}
/**
* Generates connectors beween rooms
* @returns {bool} success Was this attempt successfull?
*/
_generateCorridors() {
let cnt = 0;
while (cnt < this._corridorAttempts) {
cnt++;
this._corridors = [];
/* dig rooms into a clear map */
this._map = this._fillMap(1);
for (let i = 0; i < this._rooms.length; i++) {
let room = this._rooms[i];
room.clearDoors();
room.create(this._digCallback);
}
this._unconnected = rng["a" /* default */].shuffle(this._rooms.slice());
this._connected = [];
if (this._unconnected.length) {
this._connected.push(this._unconnected.pop());
} /* first one is always connected */
while (1) {
/* 1. pick random connected room */
let connected = rng["a" /* default */].getItem(this._connected);
if (!connected) {
break;
}
/* 2. find closest unconnected */
let room1 = this._closestRoom(this._unconnected, connected);
if (!room1) {
break;
}
/* 3. connect it to closest connected */
let room2 = this._closestRoom(this._connected, room1);
if (!room2) {
break;
}
let ok = this._connectRooms(room1, room2);
if (!ok) {
break;
} /* stop connecting, re-shuffle */
if (!this._unconnected.length) {
return true;
} /* done; no rooms remain */
}
}
return false;
}
;
/**
* For a given room, find the closest one from the list
*/
_closestRoom(rooms, room) {
let dist = Infinity;
let center = room.getCenter();
let result = null;
for (let i = 0; i < rooms.length; i++) {
let r = rooms[i];
let c = r.getCenter();
let dx = c[0] - center[0];
let dy = c[1] - center[1];
let d = dx * dx + dy * dy;
if (d < dist) {
dist = d;
result = r;
}
}
return result;
}
_connectRooms(room1, room2) {
/*
room1.debug();
room2.debug();
*/
let center1 = room1.getCenter();
let center2 = room2.getCenter();
let diffX = center2[0] - center1[0];
let diffY = center2[1] - center1[1];
let start;
let end;
let dirIndex1, dirIndex2, min, max, index;
if (Math.abs(diffX) < Math.abs(diffY)) { /* first try connecting north-south walls */
dirIndex1 = (diffY > 0 ? 2 : 0);
dirIndex2 = (dirIndex1 + 2) % 4;
min = room2.getLeft();
max = room2.getRight();
index = 0;
}
else { /* first try connecting east-west walls */
dirIndex1 = (diffX > 0 ? 1 : 3);
dirIndex2 = (dirIndex1 + 2) % 4;
min = room2.getTop();
max = room2.getBottom();
index = 1;
}
start = this._placeInWall(room1, dirIndex1); /* corridor will start here */
if (!start) {
return false;
}
if (start[index] >= min && start[index] <= max) { /* possible to connect with straight line (I-like) */
end = start.slice();
let value = 0;
switch (dirIndex2) {
case 0:
value = room2.getTop() - 1;
break;
case 1:
value = room2.getRight() + 1;
break;
case 2:
value = room2.getBottom() + 1;
break;
case 3:
value = room2.getLeft() - 1;
break;
}
end[(index + 1) % 2] = value;
this._digLine([start, end]);
}
else if (start[index] < min - 1 || start[index] > max + 1) { /* need to switch target wall (L-like) */
let diff = start[index] - center2[index];
let rotation = 0;
switch (dirIndex2) {
case 0:
case 1:
rotation = (diff < 0 ? 3 : 1);
break;
case 2:
case 3:
rotation = (diff < 0 ? 1 : 3);
break;
}
dirIndex2 = (dirIndex2 + rotation) % 4;
end = this._placeInWall(room2, dirIndex2);
if (!end) {
return false;
}
let mid = [0, 0];
mid[index] = start[index];
let index2 = (index + 1) % 2;
mid[index2] = end[index2];
this._digLine([start, mid, end]);
}
else { /* use current wall pair, but adjust the line in the middle (S-like) */
let index2 = (index + 1) % 2;
end = this._placeInWall(room2, dirIndex2);
if (!end) {
return false;
}
let mid = Math.round((end[index2] + start[index2]) / 2);
let mid1 = [0, 0];
let mid2 = [0, 0];
mid1[index] = start[index];
mid1[index2] = mid;
mid2[index] = end[index];
mid2[index2] = mid;
this._digLine([start, mid1, mid2, end]);
}
room1.addDoor(start[0], start[1]);
room2.addDoor(end[0], end[1]);
index = this._unconnected.indexOf(room1);
if (index != -1) {
this._unconnected.splice(index, 1);
this._connected.push(room1);
}
index = this._unconnected.indexOf(room2);
if (index != -1) {
this._unconnected.splice(index, 1);
this._connected.push(room2);
}
return true;
}
_placeInWall(room, dirIndex) {
let start = [0, 0];
let dir = [0, 0];
let length = 0;
switch (dirIndex) {
case 0:
dir = [1, 0];
start = [room.getLeft(), room.getTop() - 1];
length = room.getRight() - room.getLeft() + 1;
break;
case 1:
dir = [0, 1];
start = [room.getRight() + 1, room.getTop()];
length = room.getBottom() - room.getTop() + 1;
break;
case 2:
dir = [1, 0];
start = [room.getLeft(), room.getBottom() + 1];
length = room.getRight() - room.getLeft() + 1;
break;
case 3:
dir = [0, 1];
start = [room.getLeft() - 1, room.getTop()];
length = room.getBottom() - room.getTop() + 1;
break;
}
let avail = [];
let lastBadIndex = -2;
for (let i = 0; i < length; i++) {
let x = start[0] + i * dir[0];
let y = start[1] + i * dir[1];
avail.push(null);
let isWall = (this._map[x][y] == 1);
if (isWall) {
if (lastBadIndex != i - 1) {
avail[i] = [x, y];
}
}
else {
lastBadIndex = i;
if (i) {
avail[i - 1] = null;
}
}
}
for (let i = avail.length - 1; i >= 0; i--) {
if (!avail[i]) {
avail.splice(i, 1);
}
}
return (avail.length ? rng["a" /* default */].getItem(avail) : null);
}
/**
* Dig a polyline.
*/
_digLine(points) {
for (let i = 1; i < points.length; i++) {
let start = points[i - 1];
let end = points[i];
let corridor = new features_Corridor(start[0], start[1], end[0], end[1]);
corridor.create(this._digCallback);
this._corridors.push(corridor);
}
}
_digCallback(x, y, value) {
this._map[x][y] = value;
if (value == 0) {
this._dug++;
}
}
_isWallCallback(x, y) {
if (x < 0 || y < 0 || x >= this._width || y >= this._height) {
return false;
}
return (this._map[x][y] == 1);
}
_canBeDugCallback(x, y) {
if (x < 1 || y < 1 || x + 1 >= this._width || y + 1 >= this._height) {
return false;
}
return (this._map[x][y] == 1);
}
} |
JavaScript | class digger_Digger extends dungeon_Dungeon {
constructor(width, height, options = {}) {
super(width, height);
this._options = Object.assign({
roomWidth: [3, 9],
roomHeight: [3, 5],
corridorLength: [3, 10],
dugPercentage: 0.2,
timeLimit: 1000 /* we stop after this much time has passed (msec) */
}, options);
this._features = {
"room": 4,
"corridor": 4
};
this._map = [];
this._featureAttempts = 20; /* how many times do we try to create a feature on a suitable wall */
this._walls = {}; /* these are available for digging */
this._dug = 0;
this._digCallback = this._digCallback.bind(this);
this._canBeDugCallback = this._canBeDugCallback.bind(this);
this._isWallCallback = this._isWallCallback.bind(this);
this._priorityWallCallback = this._priorityWallCallback.bind(this);
}
create(callback) {
this._rooms = [];
this._corridors = [];
this._map = this._fillMap(1);
this._walls = {};
this._dug = 0;
let area = (this._width - 2) * (this._height - 2);
this._firstRoom();
let t1 = Date.now();
let priorityWalls;
do {
priorityWalls = 0;
let t2 = Date.now();
if (t2 - t1 > this._options.timeLimit) {
break;
}
/* find a good wall */
let wall = this._findWall();
if (!wall) {
break;
} /* no more walls */
let parts = wall.split(",");
let x = parseInt(parts[0]);
let y = parseInt(parts[1]);
let dir = this._getDiggingDirection(x, y);
if (!dir) {
continue;
} /* this wall is not suitable */
// console.log("wall", x, y);
/* try adding a feature */
let featureAttempts = 0;
do {
featureAttempts++;
if (this._tryFeature(x, y, dir[0], dir[1])) { /* feature added */
//if (this._rooms.length + this._corridors.length == 2) { this._rooms[0].addDoor(x, y); } /* first room oficially has doors */
this._removeSurroundingWalls(x, y);
this._removeSurroundingWalls(x - dir[0], y - dir[1]);
break;
}
} while (featureAttempts < this._featureAttempts);
for (let id in this._walls) {
if (this._walls[id] > 1) {
priorityWalls++;
}
}
} while (this._dug / area < this._options.dugPercentage || priorityWalls); /* fixme number of priority walls */
this._addDoors();
if (callback) {
for (let i = 0; i < this._width; i++) {
for (let j = 0; j < this._height; j++) {
callback(i, j, this._map[i][j]);
}
}
}
this._walls = {};
this._map = [];
return this;
}
_digCallback(x, y, value) {
if (value == 0 || value == 2) { /* empty */
this._map[x][y] = 0;
this._dug++;
}
else { /* wall */
this._walls[x + "," + y] = 1;
}
}
_isWallCallback(x, y) {
if (x < 0 || y < 0 || x >= this._width || y >= this._height) {
return false;
}
return (this._map[x][y] == 1);
}
_canBeDugCallback(x, y) {
if (x < 1 || y < 1 || x + 1 >= this._width || y + 1 >= this._height) {
return false;
}
return (this._map[x][y] == 1);
}
_priorityWallCallback(x, y) { this._walls[x + "," + y] = 2; }
;
_firstRoom() {
let cx = Math.floor(this._width / 2);
let cy = Math.floor(this._height / 2);
let room = features_Room.createRandomCenter(cx, cy, this._options);
this._rooms.push(room);
room.create(this._digCallback);
}
/**
* Get a suitable wall
*/
_findWall() {
let prio1 = [];
let prio2 = [];
for (let id in this._walls) {
let prio = this._walls[id];
if (prio == 2) {
prio2.push(id);
}
else {
prio1.push(id);
}
}
let arr = (prio2.length ? prio2 : prio1);
if (!arr.length) {
return null;
} /* no walls :/ */
let id = rng["a" /* default */].getItem(arr.sort()); // sort to make the order deterministic
delete this._walls[id];
return id;
}
/**
* Tries adding a feature
* @returns {bool} was this a successful try?
*/
_tryFeature(x, y, dx, dy) {
let featureName = rng["a" /* default */].getWeightedValue(this._features);
let ctor = FEATURES[featureName];
let feature = ctor.createRandomAt(x, y, dx, dy, this._options);
if (!feature.isValid(this._isWallCallback, this._canBeDugCallback)) {
// console.log("not valid");
// feature.debug();
return false;
}
feature.create(this._digCallback);
// feature.debug();
if (feature instanceof features_Room) {
this._rooms.push(feature);
}
if (feature instanceof features_Corridor) {
feature.createPriorityWalls(this._priorityWallCallback);
this._corridors.push(feature);
}
return true;
}
_removeSurroundingWalls(cx, cy) {
let deltas = DIRS[4];
for (let i = 0; i < deltas.length; i++) {
let delta = deltas[i];
let x = cx + delta[0];
let y = cy + delta[1];
delete this._walls[x + "," + y];
x = cx + 2 * delta[0];
y = cy + 2 * delta[1];
delete this._walls[x + "," + y];
}
}
/**
* Returns vector in "digging" direction, or false, if this does not exist (or is not unique)
*/
_getDiggingDirection(cx, cy) {
if (cx <= 0 || cy <= 0 || cx >= this._width - 1 || cy >= this._height - 1) {
return null;
}
let result = null;
let deltas = DIRS[4];
for (let i = 0; i < deltas.length; i++) {
let delta = deltas[i];
let x = cx + delta[0];
let y = cy + delta[1];
if (!this._map[x][y]) { /* there already is another empty neighbor! */
if (result) {
return null;
}
result = delta;
}
}
/* no empty neighbor */
if (!result) {
return null;
}
return [-result[0], -result[1]];
}
/**
* Find empty spaces surrounding rooms, and apply doors.
*/
_addDoors() {
let data = this._map;
function isWallCallback(x, y) {
return (data[x][y] == 1);
}
;
for (let i = 0; i < this._rooms.length; i++) {
let room = this._rooms[i];
room.clearDoors();
room.addDoors(isWallCallback);
}
}
} |
JavaScript | class rogue_Rogue extends map_Map {
constructor(width, height, options) {
super(width, height);
this.map = [];
this.rooms = [];
this.connectedCells = [];
options = Object.assign({
cellWidth: 3,
cellHeight: 3 // ie. as an array with min-max values for each direction....
}, options);
/*
Set the room sizes according to the over-all width of the map,
and the cell sizes.
*/
if (!options.hasOwnProperty("roomWidth")) {
options["roomWidth"] = this._calculateRoomSize(this._width, options["cellWidth"]);
}
if (!options.hasOwnProperty("roomHeight")) {
options["roomHeight"] = this._calculateRoomSize(this._height, options["cellHeight"]);
}
this._options = options;
}
create(callback) {
this.map = this._fillMap(1);
this.rooms = [];
this.connectedCells = [];
this._initRooms();
this._connectRooms();
this._connectUnconnectedRooms();
this._createRandomRoomConnections();
this._createRooms();
this._createCorridors();
if (callback) {
for (let i = 0; i < this._width; i++) {
for (let j = 0; j < this._height; j++) {
callback(i, j, this.map[i][j]);
}
}
}
return this;
}
_calculateRoomSize(size, cell) {
let max = Math.floor((size / cell) * 0.8);
let min = Math.floor((size / cell) * 0.25);
if (min < 2) {
min = 2;
}
if (max < 2) {
max = 2;
}
return [min, max];
}
_initRooms() {
// create rooms array. This is the "grid" list from the algo.
for (let i = 0; i < this._options.cellWidth; i++) {
this.rooms.push([]);
for (let j = 0; j < this._options.cellHeight; j++) {
this.rooms[i].push({ "x": 0, "y": 0, "width": 0, "height": 0, "connections": [], "cellx": i, "celly": j });
}
}
}
_connectRooms() {
//pick random starting grid
let cgx = rng["a" /* default */].getUniformInt(0, this._options.cellWidth - 1);
let cgy = rng["a" /* default */].getUniformInt(0, this._options.cellHeight - 1);
let idx;
let ncgx;
let ncgy;
let found = false;
let room;
let otherRoom;
let dirToCheck;
// find unconnected neighbour cells
do {
//dirToCheck = [0, 1, 2, 3, 4, 5, 6, 7];
dirToCheck = [0, 2, 4, 6];
dirToCheck = rng["a" /* default */].shuffle(dirToCheck);
do {
found = false;
idx = dirToCheck.pop();
ncgx = cgx + DIRS[8][idx][0];
ncgy = cgy + DIRS[8][idx][1];
if (ncgx < 0 || ncgx >= this._options.cellWidth) {
continue;
}
if (ncgy < 0 || ncgy >= this._options.cellHeight) {
continue;
}
room = this.rooms[cgx][cgy];
if (room["connections"].length > 0) {
// as long as this room doesn't already coonect to me, we are ok with it.
if (room["connections"][0][0] == ncgx && room["connections"][0][1] == ncgy) {
break;
}
}
otherRoom = this.rooms[ncgx][ncgy];
if (otherRoom["connections"].length == 0) {
otherRoom["connections"].push([cgx, cgy]);
this.connectedCells.push([ncgx, ncgy]);
cgx = ncgx;
cgy = ncgy;
found = true;
}
} while (dirToCheck.length > 0 && found == false);
} while (dirToCheck.length > 0);
}
_connectUnconnectedRooms() {
//While there are unconnected rooms, try to connect them to a random connected neighbor
//(if a room has no connected neighbors yet, just keep cycling, you'll fill out to it eventually).
let cw = this._options.cellWidth;
let ch = this._options.cellHeight;
this.connectedCells = rng["a" /* default */].shuffle(this.connectedCells);
let room;
let otherRoom;
let validRoom;
for (let i = 0; i < this._options.cellWidth; i++) {
for (let j = 0; j < this._options.cellHeight; j++) {
room = this.rooms[i][j];
if (room["connections"].length == 0) {
let directions = [0, 2, 4, 6];
directions = rng["a" /* default */].shuffle(directions);
validRoom = false;
do {
let dirIdx = directions.pop();
let newI = i + DIRS[8][dirIdx][0];
let newJ = j + DIRS[8][dirIdx][1];
if (newI < 0 || newI >= cw || newJ < 0 || newJ >= ch) {
continue;
}
otherRoom = this.rooms[newI][newJ];
validRoom = true;
if (otherRoom["connections"].length == 0) {
break;
}
for (let k = 0; k < otherRoom["connections"].length; k++) {
if (otherRoom["connections"][k][0] == i && otherRoom["connections"][k][1] == j) {
validRoom = false;
break;
}
}
if (validRoom) {
break;
}
} while (directions.length);
if (validRoom) {
room["connections"].push([otherRoom["cellx"], otherRoom["celly"]]);
}
else {
console.log("-- Unable to connect room.");
}
}
}
}
}
_createRandomRoomConnections() {
// Empty for now.
}
_createRooms() {
let w = this._width;
let h = this._height;
let cw = this._options.cellWidth;
let ch = this._options.cellHeight;
let cwp = Math.floor(this._width / cw);
let chp = Math.floor(this._height / ch);
let roomw;
let roomh;
let roomWidth = this._options["roomWidth"];
let roomHeight = this._options["roomHeight"];
let sx;
let sy;
let otherRoom;
for (let i = 0; i < cw; i++) {
for (let j = 0; j < ch; j++) {
sx = cwp * i;
sy = chp * j;
if (sx == 0) {
sx = 1;
}
if (sy == 0) {
sy = 1;
}
roomw = rng["a" /* default */].getUniformInt(roomWidth[0], roomWidth[1]);
roomh = rng["a" /* default */].getUniformInt(roomHeight[0], roomHeight[1]);
if (j > 0) {
otherRoom = this.rooms[i][j - 1];
while (sy - (otherRoom["y"] + otherRoom["height"]) < 3) {
sy++;
}
}
if (i > 0) {
otherRoom = this.rooms[i - 1][j];
while (sx - (otherRoom["x"] + otherRoom["width"]) < 3) {
sx++;
}
}
let sxOffset = Math.round(rng["a" /* default */].getUniformInt(0, cwp - roomw) / 2);
let syOffset = Math.round(rng["a" /* default */].getUniformInt(0, chp - roomh) / 2);
while (sx + sxOffset + roomw >= w) {
if (sxOffset) {
sxOffset--;
}
else {
roomw--;
}
}
while (sy + syOffset + roomh >= h) {
if (syOffset) {
syOffset--;
}
else {
roomh--;
}
}
sx = sx + sxOffset;
sy = sy + syOffset;
this.rooms[i][j]["x"] = sx;
this.rooms[i][j]["y"] = sy;
this.rooms[i][j]["width"] = roomw;
this.rooms[i][j]["height"] = roomh;
for (let ii = sx; ii < sx + roomw; ii++) {
for (let jj = sy; jj < sy + roomh; jj++) {
this.map[ii][jj] = 0;
}
}
}
}
}
_getWallPosition(aRoom, aDirection) {
let rx;
let ry;
let door;
if (aDirection == 1 || aDirection == 3) {
rx = rng["a" /* default */].getUniformInt(aRoom["x"] + 1, aRoom["x"] + aRoom["width"] - 2);
if (aDirection == 1) {
ry = aRoom["y"] - 2;
door = ry + 1;
}
else {
ry = aRoom["y"] + aRoom["height"] + 1;
door = ry - 1;
}
this.map[rx][door] = 0; // i'm not setting a specific 'door' tile value right now, just empty space.
}
else {
ry = rng["a" /* default */].getUniformInt(aRoom["y"] + 1, aRoom["y"] + aRoom["height"] - 2);
if (aDirection == 2) {
rx = aRoom["x"] + aRoom["width"] + 1;
door = rx - 1;
}
else {
rx = aRoom["x"] - 2;
door = rx + 1;
}
this.map[door][ry] = 0; // i'm not setting a specific 'door' tile value right now, just empty space.
}
return [rx, ry];
}
_drawCorridor(startPosition, endPosition) {
let xOffset = endPosition[0] - startPosition[0];
let yOffset = endPosition[1] - startPosition[1];
let xpos = startPosition[0];
let ypos = startPosition[1];
let tempDist;
let xDir;
let yDir;
let move; // 2 element array, element 0 is the direction, element 1 is the total value to move.
let moves = []; // a list of 2 element arrays
let xAbs = Math.abs(xOffset);
let yAbs = Math.abs(yOffset);
let percent = rng["a" /* default */].getUniform(); // used to split the move at different places along the long axis
let firstHalf = percent;
let secondHalf = 1 - percent;
xDir = xOffset > 0 ? 2 : 6;
yDir = yOffset > 0 ? 4 : 0;
if (xAbs < yAbs) {
// move firstHalf of the y offset
tempDist = Math.ceil(yAbs * firstHalf);
moves.push([yDir, tempDist]);
// move all the x offset
moves.push([xDir, xAbs]);
// move sendHalf of the y offset
tempDist = Math.floor(yAbs * secondHalf);
moves.push([yDir, tempDist]);
}
else {
// move firstHalf of the x offset
tempDist = Math.ceil(xAbs * firstHalf);
moves.push([xDir, tempDist]);
// move all the y offset
moves.push([yDir, yAbs]);
// move secondHalf of the x offset.
tempDist = Math.floor(xAbs * secondHalf);
moves.push([xDir, tempDist]);
}
this.map[xpos][ypos] = 0;
while (moves.length > 0) {
move = moves.pop();
while (move[1] > 0) {
xpos += DIRS[8][move[0]][0];
ypos += DIRS[8][move[0]][1];
this.map[xpos][ypos] = 0;
move[1] = move[1] - 1;
}
}
}
_createCorridors() {
// Draw Corridors between connected rooms
let cw = this._options.cellWidth;
let ch = this._options.cellHeight;
let room;
let connection;
let otherRoom;
let wall;
let otherWall;
for (let i = 0; i < cw; i++) {
for (let j = 0; j < ch; j++) {
room = this.rooms[i][j];
for (let k = 0; k < room["connections"].length; k++) {
connection = room["connections"][k];
otherRoom = this.rooms[connection[0]][connection[1]];
// figure out what wall our corridor will start one.
// figure out what wall our corridor will end on.
if (otherRoom["cellx"] > room["cellx"]) {
wall = 2;
otherWall = 4;
}
else if (otherRoom["cellx"] < room["cellx"]) {
wall = 4;
otherWall = 2;
}
else if (otherRoom["celly"] > room["celly"]) {
wall = 3;
otherWall = 1;
}
else {
wall = 1;
otherWall = 3;
}
this._drawCorridor(this._getWallPosition(room, wall), this._getWallPosition(otherRoom, otherWall));
}
}
}
}
} |
JavaScript | class simplex_Simplex extends Noise {
/**
* @param gradients Random gradients
*/
constructor(gradients = 256) {
super();
this._gradients = [
[0, -1],
[1, -1],
[1, 0],
[1, 1],
[0, 1],
[-1, 1],
[-1, 0],
[-1, -1]
];
let permutations = [];
for (let i = 0; i < gradients; i++) {
permutations.push(i);
}
permutations = rng["a" /* default */].shuffle(permutations);
this._perms = [];
this._indexes = [];
for (let i = 0; i < 2 * gradients; i++) {
this._perms.push(permutations[i % gradients]);
this._indexes.push(this._perms[i] % this._gradients.length);
}
}
get(xin, yin) {
let perms = this._perms;
let indexes = this._indexes;
let count = perms.length / 2;
let n0 = 0, n1 = 0, n2 = 0, gi; // Noise contributions from the three corners
// Skew the input space to determine which simplex cell we're in
let s = (xin + yin) * F2; // Hairy factor for 2D
let i = Math.floor(xin + s);
let j = Math.floor(yin + s);
let t = (i + j) * G2;
let X0 = i - t; // Unskew the cell origin back to (x,y) space
let Y0 = j - t;
let x0 = xin - X0; // The x,y distances from the cell origin
let y0 = yin - Y0;
// For the 2D case, the simplex shape is an equilateral triangle.
// Determine which simplex we are in.
let i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords
if (x0 > y0) {
i1 = 1;
j1 = 0;
}
else { // lower triangle, XY order: (0,0)->(1,0)->(1,1)
i1 = 0;
j1 = 1;
} // upper triangle, YX order: (0,0)->(0,1)->(1,1)
// A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
// a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
// c = (3-sqrt(3))/6
let x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords
let y1 = y0 - j1 + G2;
let x2 = x0 - 1 + 2 * G2; // Offsets for last corner in (x,y) unskewed coords
let y2 = y0 - 1 + 2 * G2;
// Work out the hashed gradient indices of the three simplex corners
let ii = Object(util["mod"])(i, count);
let jj = Object(util["mod"])(j, count);
// Calculate the contribution from the three corners
let t0 = 0.5 - x0 * x0 - y0 * y0;
if (t0 >= 0) {
t0 *= t0;
gi = indexes[ii + perms[jj]];
let grad = this._gradients[gi];
n0 = t0 * t0 * (grad[0] * x0 + grad[1] * y0);
}
let t1 = 0.5 - x1 * x1 - y1 * y1;
if (t1 >= 0) {
t1 *= t1;
gi = indexes[ii + i1 + perms[jj + j1]];
let grad = this._gradients[gi];
n1 = t1 * t1 * (grad[0] * x1 + grad[1] * y1);
}
let t2 = 0.5 - x2 * x2 - y2 * y2;
if (t2 >= 0) {
t2 *= t2;
gi = indexes[ii + 1 + perms[jj + 1]];
let grad = this._gradients[gi];
n2 = t2 * t2 * (grad[0] * x2 + grad[1] * y2);
}
// Add contributions from each corner to get the final noise value.
// The result is scaled to return values in the interval [-1,1].
return 70 * (n0 + n1 + n2);
}
} |
JavaScript | class dijkstra_Dijkstra extends path_Path {
constructor(toX, toY, passableCallback, options) {
super(toX, toY, passableCallback, options);
this._computed = {};
this._todo = [];
this._add(toX, toY, null);
}
/**
* Compute a path from a given point
* @see ROT.Path#compute
*/
compute(fromX, fromY, callback) {
let key = fromX + "," + fromY;
if (!(key in this._computed)) {
this._compute(fromX, fromY);
}
if (!(key in this._computed)) {
return;
}
let item = this._computed[key];
while (item) {
callback(item.x, item.y);
item = item.prev;
}
}
/**
* Compute a non-cached value
*/
_compute(fromX, fromY) {
while (this._todo.length) {
let item = this._todo.shift();
if (item.x == fromX && item.y == fromY) {
return;
}
let neighbors = this._getNeighbors(item.x, item.y);
for (let i = 0; i < neighbors.length; i++) {
let neighbor = neighbors[i];
let x = neighbor[0];
let y = neighbor[1];
let id = x + "," + y;
if (id in this._computed) {
continue;
} /* already done */
this._add(x, y, item);
}
}
}
_add(x, y, prev) {
let obj = {
x: x,
y: y,
prev: prev
};
this._computed[x + "," + y] = obj;
this._todo.push(obj);
}
} |
JavaScript | class astar_AStar extends path_Path {
constructor(toX, toY, passableCallback, options = {}) {
super(toX, toY, passableCallback, options);
this._todo = [];
this._done = {};
}
/**
* Compute a path from a given point
* @see ROT.Path#compute
*/
compute(fromX, fromY, callback) {
this._todo = [];
this._done = {};
this._fromX = fromX;
this._fromY = fromY;
this._add(this._toX, this._toY, null);
while (this._todo.length) {
let item = this._todo.shift();
let id = item.x + "," + item.y;
if (id in this._done) {
continue;
}
this._done[id] = item;
if (item.x == fromX && item.y == fromY) {
break;
}
let neighbors = this._getNeighbors(item.x, item.y);
for (let i = 0; i < neighbors.length; i++) {
let neighbor = neighbors[i];
let x = neighbor[0];
let y = neighbor[1];
let id = x + "," + y;
if (id in this._done) {
continue;
}
this._add(x, y, item);
}
}
let item = this._done[fromX + "," + fromY];
if (!item) {
return;
}
while (item) {
callback(item.x, item.y);
item = item.prev;
}
}
_add(x, y, prev) {
let h = this._distance(x, y);
let obj = {
x: x,
y: y,
prev: prev,
g: (prev ? prev.g + 1 : 0),
h: h
};
/* insert into priority queue */
let f = obj.g + obj.h;
for (let i = 0; i < this._todo.length; i++) {
let item = this._todo[i];
let itemF = item.g + item.h;
if (f < itemF || (f == itemF && h < item.h)) {
this._todo.splice(i, 0, obj);
return;
}
}
this._todo.push(obj);
}
_distance(x, y) {
switch (this._options.topology) {
case 4:
return (Math.abs(x - this._fromX) + Math.abs(y - this._fromY));
break;
case 6:
let dx = Math.abs(x - this._fromX);
let dy = Math.abs(y - this._fromY);
return dy + Math.max(0, (dx - dy) / 2);
break;
case 8:
return Math.max(Math.abs(x - this._fromX), Math.abs(y - this._fromY));
break;
}
}
} |
JavaScript | class Engine {
constructor(scheduler) {
this._scheduler = scheduler;
this._lock = 1;
}
/**
* Start the main loop. When this call returns, the loop is locked.
*/
start() { return this.unlock(); }
/**
* Interrupt the engine by an asynchronous action
*/
lock() {
this._lock++;
return this;
}
/**
* Resume execution (paused by a previous lock)
*/
unlock() {
if (!this._lock) {
throw new Error("Cannot unlock unlocked engine");
}
this._lock--;
while (!this._lock) {
let actor = this._scheduler.next();
if (!actor) {
return this.lock();
} /* no actors */
let result = actor.act();
if (result && result.then) { /* actor returned a "thenable", looks like a Promise */
this.lock();
result.then(this.unlock.bind(this));
}
}
return this;
}
} |
JavaScript | class lighting_Lighting {
constructor(reflectivityCallback, options = {}) {
this._reflectivityCallback = reflectivityCallback;
this._options = {};
options = Object.assign({
passes: 1,
emissionThreshold: 100,
range: 10
}, options);
this._lights = {};
this._reflectivityCache = {};
this._fovCache = {};
this.setOptions(options);
}
/**
* Adjust options at runtime
*/
setOptions(options) {
Object.assign(this._options, options);
if (options && options.range) {
this.reset();
}
return this;
}
/**
* Set the used Field-Of-View algo
*/
setFOV(fov) {
this._fov = fov;
this._fovCache = {};
return this;
}
/**
* Set (or remove) a light source
*/
setLight(x, y, color) {
let key = x + "," + y;
if (color) {
this._lights[key] = (typeof (color) == "string" ? lib_color["fromString"](color) : color);
}
else {
delete this._lights[key];
}
return this;
}
/**
* Remove all light sources
*/
clearLights() { this._lights = {}; }
/**
* Reset the pre-computed topology values. Call whenever the underlying map changes its light-passability.
*/
reset() {
this._reflectivityCache = {};
this._fovCache = {};
return this;
}
/**
* Compute the lighting
*/
compute(lightingCallback) {
let doneCells = {};
let emittingCells = {};
let litCells = {};
for (let key in this._lights) { /* prepare emitters for first pass */
let light = this._lights[key];
emittingCells[key] = [0, 0, 0];
lib_color["add_"](emittingCells[key], light);
}
for (let i = 0; i < this._options.passes; i++) { /* main loop */
this._emitLight(emittingCells, litCells, doneCells);
if (i + 1 == this._options.passes) {
continue;
} /* not for the last pass */
emittingCells = this._computeEmitters(litCells, doneCells);
}
for (let litKey in litCells) { /* let the user know what and how is lit */
let parts = litKey.split(",");
let x = parseInt(parts[0]);
let y = parseInt(parts[1]);
lightingCallback(x, y, litCells[litKey]);
}
return this;
}
/**
* Compute one iteration from all emitting cells
* @param emittingCells These emit light
* @param litCells Add projected light to these
* @param doneCells These already emitted, forbid them from further calculations
*/
_emitLight(emittingCells, litCells, doneCells) {
for (let key in emittingCells) {
let parts = key.split(",");
let x = parseInt(parts[0]);
let y = parseInt(parts[1]);
this._emitLightFromCell(x, y, emittingCells[key], litCells);
doneCells[key] = 1;
}
return this;
}
/**
* Prepare a list of emitters for next pass
*/
_computeEmitters(litCells, doneCells) {
let result = {};
for (let key in litCells) {
if (key in doneCells) {
continue;
} /* already emitted */
let color = litCells[key];
let reflectivity;
if (key in this._reflectivityCache) {
reflectivity = this._reflectivityCache[key];
}
else {
let parts = key.split(",");
let x = parseInt(parts[0]);
let y = parseInt(parts[1]);
reflectivity = this._reflectivityCallback(x, y);
this._reflectivityCache[key] = reflectivity;
}
if (reflectivity == 0) {
continue;
} /* will not reflect at all */
/* compute emission color */
let emission = [0, 0, 0];
let intensity = 0;
for (let i = 0; i < 3; i++) {
let part = Math.round(color[i] * reflectivity);
emission[i] = part;
intensity += part;
}
if (intensity > this._options.emissionThreshold) {
result[key] = emission;
}
}
return result;
}
/**
* Compute one iteration from one cell
*/
_emitLightFromCell(x, y, color, litCells) {
let key = x + "," + y;
let fov;
if (key in this._fovCache) {
fov = this._fovCache[key];
}
else {
fov = this._updateFOV(x, y);
}
for (let fovKey in fov) {
let formFactor = fov[fovKey];
let result;
if (fovKey in litCells) { /* already lit */
result = litCells[fovKey];
}
else { /* newly lit */
result = [0, 0, 0];
litCells[fovKey] = result;
}
for (let i = 0; i < 3; i++) {
result[i] += Math.round(color[i] * formFactor);
} /* add light color */
}
return this;
}
/**
* Compute FOV ("form factor") for a potential light source at [x,y]
*/
_updateFOV(x, y) {
let key1 = x + "," + y;
let cache = {};
this._fovCache[key1] = cache;
let range = this._options.range;
function cb(x, y, r, vis) {
let key2 = x + "," + y;
let formFactor = vis * (1 - r / range);
if (formFactor == 0) {
return;
}
cache[key2] = formFactor;
}
;
this._fov.compute(x, y, range, cb.bind(this));
return cache;
}
} |
JavaScript | class DateFormatter {
constructor(config) {
/**
* Formatting for the day
* @public
*/
this.dayFormat = "numeric";
/**
* Formatting for the weekday labels
* @public
*/
this.weekdayFormat = "long";
/**
* Formatting for the month
* @public
*/
this.monthFormat = "long";
/**
* Formatting for the year
* @public
*/
this.yearFormat = "numeric";
/**
* Date used for formatting
*/
this.date = new Date();
/**
* Add properties on construction
*/
if (config) {
for (const key in config) {
const value = config[key];
if (key === "date") {
this.date = this.getDateObject(value);
}
else {
this[key] = value;
}
}
}
}
/**
* Helper function to make sure that the DateFormatter is working with an instance of Date
* @param date - The date as an object, string or Date insance
* @returns - A Date instance
* @public
*/
getDateObject(date) {
if (typeof date === "string") {
const dates = date.split(/[/-]/);
if (dates.length < 3) {
return new Date();
}
return new Date(parseInt(dates[2], 10), parseInt(dates[0], 10) - 1, parseInt(dates[1], 10));
}
else if ("day" in date && "month" in date && "year" in date) {
const { day, month, year } = date;
return new Date(year, month - 1, day);
}
return date;
}
/**
*
* @param date - a valide date as either a Date, string, objec or a DateFormatter
* @param format - The formatting for the string
* @param locale - locale data used for formatting
* @returns A localized string of the date provided
* @public
*/
getDate(date = this.date, format = {
weekday: this.weekdayFormat,
month: this.monthFormat,
day: this.dayFormat,
year: this.yearFormat,
}, locale = this.locale) {
const dateObj = this.getDateObject(date);
const optionsWithTimeZone = Object.assign({ timeZone: "utc" }, format);
return new Intl.DateTimeFormat(locale, optionsWithTimeZone).format(dateObj);
}
/**
*
* @param day - Day to localize
* @param format - The formatting for the day
* @param locale - The locale data used for formatting
* @returns - A localized number for the day
* @public
*/
getDay(day = this.date.getDate(), format = this.dayFormat, locale = this.locale) {
return this.getDate({ month: 1, day, year: 2020 }, { day: format }, locale);
}
/**
*
* @param month - The month to localize
* @param format - The formatting for the month
* @param locale - The locale data used for formatting
* @returns - A localized name of the month
* @public
*/
getMonth(month = this.date.getMonth() + 1, format = this.monthFormat, locale = this.locale) {
return this.getDate({ month, day: 2, year: 2020 }, { month: format }, locale);
}
/**
*
* @param year - The year to localize
* @param format - The formatting for the year
* @param locale - The locale data used for formatting
* @returns - A localized string for the year
* @public
*/
getYear(year = this.date.getFullYear(), format = this.yearFormat, locale = this.locale) {
return this.getDate({ month: 2, day: 2, year }, { year: format }, locale);
}
/**
*
* @param weekday - The number of the weekday, defaults to Sunday
* @param format - The formatting for the weekday label
* @param locale - The locale data used for formatting
* @returns - A formatted weekday label
* @public
*/
getWeekday(weekday = 0, format = this.weekdayFormat, locale = this.locale) {
const date = `1-${weekday + 1}-2017`;
return this.getDate(date, { weekday: format }, locale);
}
/**
*
* @param format - The formatting for the weekdays
* @param locale - The locale data used for formatting
* @returns - An array of the weekday labels
* @public
*/
getWeekdays(format = this.weekdayFormat, locale = this.locale) {
return Array(7)
.fill(null)
.map((_, day) => this.getWeekday(day, format, locale));
}
} |
JavaScript | class Map extends Evented {
constructor(options = {}) {
super();
this._container = document.createElement('div');
this.options = options;
this.version = options.version;
this.style = new Style(options.style);
this._controls = [];
this.transform = new Transform(options);
this._loaded = false;
this.painter = {context: {gl}};
setTimeout(() => {
this.style._loaded = true;
this.fire(new Event('styledata'));
this._loaded = true;
this.fire(new Event('load'));
}, 0);
}
getContainer() {
return this._container;
}
getCenter() {
return this.transform.center;
}
setCenter(value) {
this.transform.center = value;
}
getZoom() {
return this.transform.zoom;
}
setZoom(value) {
this.transform.zoom = value;
}
getBearing() {
return this.transform.bearing;
}
setBearing(value) {
this.transform.bearing = value;
}
getPitch() {
return this.transform.pitch;
}
setPitch(value) {
this.transform.pitch = value;
}
getPadding() {
return this.transform.padding;
}
setPadding(value) {
this.transform.padding = value;
}
getRenderWorldCopies() {
return this.transform.renderWorldCopies;
}
setRenderWorldCopies(value) {
this.transform.renderWorldCopies = value;
}
addControl(control) {
this._controls.push(control);
control.onAdd(this);
}
removeControl(control) {
const i = this._controls.indexOf(control);
if (i >= 0) {
this._controls.splice(i, 1);
control.onRemove(this);
}
}
loaded() {
return this._loaded;
}
getStyle() {
return this.style.serialize();
}
setStyle(style) {
this.style = new Style(style);
setTimeout(() => {
this.style._loaded = true;
this.fire(new Event('styledata'));
}, 0);
}
addLayer(layer, beforeId) {
this.style.addLayer(layer, beforeId);
if (layer.type === 'custom') {
layer.onAdd(this, gl);
}
}
moveLayer(layerId, beforeId) {
this.style.moveLayer(layerId, beforeId);
}
removeLayer(layerId) {
const layer = this.getLayer(layerId);
if (layer.type === 'custom') {
layer.onRemove(this);
}
this.style.removeLayer(layerId);
}
getLayer(layerId) {
return this.style.getLayer(layerId);
}
triggerRepaint() {
setTimeout(() => this._render(), 0);
}
_render() {
this.style.render();
this.fire(new Event('render'));
}
remove() {
this._controls = [];
this.style = null;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.