1
0
mirror of https://github.com/psychopy/psychojs.git synced 2025-05-10 18:50:54 +00:00
psychojs/docs/util_Util.js.html
2022-09-12 13:20:16 +02:00

1494 lines
74 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>util/Util.js - PsychoJS API</title>
<meta name="keywords" content="psychopy, psychojs, api" />
<meta name="keyword" content="psychopy, psychojs, api" />
<script src="scripts/prettify/prettify.js"></script>
<script src="scripts/prettify/lang-css.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc.css">
<script src="scripts/nav.js" defer></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
<div class="navicon"></div>
</label>
<label for="nav-trigger" class="overlay"></label>
<nav >
<input type="text" id="nav-search" placeholder="Search" />
<h2><a href="index.html">Home</a></h2><h2><a href="https://psychopy.org" target="_blank" class="menu-item" id="website_link" >Project Website</a></h2><h2><a href="https://discourse.psychopy.org/" target="_blank" class="menu-item" id="forum_link" >Forum</a></h2><h2><a href="https://github.com/psychopy/psychojs" target="_blank" class="menu-item" id="github_link" >Github</a></h2><h3>Modules</h3><ul><li><a href="module-core.html">core</a></li><li><a href="module-data.html">data</a></li><li><a href="module-sound.html">sound</a></li><li><a href="module-util.html">util</a><ul class='methods'><li data-type='method'><a href="module-util.html#~_match">_match</a></li></ul></li><li></li><li><a href="module-visual.html">visual</a></li></ul><h3>Classes</h3><ul><li><a href="AudioClip.html">AudioClip</a><ul class='methods'><li data-type='method'><a href="AudioClip.html#_base64ArrayBuffer">_base64ArrayBuffer</a></li><li data-type='method'><a href="AudioClip.html#_decodeAudio">_decodeAudio</a></li><li data-type='method'><a href="AudioClip.html#_GoogleTranscribe">_GoogleTranscribe</a></li><li data-type='method'><a href="AudioClip.html#download">download</a></li><li data-type='method'><a href="AudioClip.html#getDuration">getDuration</a></li><li data-type='method'><a href="AudioClip.html#setVolume">setVolume</a></li><li data-type='method'><a href="AudioClip.html#startPlayback">startPlayback</a></li><li data-type='method'><a href="AudioClip.html#stopPlayback">stopPlayback</a></li><li data-type='method'><a href="AudioClip.html#transcribe">transcribe</a></li><li data-type='method'><a href="AudioClip.html#upload">upload</a></li></ul></li><li><a href="AudioClipPlayer.html">AudioClipPlayer</a><ul class='methods'><li data-type='method'><a href="AudioClipPlayer.html#getDuration">getDuration</a></li><li data-type='method'><a href="AudioClipPlayer.html#play">play</a></li><li data-type='method'><a href="AudioClipPlayer.html#setDuration">setDuration</a></li><li data-type='method'><a href="AudioClipPlayer.html#setLoops">setLoops</a></li><li data-type='method'><a href="AudioClipPlayer.html#setVolume">setVolume</a></li><li data-type='method'><a href="AudioClipPlayer.html#stop">stop</a></li></ul></li><li><a href="BuilderKeyResponse.html">BuilderKeyResponse</a></li><li><a href="ButtonStim.html">ButtonStim</a><ul class='methods'><li data-type='method'><a href="ButtonStim.html#_addEventListeners">_addEventListeners</a></li><li data-type='method'><a href="ButtonStim.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="ButtonStim.html#_getAnchor">_getAnchor</a></li><li data-type='method'><a href="ButtonStim.html#_getDefaultLetterHeight">_getDefaultLetterHeight</a></li><li data-type='method'><a href="ButtonStim.html#_getTextInputOptions">_getTextInputOptions</a></li><li data-type='method'><a href="ButtonStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="ButtonStim.html#clear">clear</a></li><li data-type='method'><a href="ButtonStim.html#getText">getText</a></li><li data-type='method'><a href="ButtonStim.html#reset">reset</a></li><li data-type='method'><a href="ButtonStim.html#setAlignment">setAlignment</a></li><li data-type='method'><a href="ButtonStim.html#setAnchor">setAnchor</a></li><li data-type='method'><a href="ButtonStim.html#setBorderColor">setBorderColor</a></li><li data-type='method'><a href="ButtonStim.html#setColor">setColor</a></li><li data-type='method'><a href="ButtonStim.html#setFillColor">setFillColor</a></li><li data-type='method'><a href="ButtonStim.html#setFitToContent">setFitToContent</a></li><li data-type='method'><a href="ButtonStim.html#setFont">setFont</a></li><li data-type='method'><a href="ButtonStim.html#setLanguageStyle">setLanguageStyle</a></li><li data-type='method'><a href="ButtonStim.html#setLetterHeight">setLetterHeight</a></li><li data-type='method'><a href="ButtonStim.html#setSize">setSize</a></li><li data-type='method'><a href="ButtonStim.html#setText">setText</a></li></ul></li><li><a href="Clock.html">Clock</a><ul class='methods'><li data-type='method'><a href="Clock.html#add">add</a></li><li data-type='method'><a href="Clock.html#getLastResetTime">getLastResetTime</a></li><li data-type='method'><a href="Clock.html#getTime">getTime</a></li><li data-type='method'><a href="Clock.html#reset">reset</a></li></ul></li><li><a href="Color.html">Color</a><ul class='methods'><li data-type='method'><a href="Color.html#toString">toString</a></li></ul></li><li><a href="CountdownTimer.html">CountdownTimer</a><ul class='methods'><li data-type='method'><a href="CountdownTimer.html#add">add</a></li><li data-type='method'><a href="CountdownTimer.html#getLastResetTime">getLastResetTime</a></li><li data-type='method'><a href="CountdownTimer.html#getTime">getTime</a></li><li data-type='method'><a href="CountdownTimer.html#reset">reset</a></li></ul></li><li><a href="EventEmitter.html">EventEmitter</a><ul class='methods'><li data-type='method'><a href="EventEmitter.html#emit">emit</a></li><li data-type='method'><a href="EventEmitter.html#off">off</a></li><li data-type='method'><a href="EventEmitter.html#on">on</a></li><li data-type='method'><a href="EventEmitter.html#once">once</a></li></ul></li><li><a href="EventManager.html">EventManager</a><ul class='methods'><li data-type='method'><a href="EventManager.html#_addKeyListeners">_addKeyListeners</a></li><li data-type='method'><a href="EventManager.html#addMouseListeners">addMouseListeners</a></li><li data-type='method'><a href="EventManager.html#clearEvents">clearEvents</a></li><li data-type='method'><a href="EventManager.html#clearKeys">clearKeys</a></li><li data-type='method'><a href="EventManager.html#getKeys">getKeys</a></li><li data-type='method'><a href="EventManager.html#getMouseInfo">getMouseInfo</a></li><li data-type='method'><a href="EventManager.html#resetMoveClock">resetMoveClock</a></li><li data-type='method'><a href="EventManager.html#startMoveClock">startMoveClock</a></li><li data-type='method'><a href="EventManager.html#stopMoveClock">stopMoveClock</a></li></ul></li><li><a href="ExperimentHandler.html">ExperimentHandler</a><ul class='methods'><li data-type='method'><a href="ExperimentHandler.html#addData">addData</a></li><li data-type='method'><a href="ExperimentHandler.html#addLoop">addLoop</a></li><li data-type='method'><a href="ExperimentHandler.html#isEntryEmpty">isEntryEmpty</a></li><li data-type='method'><a href="ExperimentHandler.html#nextEntry">nextEntry</a></li><li data-type='method'><a href="ExperimentHandler.html#removeLoop">removeLoop</a></li><li data-type='method'><a href="ExperimentHandler.html#save">save</a></li></ul></li><li><a href="FaceDetector.html">FaceDetector</a><ul class='methods'><li data-type='method'><a href="FaceDetector.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="FaceDetector.html#_initFaceApi">_initFaceApi</a></li><li data-type='method'><a href="FaceDetector.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="FaceDetector.html#isReady">isReady</a></li><li data-type='method'><a href="FaceDetector.html#setInput">setInput</a></li><li data-type='method'><a href="FaceDetector.html#start">start</a></li><li data-type='method'><a href="FaceDetector.html#stop">stop</a></li></ul></li><li><a href="Form.html">Form</a><ul class='methods'><li data-type='method'><a href="Form.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="Form.html#_getBoundingBox_px">_getBoundingBox_px</a></li><li data-type='method'><a href="Form.html#_importItems">_importItems</a></li><li data-type='method'><a href="Form.html#_onChange">_onChange</a></li><li data-type='method'><a href="Form.html#_processItems">_processItems</a></li><li data-type='method'><a href="Form.html#_sanitizeItems">_sanitizeItems</a></li><li data-type='method'><a href="Form.html#_setupStimuli">_setupStimuli</a></li><li data-type='method'><a href="Form.html#_updateDecorations">_updateDecorations</a></li><li data-type='method'><a href="Form.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="Form.html#_updateVisibleStimuli">_updateVisibleStimuli</a></li><li data-type='method'><a href="Form.html#addDataToExp">addDataToExp</a></li><li data-type='method'><a href="Form.html#contains">contains</a></li><li data-type='method'><a href="Form.html#draw">draw</a></li><li data-type='method'><a href="Form.html#formComplete">formComplete</a></li><li data-type='method'><a href="Form.html#getData">getData</a></li><li data-type='method'><a href="Form.html#hide">hide</a></li><li data-type='method'><a href="Form.html#refresh">refresh</a></li><li data-type='method'><a href="Form.html#release">release</a></li><li data-type='method'><a href="Form.html#reset">reset</a></li><li data-type='method'><a href="Form.html#setAutoDraw">setAutoDraw</a></li><li data-type='method'><a href="Form.html#setDepth">setDepth</a></li><li data-type='method'><a href="Form.html#setOri">setOri</a></li><li data-type='method'><a href="Form.html#setPos">setPos</a></li><li data-type='method'><a href="Form.html#setSize">setSize</a></li></ul></li><li><a href="GratingStim.html">GratingStim</a><ul class='methods'><li data-type='method'><a href="GratingStim.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="GratingStim.html#_getDisplaySize">_getDisplaySize</a></li><li data-type='method'><a href="GratingStim.html#_getPixiMeshFromPredefinedShaders">_getPixiMeshFromPredefinedShaders</a></li><li data-type='method'><a href="GratingStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="GratingStim.html#setBlendmode">setBlendmode</a></li><li data-type='method'><a href="GratingStim.html#setColor">setColor</a></li><li data-type='method'><a href="GratingStim.html#setColorSpace">setColorSpace</a></li><li data-type='method'><a href="GratingStim.html#setInterpolate">setInterpolate</a></li><li data-type='method'><a href="GratingStim.html#setMask">setMask</a></li><li data-type='method'><a href="GratingStim.html#setOpacity">setOpacity</a></li><li data-type='method'><a href="GratingStim.html#setPhase">setPhase</a></li><li data-type='method'><a href="GratingStim.html#setSF">setSF</a></li><li data-type='method'><a href="GratingStim.html#setTex">setTex</a></li></ul></li><li><a href="GUI.html">GUI</a><ul class='methods'><li data-type='method'><a href="GUI.html#_onCancelExperiment">_onCancelExperiment</a></li><li data-type='method'><a href="GUI.html#_onResourceEvents">_onResourceEvents</a></li><li data-type='method'><a href="GUI.html#_onStartExperiment">_onStartExperiment</a></li><li data-type='method'><a href="GUI.html#_setProgressMessage">_setProgressMessage</a></li><li data-type='method'><a href="GUI.html#_updateDialog">_updateDialog</a></li><li data-type='method'><a href="GUI.html#_updateProgressBar">_updateProgressBar</a></li><li data-type='method'><a href="GUI.html#_userFriendlyError">_userFriendlyError</a></li><li data-type='method'><a href="GUI.html#closeDialog">closeDialog</a></li><li data-type='method'><a href="GUI.html#dialog">dialog</a></li><li data-type='method'><a href="GUI.html#DlgFromDict">DlgFromDict</a></li><li data-type='method'><a href="GUI.html#finishDialog">finishDialog</a></li></ul></li><li><a href="ImageStim.html">ImageStim</a><ul class='methods'><li data-type='method'><a href="ImageStim.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="ImageStim.html#_getDisplaySize">_getDisplaySize</a></li><li data-type='method'><a href="ImageStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="ImageStim.html#setImage">setImage</a></li><li data-type='method'><a href="ImageStim.html#setInterpolate">setInterpolate</a></li><li data-type='method'><a href="ImageStim.html#setMask">setMask</a></li></ul></li><li><a href="Keyboard.html">Keyboard</a><ul class='methods'><li data-type='method'><a href="Keyboard.html#_addKeyListeners">_addKeyListeners</a></li><li data-type='method'><a href="Keyboard.html#clearEvents">clearEvents</a></li><li data-type='method'><a href="Keyboard.html#getEvents">getEvents</a></li><li data-type='method'><a href="Keyboard.html#getKeys">getKeys</a></li><li data-type='method'><a href="Keyboard.html#start">start</a></li><li data-type='method'><a href="Keyboard.html#stop">stop</a></li></ul></li><li><a href="KeyPress.html">KeyPress</a></li><li><a href="Logger.html">Logger</a><ul class='methods'><li data-type='method'><a href="Logger.html#_customConsoleLayout">_customConsoleLayout</a></li><li data-type='method'><a href="Logger.html#_getValue">_getValue</a></li><li data-type='method'><a href="Logger.html#_throttle">_throttle</a></li><li data-type='method'><a href="Logger.html#data">data</a></li><li data-type='method'><a href="Logger.html#exp">exp</a></li><li data-type='method'><a href="Logger.html#flush">flush</a></li><li data-type='method'><a href="Logger.html#log">log</a></li><li data-type='method'><a href="Logger.html#setLevel">setLevel</a></li></ul></li><li><a href="Microphone.html">Microphone</a><ul class='methods'><li data-type='method'><a href="Microphone.html#_onChange">_onChange</a></li><li data-type='method'><a href="Microphone.html#_prepareRecording">_prepareRecording</a></li><li data-type='method'><a href="Microphone.html#download">download</a></li><li data-type='method'><a href="Microphone.html#flush">flush</a></li><li data-type='method'><a href="Microphone.html#getRecording">getRecording</a></li><li data-type='method'><a href="Microphone.html#pause">pause</a></li><li data-type='method'><a href="Microphone.html#resume">resume</a></li><li data-type='method'><a href="Microphone.html#start">start</a></li><li data-type='method'><a href="Microphone.html#stop">stop</a></li><li data-type='method'><a href="Microphone.html#upload">upload</a></li></ul></li><li><a href="MinimalStim.html">MinimalStim</a><ul class='methods'><li data-type='method'><a href="MinimalStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="MinimalStim.html#contains">contains</a></li><li data-type='method'><a href="MinimalStim.html#draw">draw</a></li><li data-type='method'><a href="MinimalStim.html#hide">hide</a></li><li data-type='method'><a href="MinimalStim.html#release">release</a></li><li data-type='method'><a href="MinimalStim.html#setAutoDraw">setAutoDraw</a></li></ul></li><li><a href="module-core.PsychoJS.html">PsychoJS</a><ul class='methods'><li data-type='method'><a href="module-core.PsychoJS.html#_captureErrors">_captureErrors</a></li><li data-type='method'><a href="module-core.PsychoJS.html#_configure">_configure</a></li><li data-type='method'><a href="module-core.PsychoJS.html#_getParticipantIPInfo">_getParticipantIPInfo</a></li><li data-type='method'><a href="module-core.PsychoJS.html#_makeStatusTopLevel">_makeStatusTopLevel</a></li><li data-type='method'><a href="module-core.PsychoJS.html#getEnvironment">getEnvironment</a></li><li data-type='method'><a href="module-core.PsychoJS.html#importAttributes">importAttributes</a></li><li data-type='method'><a href="module-core.PsychoJS.html#openWindow">openWindow</a></li><li data-type='method'><a href="module-core.PsychoJS.html#quit">quit</a></li><li data-type='method'><a href="module-core.PsychoJS.html#schedule">schedule</a></li><li data-type='method'><a href="module-core.PsychoJS.html#scheduleCondition">scheduleCondition</a></li><li data-type='method'><a href="module-core.PsychoJS.html#setRedirectUrls">setRedirectUrls</a></li><li data-type='method'><a href="module-core.PsychoJS.html#start">start</a></li><li data-type='method'><a href="module-core.PsychoJS.html#waitForResources">waitForResources</a></li></ul></li><li><a href="module-data.TrialHandler.html">TrialHandler</a><ul class='methods'><li data-type='method'><a href="module-data.TrialHandler.html#_prepareSequence">_prepareSequence</a></li><li data-type='method'><a href="module-data.TrialHandler.html#_prepareTrialList">_prepareTrialList</a></li><li data-type='method'><a href="module-data.TrialHandler.html#addData">addData</a></li><li data-type='method'><a href="module-data.TrialHandler.html#forEach">forEach</a></li><li data-type='method'><a href="module-data.TrialHandler.html#getAttributes">getAttributes</a></li><li data-type='method'><a href="module-data.TrialHandler.html#getCurrentTrial">getCurrentTrial</a></li><li data-type='method'><a href="module-data.TrialHandler.html#getEarlierTrial">getEarlierTrial</a></li><li data-type='method'><a href="module-data.TrialHandler.html#getFutureTrial">getFutureTrial</a></li><li data-type='method'><a href="module-data.TrialHandler.html#getSnapshot">getSnapshot</a></li><li data-type='method'><a href="module-data.TrialHandler.html#getTrial">getTrial</a></li><li data-type='method'><a href="module-data.TrialHandler.html#getTrialIndex">getTrialIndex</a></li><li data-type='method'><a href="module-data.TrialHandler.html#next">next</a></li><li data-type='method'><a href="module-data.TrialHandler.html#setSeed">setSeed</a></li><li data-type='method'><a href="module-data.TrialHandler.html#setTrialIndex">setTrialIndex</a></li><li data-type='method'><a href="module-data.TrialHandler.html#Symbol.iterator">Symbol.iterator</a></li></ul></li><li><a href="module-hardware.Camera.html">Camera</a><ul class='methods'><li data-type='method'><a href="module-hardware.Camera.html#_onChange">_onChange</a></li><li data-type='method'><a href="module-hardware.Camera.html#_prepareRecording">_prepareRecording</a></li><li data-type='method'><a href="module-hardware.Camera.html#_upload">_upload</a></li><li data-type='method'><a href="module-hardware.Camera.html#authorize">authorize</a></li><li data-type='method'><a href="module-hardware.Camera.html#close">close</a></li><li data-type='method'><a href="module-hardware.Camera.html#flush">flush</a></li><li data-type='method'><a href="module-hardware.Camera.html#getRecording">getRecording</a></li><li data-type='method'><a href="module-hardware.Camera.html#getStream">getStream</a></li><li data-type='method'><a href="module-hardware.Camera.html#getVideo">getVideo</a></li><li data-type='method'><a href="module-hardware.Camera.html#isReady">isReady</a></li><li data-type='method'><a href="module-hardware.Camera.html#open">open</a></li><li data-type='method'><a href="module-hardware.Camera.html#pause">pause</a></li><li data-type='method'><a href="module-hardware.Camera.html#record">record</a></li><li data-type='method'><a href="module-hardware.Camera.html#resume">resume</a></li><li data-type='method'><a href="module-hardware.Camera.html#stop">stop</a></li></ul></li><li><a href="module-sound.Sound.html">Sound</a><ul class='methods'><li data-type='method'><a href="module-sound.Sound.html#_getPlayer">_getPlayer</a></li><li data-type='method'><a href="module-sound.Sound.html#getDuration">getDuration</a></li><li data-type='method'><a href="module-sound.Sound.html#play">play</a></li><li data-type='method'><a href="module-sound.Sound.html#setLoops">setLoops</a></li><li data-type='method'><a href="module-sound.Sound.html#setSecs">setSecs</a></li><li data-type='method'><a href="module-sound.Sound.html#setSound">setSound</a></li><li data-type='method'><a href="module-sound.Sound.html#setVolume">setVolume</a></li><li data-type='method'><a href="module-sound.Sound.html#stop">stop</a></li></ul></li><li><a href="module-util.PsychObject.html">PsychObject</a><ul class='methods'><li data-type='method'><a href="module-util.PsychObject.html#_addAttribute">_addAttribute</a></li><li data-type='method'><a href="module-util.PsychObject.html#_setAttribute">_setAttribute</a></li><li data-type='method'><a href="module-util.PsychObject.html#emit">emit</a></li><li data-type='method'><a href="module-util.PsychObject.html#off">off</a></li><li data-type='method'><a href="module-util.PsychObject.html#on">on</a></li><li data-type='method'><a href="module-util.PsychObject.html#once">once</a></li><li data-type='method'><a href="module-util.PsychObject.html#toString">toString</a></li></ul></li><li><a href="module-visual.VisualStim.html">VisualStim</a><ul class='methods'><li data-type='method'><a href="module-visual.VisualStim.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="module-visual.VisualStim.html#_getBoundingBox_px">_getBoundingBox_px</a></li><li data-type='method'><a href="module-visual.VisualStim.html#_onChange">_onChange</a></li><li data-type='method'><a href="module-visual.VisualStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="module-visual.VisualStim.html#contains">contains</a></li><li data-type='method'><a href="module-visual.VisualStim.html#draw">draw</a></li><li data-type='method'><a href="module-visual.VisualStim.html#hide">hide</a></li><li data-type='method'><a href="module-visual.VisualStim.html#refresh">refresh</a></li><li data-type='method'><a href="module-visual.VisualStim.html#release">release</a></li><li data-type='method'><a href="module-visual.VisualStim.html#setAutoDraw">setAutoDraw</a></li><li data-type='method'><a href="module-visual.VisualStim.html#setDepth">setDepth</a></li><li data-type='method'><a href="module-visual.VisualStim.html#setOri">setOri</a></li><li data-type='method'><a href="module-visual.VisualStim.html#setPos">setPos</a></li><li data-type='method'><a href="module-visual.VisualStim.html#setSize">setSize</a></li></ul></li><li><a href="MonotonicClock.html">MonotonicClock</a><ul class='methods'><li data-type='method'><a href="MonotonicClock.html#getLastResetTime">getLastResetTime</a></li><li data-type='method'><a href="MonotonicClock.html#getTime">getTime</a></li></ul></li><li><a href="Mouse.html">Mouse</a><ul class='methods'><li data-type='method'><a href="Mouse.html#clickReset">clickReset</a></li><li data-type='method'><a href="Mouse.html#getPos">getPos</a></li><li data-type='method'><a href="Mouse.html#getPressed">getPressed</a></li><li data-type='method'><a href="Mouse.html#getRel">getRel</a></li><li data-type='method'><a href="Mouse.html#getWheelRel">getWheelRel</a></li><li data-type='method'><a href="Mouse.html#isPressedIn">isPressedIn</a></li><li data-type='method'><a href="Mouse.html#mouseMoved">mouseMoved</a></li><li data-type='method'><a href="Mouse.html#mouseMoveTime">mouseMoveTime</a></li></ul></li><li><a href="MovieStim.html">MovieStim</a><ul class='methods'><li data-type='method'><a href="MovieStim.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="MovieStim.html#_getDisplaySize">_getDisplaySize</a></li><li data-type='method'><a href="MovieStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="MovieStim.html#pause">pause</a></li><li data-type='method'><a href="MovieStim.html#play">play</a></li><li data-type='method'><a href="MovieStim.html#reset">reset</a></li><li data-type='method'><a href="MovieStim.html#seek">seek</a></li><li data-type='method'><a href="MovieStim.html#setMovie">setMovie</a></li><li data-type='method'><a href="MovieStim.html#stop">stop</a></li></ul></li><li><a href="MultiStairHandler.html">MultiStairHandler</a><ul class='methods'><li data-type='method'><a href="MultiStairHandler.html#_nextTrial">_nextTrial</a></li><li data-type='method'><a href="MultiStairHandler.html#_prepareStaircases">_prepareStaircases</a></li><li data-type='method'><a href="MultiStairHandler.html#_validateConditions">_validateConditions</a></li><li data-type='method'><a href="MultiStairHandler.html#addResponse">addResponse</a></li></ul></li><li><a href="Polygon.html">Polygon</a><ul class='methods'><li data-type='method'><a href="Polygon.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="Polygon.html#_getPixiPolygon">_getPixiPolygon</a></li><li data-type='method'><a href="Polygon.html#_getVertices_px">_getVertices_px</a></li><li data-type='method'><a href="Polygon.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="Polygon.html#contains">contains</a></li><li data-type='method'><a href="Polygon.html#setEdges">setEdges</a></li><li data-type='method'><a href="Polygon.html#setRadius">setRadius</a></li><li data-type='method'><a href="Polygon.html#setVertices">setVertices</a></li></ul></li><li><a href="QuestHandler.html">QuestHandler</a><ul class='methods'><li data-type='method'><a href="QuestHandler.html#_estimateQuestValue">_estimateQuestValue</a></li><li data-type='method'><a href="QuestHandler.html#_setupJsQuest">_setupJsQuest</a></li><li data-type='method'><a href="QuestHandler.html#addResponse">addResponse</a></li><li data-type='method'><a href="QuestHandler.html#confInterval">confInterval</a></li><li data-type='method'><a href="QuestHandler.html#getQuestValue">getQuestValue</a></li><li data-type='method'><a href="QuestHandler.html#mean">mean</a></li><li data-type='method'><a href="QuestHandler.html#mode">mode</a></li><li data-type='method'><a href="QuestHandler.html#quantile">quantile</a></li><li data-type='method'><a href="QuestHandler.html#sd">sd</a></li><li data-type='method'><a href="QuestHandler.html#setMethod">setMethod</a></li><li data-type='method'><a href="QuestHandler.html#simulate">simulate</a></li></ul></li><li><a href="Rect.html">Rect</a><ul class='methods'><li data-type='method'><a href="Rect.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="Rect.html#_getPixiPolygon">_getPixiPolygon</a></li><li data-type='method'><a href="Rect.html#_getVertices_px">_getVertices_px</a></li><li data-type='method'><a href="Rect.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="Rect.html#_updateVertices">_updateVertices</a></li><li data-type='method'><a href="Rect.html#contains">contains</a></li><li data-type='method'><a href="Rect.html#setHeight">setHeight</a></li><li data-type='method'><a href="Rect.html#setVertices">setVertices</a></li><li data-type='method'><a href="Rect.html#setWidth">setWidth</a></li></ul></li><li><a href="Scheduler.html">Scheduler</a><ul class='methods'><li data-type='method'><a href="Scheduler.html#add">add</a></li><li data-type='method'><a href="Scheduler.html#addConditional">addConditional</a></li><li data-type='method'><a href="Scheduler.html#start">start</a></li><li data-type='method'><a href="Scheduler.html#stop">stop</a></li></ul></li><li><a href="ServerManager.html">ServerManager</a><ul class='methods'><li data-type='method'><a href="ServerManager.html#_downloadResources">_downloadResources</a></li><li data-type='method'><a href="ServerManager.html#_listResources">_listResources</a></li><li data-type='method'><a href="ServerManager.html#_queryServerAPI">_queryServerAPI</a></li><li data-type='method'><a href="ServerManager.html#_setupPreloadQueue">_setupPreloadQueue</a></li><li data-type='method'><a href="ServerManager.html#closeSession">closeSession</a></li><li data-type='method'><a href="ServerManager.html#getConfiguration">getConfiguration</a></li><li data-type='method'><a href="ServerManager.html#getResource">getResource</a></li><li data-type='method'><a href="ServerManager.html#getResourceStatus">getResourceStatus</a></li><li data-type='method'><a href="ServerManager.html#openSession">openSession</a></li><li data-type='method'><a href="ServerManager.html#prepareResources">prepareResources</a></li><li data-type='method'><a href="ServerManager.html#resetStatus">resetStatus</a></li><li data-type='method'><a href="ServerManager.html#setStatus">setStatus</a></li><li data-type='method'><a href="ServerManager.html#uploadAudioVideo">uploadAudioVideo</a></li><li data-type='method'><a href="ServerManager.html#uploadData">uploadData</a></li><li data-type='method'><a href="ServerManager.html#uploadLog">uploadLog</a></li><li data-type='method'><a href="ServerManager.html#waitForResources">waitForResources</a></li></ul></li><li><a href="ShapeStim.html">ShapeStim</a><ul class='methods'><li data-type='method'><a href="ShapeStim.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="ShapeStim.html#_getPixiPolygon">_getPixiPolygon</a></li><li data-type='method'><a href="ShapeStim.html#_getVertices_px">_getVertices_px</a></li><li data-type='method'><a href="ShapeStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="ShapeStim.html#contains">contains</a></li><li data-type='method'><a href="ShapeStim.html#setVertices">setVertices</a></li></ul></li><li><a href="Shelf.html">Shelf</a><ul class='methods'><li data-type='method'><a href="Shelf.html#_checkAvailability">_checkAvailability</a></li><li data-type='method'><a href="Shelf.html#_checkKey">_checkKey</a></li><li data-type='method'><a href="Shelf.html#_getValue">_getValue</a></li><li data-type='method'><a href="Shelf.html#_updateValue">_updateValue</a></li><li data-type='method'><a href="Shelf.html#addIntegerValue">addIntegerValue</a></li><li data-type='method'><a href="Shelf.html#appendListValue">appendListValue</a></li><li data-type='method'><a href="Shelf.html#clearListValue">clearListValue</a></li><li data-type='method'><a href="Shelf.html#counterBalanceSelect">counterBalanceSelect</a></li><li data-type='method'><a href="Shelf.html#flipBooleanValue">flipBooleanValue</a></li><li data-type='method'><a href="Shelf.html#getBooleanValue">getBooleanValue</a></li><li data-type='method'><a href="Shelf.html#getDictionaryFieldNames">getDictionaryFieldNames</a></li><li data-type='method'><a href="Shelf.html#getDictionaryFieldValue">getDictionaryFieldValue</a></li><li data-type='method'><a href="Shelf.html#getDictionaryValue">getDictionaryValue</a></li><li data-type='method'><a href="Shelf.html#getIntegerValue">getIntegerValue</a></li><li data-type='method'><a href="Shelf.html#getListValue">getListValue</a></li><li data-type='method'><a href="Shelf.html#getTextValue">getTextValue</a></li><li data-type='method'><a href="Shelf.html#incrementComponent">incrementComponent</a></li><li data-type='method'><a href="Shelf.html#popListValue">popListValue</a></li><li data-type='method'><a href="Shelf.html#setBooleanValue">setBooleanValue</a></li><li data-type='method'><a href="Shelf.html#setDictionaryFieldValue">setDictionaryFieldValue</a></li><li data-type='method'><a href="Shelf.html#setDictionaryValue">setDictionaryValue</a></li><li data-type='method'><a href="Shelf.html#setIntegerValue">setIntegerValue</a></li><li data-type='method'><a href="Shelf.html#setListValue">setListValue</a></li><li data-type='method'><a href="Shelf.html#setTextValue">setTextValue</a></li><li data-type='method'><a href="Shelf.html#shuffleListValue">shuffleListValue</a></li></ul></li><li><a href="Slider.html">Slider</a><ul class='methods'><li data-type='method'><a href="Slider.html#_addEventListeners">_addEventListeners</a></li><li data-type='method'><a href="Slider.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="Slider.html#_getBoundingBox_px">_getBoundingBox_px</a></li><li data-type='method'><a href="Slider.html#_getPosition_px">_getPosition_px</a></li><li data-type='method'><a href="Slider.html#_getTextStyle">_getTextStyle</a></li><li data-type='method'><a href="Slider.html#_granularise">_granularise</a></li><li data-type='method'><a href="Slider.html#_handlePointerDown">_handlePointerDown</a></li><li data-type='method'><a href="Slider.html#_handlePointerMove">_handlePointerMove</a></li><li data-type='method'><a href="Slider.html#_handlePointerUp">_handlePointerUp</a></li><li data-type='method'><a href="Slider.html#_isHorizontal">_isHorizontal</a></li><li data-type='method'><a href="Slider.html#_onChange">_onChange</a></li><li data-type='method'><a href="Slider.html#_posToRating">_posToRating</a></li><li data-type='method'><a href="Slider.html#_ratingToPos">_ratingToPos</a></li><li data-type='method'><a href="Slider.html#_removeEventListeners">_removeEventListeners</a></li><li data-type='method'><a href="Slider.html#_sanitizeAttributes">_sanitizeAttributes</a></li><li data-type='method'><a href="Slider.html#_setupBar">_setupBar</a></li><li data-type='method'><a href="Slider.html#_setupLabels">_setupLabels</a></li><li data-type='method'><a href="Slider.html#_setupMarker">_setupMarker</a></li><li data-type='method'><a href="Slider.html#_setupSlider">_setupSlider</a></li><li data-type='method'><a href="Slider.html#_setupStyle">_setupStyle</a></li><li data-type='method'><a href="Slider.html#_setupTicks">_setupTicks</a></li><li data-type='method'><a href="Slider.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="Slider.html#contains">contains</a></li><li data-type='method'><a href="Slider.html#draw">draw</a></li><li data-type='method'><a href="Slider.html#getRating">getRating</a></li><li data-type='method'><a href="Slider.html#getRT">getRT</a></li><li data-type='method'><a href="Slider.html#hide">hide</a></li><li data-type='method'><a href="Slider.html#isMarkerDragging">isMarkerDragging</a></li><li data-type='method'><a href="Slider.html#recordRating">recordRating</a></li><li data-type='method'><a href="Slider.html#refresh">refresh</a></li><li data-type='method'><a href="Slider.html#release">release</a></li><li data-type='method'><a href="Slider.html#reset">reset</a></li><li data-type='method'><a href="Slider.html#setAutoDraw">setAutoDraw</a></li><li data-type='method'><a href="Slider.html#setDepth">setDepth</a></li><li data-type='method'><a href="Slider.html#setMarkerPos">setMarkerPos</a></li><li data-type='method'><a href="Slider.html#setOri">setOri</a></li><li data-type='method'><a href="Slider.html#setPos">setPos</a></li><li data-type='method'><a href="Slider.html#setRating">setRating</a></li><li data-type='method'><a href="Slider.html#setReadOnly">setReadOnly</a></li><li data-type='method'><a href="Slider.html#setSize">setSize</a></li></ul></li><li><a href="SpeechRecognition.html">SpeechRecognition</a><ul class='methods'><li data-type='method'><a href="SpeechRecognition.html#_onChange">_onChange</a></li><li data-type='method'><a href="SpeechRecognition.html#_prepareRecognition">_prepareRecognition</a></li><li data-type='method'><a href="SpeechRecognition.html#clearTranscripts">clearTranscripts</a></li><li data-type='method'><a href="SpeechRecognition.html#getTranscripts">getTranscripts</a></li><li data-type='method'><a href="SpeechRecognition.html#start">start</a></li><li data-type='method'><a href="SpeechRecognition.html#stop">stop</a></li></ul></li><li><a href="TextBox.html">TextBox</a><ul class='methods'><li data-type='method'><a href="TextBox.html#_addEventListeners">_addEventListeners</a></li><li data-type='method'><a href="TextBox.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="TextBox.html#_getAnchor">_getAnchor</a></li><li data-type='method'><a href="TextBox.html#_getDefaultLetterHeight">_getDefaultLetterHeight</a></li><li data-type='method'><a href="TextBox.html#_getTextInputOptions">_getTextInputOptions</a></li><li data-type='method'><a href="TextBox.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="TextBox.html#clear">clear</a></li><li data-type='method'><a href="TextBox.html#getText">getText</a></li><li data-type='method'><a href="TextBox.html#reset">reset</a></li><li data-type='method'><a href="TextBox.html#setAlignment">setAlignment</a></li><li data-type='method'><a href="TextBox.html#setAnchor">setAnchor</a></li><li data-type='method'><a href="TextBox.html#setBorderColor">setBorderColor</a></li><li data-type='method'><a href="TextBox.html#setColor">setColor</a></li><li data-type='method'><a href="TextBox.html#setFillColor">setFillColor</a></li><li data-type='method'><a href="TextBox.html#setFitToContent">setFitToContent</a></li><li data-type='method'><a href="TextBox.html#setFont">setFont</a></li><li data-type='method'><a href="TextBox.html#setLanguageStyle">setLanguageStyle</a></li><li data-type='method'><a href="TextBox.html#setLetterHeight">setLetterHeight</a></li><li data-type='method'><a href="TextBox.html#setSize">setSize</a></li><li data-type='method'><a href="TextBox.html#setText">setText</a></li></ul></li><li><a href="TextStim.html">TextStim</a><ul class='methods'><li data-type='method'><a href="TextStim.html#_estimateBoundingBox">_estimateBoundingBox</a></li><li data-type='method'><a href="TextStim.html#_getAnchor">_getAnchor</a></li><li data-type='method'><a href="TextStim.html#_getDefaultLetterHeight">_getDefaultLetterHeight</a></li><li data-type='method'><a href="TextStim.html#_getDefaultWrapWidth">_getDefaultWrapWidth</a></li><li data-type='method'><a href="TextStim.html#_getTextStyle">_getTextStyle</a></li><li data-type='method'><a href="TextStim.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="TextStim.html#getBoundingBox">getBoundingBox</a></li><li data-type='method'><a href="TextStim.html#getTextMetrics">getTextMetrics</a></li><li data-type='method'><a href="TextStim.html#setColor">setColor</a></li></ul></li><li><a href="TonePlayer.html">TonePlayer</a><ul class='methods'><li data-type='method'><a href="TonePlayer.html#_initSoundLibrary">_initSoundLibrary</a></li><li data-type='method'><a href="TonePlayer.html#getDuration">getDuration</a></li><li data-type='method'><a href="TonePlayer.html#play">play</a></li><li data-type='method'><a href="TonePlayer.html#setDuration">setDuration</a></li><li data-type='method'><a href="TonePlayer.html#setLoops">setLoops</a></li><li data-type='method'><a href="TonePlayer.html#setVolume">setVolume</a></li><li data-type='method'><a href="TonePlayer.html#stop">stop</a></li></ul></li><li><a href="TrackPlayer.html">TrackPlayer</a><ul class='methods'><li data-type='method'><a href="TrackPlayer.html#getDuration">getDuration</a></li><li data-type='method'><a href="TrackPlayer.html#play">play</a></li><li data-type='method'><a href="TrackPlayer.html#setDuration">setDuration</a></li><li data-type='method'><a href="TrackPlayer.html#setLoops">setLoops</a></li><li data-type='method'><a href="TrackPlayer.html#setVolume">setVolume</a></li><li data-type='method'><a href="TrackPlayer.html#stop">stop</a></li></ul></li><li><a href="Transcript.html">Transcript</a></li><li><a href="Window.html">Window</a><ul class='methods'><li data-type='method'><a href="Window.html#_fullRefresh">_fullRefresh</a></li><li data-type='method'><a href="Window.html#_refresh">_refresh</a></li><li data-type='method'><a href="Window.html#_setupPixi">_setupPixi</a></li><li data-type='method'><a href="Window.html#_updateIfNeeded">_updateIfNeeded</a></li><li data-type='method'><a href="Window.html#_writeLogOnFlip">_writeLogOnFlip</a></li><li data-type='method'><a href="Window.html#addPixiObject">addPixiObject</a></li><li data-type='method'><a href="Window.html#adjustScreenSize">adjustScreenSize</a></li><li data-type='method'><a href="Window.html#callOnFlip">callOnFlip</a></li><li data-type='method'><a href="Window.html#close">close</a></li><li data-type='method'><a href="Window.html#closeFullScreen">closeFullScreen</a></li><li data-type='method'><a href="Window.html#getActualFrameRate">getActualFrameRate</a></li><li data-type='method'><a href="Window.html#logOnFlip">logOnFlip</a></li><li data-type='method'><a href="Window.html#removePixiObject">removePixiObject</a></li><li data-type='method'><a href="Window.html#render">render</a></li></ul></li></ul><h3>Interfaces</h3><ul><li><a href="SoundPlayer.html">SoundPlayer</a><ul class='methods'><li data-type='method'><a href="SoundPlayer.html#getDuration">getDuration</a></li><li data-type='method'><a href="SoundPlayer.html#play">play</a></li><li data-type='method'><a href="SoundPlayer.html#setDuration">setDuration</a></li><li data-type='method'><a href="SoundPlayer.html#setLoops">setLoops</a></li><li data-type='method'><a href="SoundPlayer.html#setVolume">setVolume</a></li><li data-type='method'><a href="SoundPlayer.html#stop">stop</a></li></ul></li></ul><h3>Mixins</h3><ul><li><a href="module-core.WindowMixin.html">WindowMixin</a><ul class='methods'><li data-type='method'><a href="module-core.WindowMixin.html#_getHorLengthPix">_getHorLengthPix</a></li><li data-type='method'><a href="module-core.WindowMixin.html#_getLengthPix">_getLengthPix</a></li><li data-type='method'><a href="module-core.WindowMixin.html#_getLengthUnits">_getLengthUnits</a></li><li data-type='method'><a href="module-core.WindowMixin.html#_getVerLengthPix">_getVerLengthPix</a></li></ul></li><li><a href="module-util.ColorMixin.html">ColorMixin</a><ul class='methods'><li data-type='method'><a href="module-util.ColorMixin.html#getContrastedColor">getContrastedColor</a></li><li data-type='method'><a href="module-util.ColorMixin.html#setColor">setColor</a></li><li data-type='method'><a href="module-util.ColorMixin.html#setContrast">setContrast</a></li></ul></li></ul>
</nav>
<div id="main">
<h1 class="page-title">util/Util.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>/** @module util */
/**
* Various utilities.
*
* @authors Alain Pitiot, Sotiri Bakagiannis, Thomas Pronk
* @version 2022.2.3
* @copyright (c) 2017-2020 Ilixa Ltd. (http://ilixa.com) (c) 2020-2022 Open Science Tools Ltd. (https://opensciencetools.org)
* @license Distributed under the terms of the MIT License
*/
/**
* Syntactic sugar for Mixins
*
* &lt;p>This is heavily adapted from: http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/&lt;/p>
*
* @param {Object} superclass
*
* @example
* class BaseClass { ... }
* let Mixin1 = (superclass) => class extends superclass { ... }
* let Mixin2 = (superclass) => class extends superclass { ... }
* class NewClass extends mix(BaseClass).with(Mixin1, Mixin2) { ... }
*/
export let mix = (superclass) => new MixinBuilder(superclass);
class MixinBuilder
{
constructor(superclass)
{
this.superclass = superclass;
}
/**
* @param mixins
* @returns {*}
*/
with(...mixins)
{
return mixins.reduce((c, mixin) => mixin(c), this.superclass);
}
}
/**
* Convert the resulting value of a promise into a tupple.
*
* @param {Promise} promise - the promise
* @return {Object[]} the resulting value in the format [error, return data]
* where error is null if there was no error
*/
export function promiseToTupple(promise)
{
return promise
.then((data) => [null, data])
.catch((error) => [error, null]);
}
/**
* Get a Universally Unique Identifier (RFC4122 version 4)
* &lt;p> See details here: https://www.ietf.org/rfc/rfc4122.txt&lt;/p>
*
* @return {string} the uuid
*/
export function makeUuid()
{
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c)
{
const r = Math.random() * 16 | 0, v = (c === "x") ? r : (r &amp; 0x3 | 0x8);
return v.toString(16);
});
}
/**
* Get the error stack of the calling, exception-throwing function.
*
* @return {string} the error stack as a string
*/
export function getErrorStack()
{
try
{
throw Error("");
}
catch (error)
{
// we need to remove the second line since it references getErrorStack:
let stack = error.stack.split("\n");
stack.splice(1, 1);
return JSON.stringify(stack.join("\n"));
}
}
/**
* Test if x is an 'empty' value.
*
* @param {Object} x the value to test
* @return {boolean} true if x is one of the following: undefined, [], [undefined]
*/
export function isEmpty(x)
{
if (typeof x === "undefined")
{
return true;
}
if (!Array.isArray(x))
{
return false;
}
if (x.length === 0)
{
return true;
}
if (x.length === 1 &amp;&amp; typeof x[0] === "undefined")
{
return true;
}
return false;
}
/**
* Detect the user's browser.
*
* &lt;p> Note: since user agent is easily spoofed, we use a more sophisticated approach, as described here:
* https://stackoverflow.com/a/9851769&lt;/p>
*
* @return {string} the detected browser, one of 'Opera', 'Firefox', 'Safari',
* 'IE', 'Edge', 'EdgeChromium', 'Chrome', 'unknown'
*/
export function detectBrowser()
{
// Opera 8.0+
const isOpera = (!!window.opr &amp;&amp; !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(" OPR/") >= 0;
if (isOpera)
{
return "Opera";
}
// Firefox 1.0+
const isFirefox = (typeof InstallTrigger !== "undefined");
if (isFirefox)
{
return "Firefox";
}
// Safari 3.0+ "[object HTMLElementConstructor]"
const isSafari = /constructor/i.test(window.HTMLElement) || (function(p)
{
return p.toString() === "[object SafariRemoteNotification]";
})(!window["safari"] || (typeof safari !== "undefined" &amp;&amp; safari.pushNotification));
if (isSafari)
{
return "Safari";
}
// Internet Explorer 6-11
// const isIE6 = !window.XMLHttpRequest;
// const isIE7 = document.all &amp;&amp; window.XMLHttpRequest &amp;&amp; !XDomainRequest &amp;&amp; !window.opera;
// const isIE8 = document.documentMode==8;
const isIE = /*@cc_on!@*/ false || !!document.documentMode;
if (isIE)
{
return "IE";
}
// Edge 20+
const isEdge = !isIE &amp;&amp; !!window.StyleMedia;
if (isEdge)
{
return "Edge";
}
// Chrome 1+
const isChrome = window.chrome;
if (isChrome)
{
return "Chrome";
}
// Chromium-based Edge:
const isEdgeChromium = isChrome &amp;&amp; (navigator.userAgent.indexOf("Edg") !== -1);
if (isEdgeChromium)
{
return "EdgeChromium";
}
// Blink engine detection
const isBlink = (isChrome || isOpera) &amp;&amp; !!window.CSS;
if (isBlink)
{
return "Blink";
}
return "unknown";
}
/**
* Convert obj to its numerical form.
*
* &lt;ul>
* &lt;li>number -> number, e.g. 2 -> 2&lt;/li>
* &lt;li>[number] -> [number], e.g. [1,2,3] -> [1,2,3]&lt;/li>
* &lt;li>numeral string -> number, e.g. "8" -> 8&lt;/li>
* &lt;li>[number | numeral string] -> [number], e.g. [1, 2, "3"] -> [1,2,3]&lt;/li>
* &lt;/ul>
*
* @param {Object} obj - the input object
* @return {number | number[]} the numerical form of the input object
*/
export function toNumerical(obj)
{
const response = {
origin: "util.toNumerical",
context: "when converting an object to its numerical form",
};
try
{
if (obj === null)
{
throw "unable to convert null to a number";
}
if (typeof obj === "undefined")
{
throw "unable to convert undefined to a number";
}
if (typeof obj === "number")
{
return obj;
}
const convertToNumber = (input) =>
{
const n = Number.parseFloat(input);
if (Number.isNaN(n))
{
throw `unable to convert ${input} to a number`;
}
return n;
};
if (Array.isArray(obj))
{
return obj.map(convertToNumber);
}
const arrayMaybe = turnSquareBracketsIntoArrays(obj);
if (Array.isArray(arrayMaybe))
{
return arrayMaybe.map(convertToNumber);
}
if (typeof obj === "string")
{
return convertToNumber(obj);
}
throw "unable to convert the object to a number";
}
catch (error)
{
throw Object.assign(response, { error });
}
}
/**
* Check whether a value looks like a number
*
* @param {*} input - Some value
* @return {boolean} Whether or not the value can be converted into a number
*/
export function isNumeric(input)
{
return Number.isNaN(Number(input)) === false;
}
/**
* Check whether a point lies within a polygon
* &lt;p>We are using the algorithm described here: https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html&lt;/p>
*
* @param {number[]} point - the point
* @param {Object} vertices - the vertices defining the polygon
* @return {boolean} whether or not the point lies within the polygon
*/
export function IsPointInsidePolygon(point, vertices)
{
const x = point[0];
const y = point[1];
let isInside = false;
for (let i = 0, j = vertices.length - 1; i &lt; vertices.length; j = i++)
{
const xi = vertices[i][0], yi = vertices[i][1];
const xj = vertices[j][0], yj = vertices[j][1];
const intersect = ((yi > y) !== (yj > y)) &amp;&amp; (x &lt; (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect)
{
isInside = !isInside;
}
}
return isInside;
}
/**
* Shuffle an array in place using the Fisher-Yastes's modern algorithm
* &lt;p>See details here: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm&lt;/p>
*
* @param {Object[]} array - the input 1-D array
* @param {Function} [randomNumberGenerator = undefined] - A function used to generated random numbers in the interal [0, 1). Defaults to Math.random
* @return {Object[]} the shuffled array
*/
export function shuffle(array, randomNumberGenerator = undefined)
{
if (randomNumberGenerator === undefined)
{
randomNumberGenerator = Math.random;
}
for (let i = array.length - 1; i > 0; i--)
{
const j = Math.floor(randomNumberGenerator() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
/**
* Pick a random value from an array, uses `util.shuffle` to shuffle the array and returns the last value.
*
* @param {Object[]} array - the input 1-D array
* @param {Function} [randomNumberGenerator = undefined] - A function used to generated random numbers in the interal [0, 1). Defaults to Math.random
* @return {Object[]} a chosen value from the array
*/
export function randchoice(array, randomNumberGenerator = undefined)
{
if (randomNumberGenerator === undefined)
{
randomNumberGenerator = Math.random;
}
const j = Math.floor(randomNumberGenerator() * array.length);
return array[j]
}
/**
* Get the position of the object, in pixel units
*
* @param {Object} object - the input object
* @param {string} units - the units
* @returns {number[]} the position of the object, in pixel units
*/
export function getPositionFromObject(object, units)
{
const response = {
origin: "util.getPositionFromObject",
context: "when getting the position of an object",
};
try
{
if (typeof object === "undefined")
{
throw "cannot get the position of an undefined object";
}
let objectWin = undefined;
// the object has a getPos function:
if (typeof object.getPos === "function")
{
units = object.units;
objectWin = object.win;
object = object.getPos();
}
// convert object to pixel units:
return to_px(object, units, objectWin);
}
catch (error)
{
throw Object.assign(response, { error });
}
}
/**
* Convert the position to pixel units.
*
* @param {number[]} pos - the input position
* @param {string} posUnit - the position units
* @param {Window} win - the associated Window
* @param {boolean} [integerCoordinates = false] - whether or not to round the position coordinates.
* @returns {number[]} the position in pixel units
*/
export function to_px(pos, posUnit, win, integerCoordinates = false)
{
const response = {
origin: "util.to_px",
context: "when converting a position to pixel units",
};
let pos_px;
if (posUnit === "pix")
{
pos_px = pos;
}
else if (posUnit === "norm")
{
pos_px = [pos[0] * win.size[0] / 2.0, pos[1] * win.size[1] / 2.0];
}
else if (posUnit === "height")
{
const minSize = Math.min(win.size[0], win.size[1]);
pos_px = [pos[0] * minSize, pos[1] * minSize];
}
else
{
throw Object.assign(response, { error: `unknown position units: ${posUnit}` });
}
if (integerCoordinates)
{
return [Math.round(pos_px[0]), Math.round(pos_px[1])];
}
else
{
return pos_px;
}
}
/**
* Convert the position to norm units.
*
* @param {number[]} pos - the input position
* @param {string} posUnit - the position units
* @param {Window} win - the associated Window
* @returns {number[]} the position in norm units
*/
export function to_norm(pos, posUnit, win)
{
const response = { origin: "util.to_norm", context: "when converting a position to norm units" };
if (posUnit === "norm")
{
return pos;
}
if (posUnit === "pix")
{
return [pos[0] / (win.size[0] / 2.0), pos[1] / (win.size[1] / 2.0)];
}
if (posUnit === "height")
{
const minSize = Math.min(win.size[0], win.size[1]);
return [pos[0] * minSize / (win.size[0] / 2.0), pos[1] * minSize / (win.size[1] / 2.0)];
}
throw Object.assign(response, { error: `unknown position units: ${posUnit}` });
}
/**
* Convert the position to height units.
*
* @param {number[]} pos - the input position
* @param {string} posUnit - the position units
* @param {Window} win - the associated Window
* @returns {number[]} the position in height units
*/
export function to_height(pos, posUnit, win)
{
const response = {
origin: "util.to_height",
context: "when converting a position to height units",
};
if (posUnit === "height")
{
return pos;
}
if (posUnit === "pix")
{
const minSize = Math.min(win.size[0], win.size[1]);
return [pos[0] / minSize, pos[1] / minSize];
}
if (posUnit === "norm")
{
const minSize = Math.min(win.size[0], win.size[1]);
return [pos[0] * win.size[0] / 2.0 / minSize, pos[1] * win.size[1] / 2.0 / minSize];
}
throw Object.assign(response, { error: `unknown position units: ${posUnit}` });
}
/**
* Convert the position to window units.
*
* @param {number[]} pos - the input position
* @param {string} posUnit - the position units
* @param {Window} win - the associated Window
* @returns {number[]} the position in window units
*/
export function to_win(pos, posUnit, win)
{
const response = { origin: "util.to_win", context: "when converting a position to window units" };
try
{
if (win._units === "pix")
{
return to_px(pos, posUnit, win);
}
if (win._units === "norm")
{
return to_norm(pos, posUnit, win);
}
if (win._units === "height")
{
return to_height(pos, posUnit, win);
}
throw `unknown window units: ${win._units}`;
}
catch (error)
{
throw Object.assign(response, { response, error });
}
}
/**
* Convert the position to given units.
*
* @param {number[]} pos - the input position
* @param {string} posUnit - the position units
* @param {Window} win - the associated Window
* @param {string} targetUnit - the target units
* @returns {number[]} the position in target units
*/
export function to_unit(pos, posUnit, win, targetUnit)
{
const response = { origin: "util.to_unit", context: "when converting a position to different units" };
try
{
if (targetUnit === "pix")
{
return to_px(pos, posUnit, win);
}
if (targetUnit === "norm")
{
return to_norm(pos, posUnit, win);
}
if (targetUnit === "height")
{
return to_height(pos, posUnit, win);
}
throw `unknown target units: ${targetUnit}`;
}
catch (error)
{
throw Object.assign(response, { error });
}
}
/**
* Convert an object to its string representation, taking care of symbols.
*
* &lt;p>Note: if the object is not already a string, we JSON stringify it and detect circularity.&lt;/p>
*
* @param {Object} object - the input object
* @return {string} a string representation of the object or 'Object (circular)'
*/
export function toString(object)
{
if (typeof object === "undefined")
{
return "undefined";
}
if (!object)
{
return "null";
}
if (typeof object === "string")
{
return object;
}
// if the object is a class and has a toString method:
if (object.constructor.toString().substring(0, 5) === "class" &amp;&amp; typeof object.toString === "function")
{
return object.toString();
}
try
{
const symbolReplacer = (key, value) =>
{
if (typeof value === "symbol")
{
value = Symbol.keyFor(value);
}
return value;
};
return JSON.stringify(object, symbolReplacer);
}
catch (e)
{
return "Object (circular)";
}
}
if (!String.prototype.format)
{
String.prototype.format = function()
{
var args = arguments;
return this
.replace(/{(\d+)}/g, function(match, number)
{
return typeof args[number] != "undefined" ? args[number] : match;
})
.replace(/{([$_a-zA-Z][$_a-zA-Z0-9]*)}/g, function(match, name)
{
// console.log("n=" + name + " args[0][name]=" + args[0][name]);
return args.length > 0 &amp;&amp; args[0][name] !== undefined ? args[0][name] : match;
});
};
}
/**
* Get the most informative error from the server response from a jquery server request.
*
* @param jqXHR
* @param textStatus
* @param errorThrown
*/
export function getRequestError(jqXHR, textStatus, errorThrown)
{
let errorMsg = "unknown error";
if (typeof jqXHR.responseJSON !== "undefined")
{
errorMsg = jqXHR.responseJSON;
}
else if (typeof jqXHR.responseText !== "undefined")
{
errorMsg = jqXHR.responseText;
}
else if (typeof errorThrown !== "undefined")
{
errorMsg = errorThrown;
}
return errorMsg;
}
/**
* Test whether an object is either an integer or the string representation of an integer.
* &lt;p>This is adapted from: https://stackoverflow.com/a/14794066&lt;/p>
*
* @param {Object} obj - the input object
* @returns {boolean} whether or not the object is an integer or the string representation of an integer
*/
export function isInt(obj)
{
if (isNaN(obj))
{
return false;
}
const x = parseFloat(obj);
return (x | 0) === x;
}
/**
* Get the URL parameters.
*
* @returns {URLSearchParams} the iterable URLSearchParams
*
* @example
* const urlParameters = util.getUrlParameters();
* for (const [key, value] of urlParameters)
* console.log(key + ' = ' + value);
*
*/
export function getUrlParameters()
{
const urlQuery = window.location.search.slice(1);
return new URLSearchParams(urlQuery);
/*let urlMap = new Map();
for (const entry of urlParameters)
urlMap.set(entry[0], entry[1])
return urlMap;*/
}
/**
* Add info extracted from the URL to the given dictionary.
*
* &lt;p>We exclude all URL parameters starting with a double underscore
* since those are reserved for client/server communication&lt;/p>
*
* @param {Object} info - the dictionary
*/
export function addInfoFromUrl(info)
{
const infoFromUrl = getUrlParameters();
// note: parameters starting with a double underscore are reserved for client/server communication,
// we do not add them to info
// for (const [key, value] of infoFromUrl)
infoFromUrl.forEach((value, key) =>
{
if (key.indexOf("__") !== 0)
{
info[key] = value;
}
});
return info;
}
/**
* Select values from an array.
*
* &lt;p> 'selection' can be a single integer, an array of indices, or a string to be parsed, e.g.:
* &lt;ul>
* &lt;li>5&lt;/li>
* &lt;li>[1,2,3,10]&lt;/li>
* &lt;li>'1,5,10'&lt;/li>
* &lt;li>'1:2:5'&lt;/li>
* &lt;li>'5:'&lt;/li>
* &lt;li>'-5:-2, 9, 11:5:22'&lt;/li>
* &lt;/ul>&lt;/p>
*
* @param {Array.&lt;Object>} array - the input array
* @param {number | Array.&lt;number> | string} selection - the selection
* @returns {Object | Array.&lt;Object>} the array of selected items
*/
export function selectFromArray(array, selection)
{
// if selection is an integer, or a string representing an integer, we treat it
// as an index in the array and return that entry:
if (isInt(selection))
{
return [array[parseInt(selection)]];
}
// if selection is an array, we treat it as a list of indices
// and return an array with the entries corresponding to those indices:
else if (Array.isArray(selection))
{
return selection.map( (i) => array[i] );
}
// if selection is a string:
else if (typeof selection === "string")
{
if (selection.indexOf(",") > -1)
{
const selectionAsArray = selection.split(",").map( (i) => parseInt(i) );
return selectFromArray(array, selectionAsArray);
}
else if (selection.indexOf(":") > -1)
{
let sliceParams = selection.split(":").map((a) => parseInt(a));
if (sliceParams.length === 3)
{
return sliceArray(array, sliceParams[0], sliceParams[2], sliceParams[1]);
}
else
{
return sliceArray(array, ...sliceParams);
}
}
}
else
{
throw {
origin: "selectFromArray",
context: "when selecting entries from an array",
error: "unknown selection type: " + (typeof selection),
};
}
}
/**
* Recursively flatten an array of arrays.
*
* @param {Array.&lt;Object>} array - the input array of arrays
* @returns {Array.&lt;Object>} the flatten array
*/
export function flattenArray(array)
{
return array.reduce(
(flat, next) =>
{
flat.push((Array.isArray(next) &amp;&amp; Array.isArray(next[0])) ? flattenArray(next) : next);
return flat;
},
[],
);
}
/**
* Slice an array.
*
* @param {Array.&lt;Object>} array - the input array
* @param {number} [from= NaN] - the start of the slice
* @param {number} [to= NaN] - the end of the slice
* @param {number} [step= NaN] - the step of the slice
* @returns {Array.&lt;Object>} the array slice
*/
export function sliceArray(array, from = NaN, to = NaN, step = NaN)
{
if (isNaN(from))
{
from = 0;
}
if (isNaN(to))
{
to = array.length;
}
let arraySlice = array.slice(from, to);
if (isNaN(step))
{
return arraySlice;
}
if (step &lt; 0)
{
arraySlice.reverse();
}
step = Math.abs(step);
if (step === 1)
{
return arraySlice;
}
else
{
return arraySlice.filter((e, i) => (i % step === 0));
}
}
/**
* Offer data as download in the browser.
*
* @param {string} filename - the name of the file to be downloaded
* @param {*} data - the data
* @param {string} type - the MIME type of the data, e.g. 'text/csv' or 'application/json'
*/
export function offerDataForDownload(filename, data, type)
{
const blob = new Blob([data], { type });
if (window.navigator.msSaveOrOpenBlob)
{
window.navigator.msSaveBlob(blob, filename);
}
else
{
const anchor = document.createElement("a");
anchor.href = window.URL.createObjectURL(blob);
anchor.download = filename;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
}
}
/**
* Convert a string representing a JSON array, e.g. "[1, 2]" into an array, e.g. ["1","2"].
* This approach overcomes the built-in JSON parsing limitations when it comes to eg. floats
* missing the naught prefix, and is able to process several arrays, e.g. "[1,2][3,4]".
*
* @param {string} input - string potentially containing JSON arrays
* @param {string} max - how many matches to return, unwrap resulting array if less than two
* @returns {array} an array if arrays were found, undefined otherwise
*/
export function turnSquareBracketsIntoArrays(input, max = 1)
{
// Only interested in strings
// https://stackoverflow.com/questions/4059147
if (String(input) !== input)
{
return;
}
// Matches content within square brackets (using literal
// form is MDN's advice for patterns unlikely to change)
const matchesMaybe = input.match(/\[(.*?)\]/g);
// Exit if no array-like matches found
if (matchesMaybe === null)
{
return;
}
// Reformat content for each match
const matches = matchesMaybe.map((data) =>
{
return data
// Remove the square brackets
.replace(/[\[\]]+/g, "")
// Eat up space after comma
.split(/[, ]+/);
});
if (max &lt; 2)
{
return matches[0];
}
return matches;
}
/**
* Generates random integers a-la NumPy's in the "half-open" interval [min, max). In other words, from min inclusive to max exclusive. When max is undefined, as is the case by default, results are chosen from [0, min). An error is thrown if max is less than min.
*
* @param {number} [min = 0] - lowest integer to be drawn, or highest plus one if max is undefined (default)
* @param {number} max - one above the largest integer to be drawn
* @returns {number} a random integer in the requested range (signed)
*/
export function randint(min = 0, max)
{
let lo = min;
let hi = max;
if (typeof max === "undefined")
{
hi = lo;
lo = 0;
}
if (hi &lt; lo)
{
throw {
origin: "util.randint",
context: "when generating a random integer",
error: "min should be &lt;= max",
};
}
return Math.floor(Math.random() * (hi - lo)) + lo;
}
/**
* Round to a certain number of decimal places.
*
* This is the Crib Sheet provided solution, but please note that as of 2020 the most popular SO answer is different.
*
* @see {@link https://stackoverflow.com/questions/11832914|Stack Overflow}
* @param {number} input - the number to be rounded
* @param {number} places - the max number of decimals desired
* @returns {number} input rounded to the specified number of decimal places at most
*/
export function round(input, places = 0)
{
return +(Math.round(`${input}e+${places}`) + `e-${places}`);
}
/**
* Calculate the sum of the elements in the input array.
*
* If 'input' is not an array, then we return start.
*
* @param {array} input - an array of numbers, or of objects that can be cast into a number, e.g. ['1', 2.5, 3e1]
* @param {number} start - value added to the sum of numbers (a la Python)
* @returns {number} the sum of the elements in the array + start
*/
export function sum(input = [], start = 0)
{
if (!Array.isArray(input))
{
return start;
}
const add = (a, b) => a + b;
return input
// type cast everything as a number
.map((value) => Number(value))
// drop non numeric looking entries (note: needs transpiling for IE11)
.filter((value) => Number.isNaN(value) === false)
// add up each successive entry, starting with start
.reduce(add, start);
}
/**
* Calculate the average of the elements in the input array.
*
* If 'input' is not an array, or if it is an empty array, then we return 0.
*
* @param {array} input - an array of numbers, or of objects that can be cast into a number, e.g. ['1', 2.5, 3e1]
* @returns {number} the average of the elements in the array
*/
export function average(input = [])
{
if (!Array.isArray(input))
{
return 0;
}
if (input.length === 0)
{
return 0;
}
return sum(input, 0) / input.length;
}
/**
* Sort the elements of the input array, in increasing alphabetical or numerical order.
*
* @param {array} input - an array of numbers or of strings
* @return {array} the sorted array
* @throws if 'input' is not an array, or if its elements are not consistent in types, or if they are not all either numbers or
* strings
*/
export function sort(input)
{
const response = {
origin: "util.sort",
context: "when sorting the elements of an array",
};
try
{
if (!Array.isArray(input))
{
throw "the input argument should be an array";
}
// check the type and consistency of the array, and sort it accordingly:
const isNumberArray = input.every((element) => typeof element === "number");
if (isNumberArray)
{
return input.sort((a, b) => (a - b));
}
const isStringArray = input.every((element) => typeof element === "string");
if (isStringArray)
{
return input.sort();
}
throw "the input array should either consist entirely of strings or of numbers";
}
catch (error)
{
throw { ...response, error };
}
}
/**
* Create a sequence of integers.
*
* The sequence is such that the integer at index i is: start + step * i, with i >= 0 and start + step * i &lt; stop
*
* &lt;p> Note: this is a JavaScript implement of the Python range function, which explains the unusual management of arguments.&lt;/p>
*
* @param {Number} [start=0] - the value of start
* @param {Number} stop - the value of stop
* @param {Number} [step=1] - the value of step
* @returns {Number[]} the range as an array of numbers
*/
export function range(...args)
{
const response = {
origin: "util.range",
context: "when building a range of numbers",
};
try
{
let start, stop, step;
switch (args.length)
{
case 0:
throw "at least one argument is required";
// 1 arg: start = 0, stop = arg, step = 1
case 1:
start = 0;
stop = args[0];
step = 1;
break;
// 2 args: start = arg1, stop = arg2
case 2:
start = args[0];
stop = args[1];
step = 1;
break;
// 3 args:
case 3:
start = args[0];
stop = args[1];
step = args[2];
break;
default:
throw "range requires at least one and at most 3 arguments";
}
if (!Number.isInteger(start))
{
throw "start should be an integer";
}
if (!Number.isInteger(stop))
{
throw "stop should be an integer";
}
if (!Number.isInteger(step))
{
throw "step should be an integer";
}
// if start >= stop, the range is empty:
if (start >= stop)
{
return [];
}
let result = [];
for (let i = start; i &lt; stop; i += step)
{
result.push(i);
}
return result;
}
catch (error)
{
throw { ...response, error };
}
}
/**
* Create a boolean function that compares an input element to the given value.
*
* @protected
* @param {Number|string|object|null} value the matching value
* @return {} a function that compares an input element to the given value
*/
function _match(value)
{
const response = {
origin: "util._match",
context: "when creating a function that compares an input element to the given value",
};
try
{
// function:
if (typeof value === "function")
{
throw "the value cannot be a function";
}
// NaN:
if (Number.isNaN(value))
{
return (element) => Number.isNaN(element);
}
// null:
if (value === null)
{
return (element) => element === null;
}
// object: we compare using JSON.stringify
if (typeof value === "object")
{
const jsonValue = JSON.stringify(value);
if (typeof jsonValue === "undefined")
{
throw "value could not be converted to a JSON string";
}
return (element) =>
{
const jsonElement = JSON.stringify(element);
return (jsonElement === jsonValue);
};
}
// everything else:
return (element) => element === value;
}
catch (error)
{
throw { ...response, error };
}
}
/**
* Count the number of elements in the input array that match the given value.
*
* &lt;p> Note: count is able to handle NaN, null, as well as any value convertible to a JSON string.&lt;/p>
*
* @param {array} input the input array
* @param {Number|string|object|null} value the matching value
* @returns the number of matching elements
*/
export function count(input, value)
{
const response = {
origin: "util.count",
context: "when counting how many elements in the input array match the given value",
};
try
{
if (!Array.isArray(input))
{
throw "the input argument should be an array";
}
const match = _match(value);
let nbMatches = 0;
input.forEach((element) =>
{
if (match(element))
{
++nbMatches;
}
});
return nbMatches;
}
catch (error)
{
throw { ...response, error };
}
}
/**
* Pad the given floating-point number with however many 0 needed at the start such that
* the padded integer part of the number is of the given width.
*
* @param n - the input floating-point number
* @param width - the desired width
* @returns {string} - the padded number, whose integer part has the given width
*/
export function pad(n, width = 2)
{
const integerPart = Number.parseInt(n);
let decimalPart = (n+'').match(/\.[0-9]*/);
if (!decimalPart)
{
decimalPart = '';
}
return (integerPart+'').padStart(width,'0') + decimalPart;
}
/**
* Get the index in the input array of the first element that matches the given value.
*
* &lt;p> Note: index is able to handle NaN, null, as well as any value convertible to a JSON string.&lt;/p>
*
* @param {array} input the input array
* @param {Number|string|object|null} value the matching value
* @returns the index of the first element that matches the value
* @throws if the input array does not contain any matching element
*/
export function index(input, value)
{
const response = {
origin: "util.index",
context: "when getting the index in the input array of the first element that matches the given value",
};
try
{
if (!Array.isArray(input))
{
throw "the input argument should be an array";
}
const match = _match(value);
const index = input.findIndex(match);
if (index === -1)
{
throw "no element in the input array matches the value";
}
return index;
}
catch (error)
{
throw { ...response, error };
}
}
/**
* Return the file extension corresponding to an audio mime type.
* If the provided mimeType is not a string (e.g. null, undefined, an array)
* or unknown, then '.dat' is returned, instead of throwing an exception.
*
* @param {string} mimeType the MIME type, e.g. 'audio/webm;codecs=opus'
* @return {string} the corresponding file extension, e.g. '.webm'
*/
export function extensionFromMimeType(mimeType)
{
if (typeof mimeType !== "string")
{
return ".dat";
}
if (mimeType.indexOf("audio/webm") === 0)
{
return ".webm";
}
if (mimeType.indexOf("audio/ogg") === 0)
{
return ".ogg";
}
if (mimeType.indexOf("audio/wav") === 0)
{
return ".wav";
}
if (mimeType.indexOf("video/webm") === 0)
{
return ".webm";
}
return ".dat";
}
/**
* Get an estimate of the download speed, by repeatedly downloading an image file from a distant
* server.
*
* @param {PsychoJS} psychoJS the instance of PsychoJS
* @param {number} [nbDownloads = 1] the number of image downloads over which to average
* the download speed
* @return {number} the download speed, in megabits per second
*/
export async function getDownloadSpeed(psychoJS, nbDownloads = 1)
{
// url of the image to download and size of the image in bits:
// TODO use a variety of files, with different sizes
const imageUrl = "https://upload.wikimedia.org/wikipedia/commons/a/a6/Brandenburger_Tor_abends.jpg";
const imageSize_b = 2707459 * 8;
return new Promise( (resolve, reject) =>
{
let downloadTimeAccumulator = 0;
let downloadCounter = 0;
const download = new Image();
download.onload = () =>
{
const toc = performance.now();
downloadTimeAccumulator += (toc-tic);
++ downloadCounter;
if (downloadCounter === nbDownloads)
{
const speed_bps = (imageSize_b * nbDownloads) / (downloadTimeAccumulator / 1000);
resolve(speed_bps / 1024 / 1024);
}
else
{
tic = performance.now();
download.src = `${imageUrl}?salt=${tic}`;
}
}
download.onerror = (event) =>
{
const errorMsg = `unable to estimate the download speed: ${JSON.stringify(event)}`;
psychoJS.logger.error(errorMsg);
reject(errorMsg);
}
let tic = performance.now();
download.src = `${imageUrl}?salt=${tic}`;
});
}
/**
* Enum that stores possible text directions.
* Note that Arabic is the same as RTL but added here to support PsychoPy's
* languageStyle enum. Arabic reshaping is handled by the browser automatically.
*
* @enum
*/
export const TEXT_DIRECTION = {
LTR: "ltr",
RTL: "rtl",
Arabic: "rtl"
};
</code></pre>
</article>
</section>
</div>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.6.7</a> on Mon Aug 01 2022 10:19:55 GMT+0200 (Central European Summer Time) using the <a href="https://github.com/clenemt/docdash">docdash</a> theme.
</footer>
<script>prettyPrint();</script>
<script src="scripts/polyfill.js"></script>
<script src="scripts/linenumber.js"></script>
<script src="scripts/search.js" defer></script>
</body>
</html>