Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

*Questions 1 - 3 are based on the original index.html source code provided by the instructor. Questions 4 5 are based on the server.js source

*Questions 1 - 3 are based on the original index.html source code provided by the instructor. Questions 4 5 are based on the server.js source code.

Question 1: What type of variable is langs, is it an integer, a float, a boolean, a string, or an array?

Question 2: What do you think webkitSpeechRecognition is on line 225? Do you think this mysterious thing exists only in Chrome web browser? Why?

Question 3: What do you think the recognition variable is? How many events and their corresponding handlers are registered with this object? What are they?

Question 4: Can you point out where the in the server.js file the feedback is logged in the Node server console? (You can type the code out or give the line number.)

Question 5: What do I need to change if I want this web application to run on localhost port 3333 instead of port 5000? (Which line to change? How will you change it?)

index.html

html> <meta charset="utf-8"> <title>Web Speech API Demonstrationtitle> <style> * { font-family: Verdana, Arial, sans-serif; } a:link { color:#000; text-decoration: none; } a:visited { color:#000; } a:hover { color:#33F; } .button { background: -webkit-linear-gradient(top,#008dfd 0,#0370ea 100%); border: 1px solid #076bd2; border-radius: 3px; color: #fff; display: none; font-size: 13px; font-weight: bold; line-height: 1.3; padding: 8px 25px; text-align: center; text-shadow: 1px 1px 1px #076bd2; letter-spacing: normal; } .center { padding: 10px; text-align: center; } .final { color: black; padding-right: 3px; } .interim { color: gray; } .info { font-size: 14px; text-align: center; color: #777; display: none; } .right { float: right; } .sidebyside { display: inline-block; width: 45%; min-height: 40px; text-align: left; vertical-align: top; } #headline { font-size: 40px; font-weight: 300; } #info { font-size: 20px; text-align: center; color: #777; visibility: hidden; } #results { font-size: 14px; font-weight: bold; border: 1px solid #ddd; padding: 15px; text-align: left; min-height: 150px; } #start_button { border: 0; background-color:transparent; padding: 0; } style> <h1 class="center" id="headline"> <a href="http://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html"> Wake Tech Credit Union (WTCU) Customer Feedbacka>h1> <div id="info"> <p id="info_start">We would like to hear from you.p> <p id="info_speak_now">Speak now.p> <p id="info_no_speech">No speech was detected. You may need to adjust your <a href="//support.google.com/chrome/bin/answer.py?hl=en&answer=1407892"> microphone settingsa>.p> <p id="info_no_microphone" style="display:none"> No microphone was found. Ensure that a microphone is installed and that <a href="//support.google.com/chrome/bin/answer.py?hl=en&answer=1407892"> microphone settingsa> are configured correctly.p> <p id="info_allow">Click the "Allow" button above to enable your microphone.p> <p id="info_denied">Permission to use microphone was denied.p> <p id="info_blocked">Permission to use microphone is blocked. To change, go to chrome://settings/contentExceptions#media-streamp> <p id="info_upgrade">Web Speech API is not supported by this browser. Upgrade to <a href="//www.google.com/chrome">Chromea> version 25 or later.p> div> <div class="right"> <button id="start_button" onclick="startButton(event)"> <img id="start_img" src="mic.gif" alt="Start">button> div> <div id="results"> <span id="final_span" class="final">span> <span id="interim_span" class="interim">span> <p> div> <div class="center"> <div class="sidebyside" style="text-align:right"> <button id="copy_button" class="button" onclick="copyButton()"> Copy and Pastebutton> <div id="copy_info" class="info"> Press Control-C to copy text.<br>(Command-C on Mac.) div> div> <div class="sidebyside"> <button id="email_button" class="button" onclick="emailButton()"> Create Emailbutton> <div id="email_info" class="info"> Text sent to default email application.<br> (See chrome://settings/handlers to change.) div> div> <p> <div id="div_language"> <select id="select_language" onchange="updateCountry()">select> <select id="select_dialect">select> div> div> <script> var langs = [['Afrikaans', ['af-ZA']], ['Bahasa Indonesia',['id-ID']], ['Bahasa Melayu', ['ms-MY']], ['Catal', ['ca-ES']], ['etina', ['cs-CZ']], ['Deutsch', ['de-DE']], ['English', ['en-AU', 'Australia'], ['en-CA', 'Canada'], ['en-IN', 'India'], ['en-NZ', 'New Zealand'], ['en-ZA', 'South Africa'], ['en-GB', 'United Kingdom'], ['en-US', 'United States']], ['Espaol', ['es-AR', 'Argentina'], ['es-BO', 'Bolivia'], ['es-CL', 'Chile'], ['es-CO', 'Colombia'], ['es-CR', 'Costa Rica'], ['es-EC', 'Ecuador'], ['es-SV', 'El Salvador'], ['es-ES', 'Espaa'], ['es-US', 'Estados Unidos'], ['es-GT', 'Guatemala'], ['es-HN', 'Honduras'], ['es-MX', 'Mxico'], ['es-NI', 'Nicaragua'], ['es-PA', 'Panam'], ['es-PY', 'Paraguay'], ['es-PE', 'Per'], ['es-PR', 'Puerto Rico'], ['es-DO', 'Repblica Dominicana'], ['es-UY', 'Uruguay'], ['es-VE', 'Venezuela']], ['Euskara', ['eu-ES']], ['Franais', ['fr-FR']], ['Galego', ['gl-ES']], ['Hrvatski', ['hr_HR']], ['IsiZulu', ['zu-ZA']], ['slenska', ['is-IS']], ['Italiano', ['it-IT', 'Italia'], ['it-CH', 'Svizzera']], ['Magyar', ['hu-HU']], ['Nederlands', ['nl-NL']], ['Norsk bokml', ['nb-NO']], ['Polski', ['pl-PL']], ['Portugus', ['pt-BR', 'Brasil'], ['pt-PT', 'Portugal']], ['Romn', ['ro-RO']], ['Slovenina', ['sk-SK']], ['Suomi', ['fi-FI']], ['Svenska', ['sv-SE']], ['Trke', ['tr-TR']], ['', ['bg-BG']], ['P', ['ru-RU']], ['', ['sr-RS']], ['', ['ko-KR']], ['', ['cmn-Hans-CN', ' ()'], ['cmn-Hans-HK', ' ()'], ['cmn-Hant-TW', ' ()'], ['yue-Hant-HK', ' ()']], ['', ['ja-JP']], ['Lingua latna', ['la']]]; for (var i = 0; i < langs.length; i++) { select_language.options[i] = new Option(langs[i][0], i); } select_language.selectedIndex = 6; updateCountry(); select_dialect.selectedIndex = 6; showInfo('info_start'); function updateCountry() { for (var i = select_dialect.options.length - 1; i >= 0; i--) { select_dialect.remove(i); } var list = langs[select_language.selectedIndex]; for (var i = 1; i < list.length; i++) { select_dialect.options.add(new Option(list[i][1], list[i][0])); } select_dialect.style.visibility = list[1].length == 1 ? 'hidden' : 'visible'; } var create_email = false; var final_transcript = ''; var recognizing = false; var ignore_onend; var start_timestamp; if (!('webkitSpeechRecognition' in window)) { upgrade(); } else { start_button.style.display = 'inline-block'; var recognition = new webkitSpeechRecognition(); recognition.continuous = true; recognition.interimResults = true; recognition.onstart = function() { recognizing = true; showInfo('info_speak_now'); start_img.src = 'mic-animate.gif'; }; recognition.onerror = function(event) { if (event.error == 'no-speech') { start_img.src = 'mic.gif'; showInfo('info_no_speech'); ignore_onend = true; } if (event.error == 'audio-capture') { start_img.src = 'mic.gif'; showInfo('info_no_microphone'); ignore_onend = true; } if (event.error == 'not-allowed') { if (event.timeStamp - start_timestamp < 100) { showInfo('info_blocked'); } else { showInfo('info_denied'); } ignore_onend = true; } }; recognition.onend = function() { recognizing = false; if (ignore_onend) { return; } start_img.src = 'mic.gif'; if (!final_transcript) { showInfo('info_start'); return; } showInfo(''); if (window.getSelection) { window.getSelection().removeAllRanges(); var range = document.createRange(); range.selectNode(document.getElementById('final_span')); window.getSelection().addRange(range); } if (create_email) { create_email = false; createEmail(); } }; recognition.onresult = function(event) { var interim_transcript = ''; for (var i = event.resultIndex; i < event.results.length; ++i) { if (event.results[i].isFinal) { final_transcript += event.results[i][0].transcript; } else { interim_transcript += event.results[i][0].transcript; } } final_transcript = capitalize(final_transcript); final_span.innerHTML = linebreak(final_transcript); interim_span.innerHTML = linebreak(interim_transcript); if (final_transcript || interim_transcript) { showButtons('inline-block'); } }; } function upgrade() { start_button.style.visibility = 'hidden'; showInfo('info_upgrade'); } var two_line = / /g; var one_line = / /g; function linebreak(s) { return s.replace(two_line, '

').replace(one_line, ' '); } var first_char = /\S/; function capitalize(s) { return s.replace(first_char, function(m) { return m.toUpperCase(); }); } function createEmail() { var n = final_transcript.indexOf(' '); if (n < 0 || n >= 80) { n = 40 + final_transcript.substring(40).indexOf(' '); } var subject = encodeURI(final_transcript.substring(0, n)); var body = encodeURI(final_transcript.substring(n + 1)); window.location.href = 'mailto:?subject=' + subject + '&body=' + body; } function copyButton() { if (recognizing) { recognizing = false; recognition.stop(); } copy_button.style.display = 'none'; copy_info.style.display = 'inline-block'; showInfo(''); } function emailButton() { if (recognizing) { create_email = true; recognizing = false; recognition.stop(); } else { createEmail(); } email_button.style.display = 'none'; email_info.style.display = 'inline-block'; showInfo(''); } function startButton(event) { if (recognizing) { recognition.stop(); return; } final_transcript = ''; recognition.lang = select_dialect.value; recognition.start(); ignore_onend = false; final_span.innerHTML = ''; interim_span.innerHTML = ''; start_img.src = 'mic-slash.gif'; showInfo('info_allow'); showButtons('none'); start_timestamp = event.timeStamp; } function showInfo(s) { if (s) { for (var child = info.firstChild; child; child = child.nextSibling) { if (child.style) { child.style.display = child.id == s ? 'inline' : 'none'; } } info.style.visibility = 'visible'; } else { info.style.visibility = 'hidden'; } } var current_style; function showButtons(style) { if (style == current_style) { return; } current_style = style; copy_button.style.display = style; email_button.style.display = style; copy_info.style.display = 'none'; email_info.style.display = 'none'; } script>

server.js

#!/bin/env node // OpenShift sample Node application var express = require('express'); var fs = require('fs'); /**  * Define the sample application.  */ var SampleApp = function() { // Scope.  var self = this; /* ================================================================ */  /* Helper functions. */  /* ================================================================ */   /**  * Set up server IP address and port # using env variables/defaults.  */  self.setupVariables = function() { // Set the environment variables we need.  //self.ipaddress = process.env.IP;  //self.port = process.env.PORT || 5000;   //if (typeof self.ipaddress === "undefined") {  // self.ipaddress = "127.0.0.1";  //};  }; /**  * Populate the cache.  */  self.populateCache = function() { if (typeof self.zcache === "undefined") { self.zcache = { 'index.html': '' }; } // Local cache for static content.  self.zcache['index.html'] = fs.readFileSync('./index.html'); }; /**  * Retrieve entry (content) from cache.  * @param {string} key Key identifying content to retrieve from cache.  */  self.cache_get = function(key) { return self.zcache[key]; }; /**  * terminator === the termination handler  * Terminate server on receipt of the specified signal.  * @param {string} sig Signal to terminate on.  */  self.terminator = function(sig){ if (typeof sig === "string") { console.log('%s: Received %s - terminating sample app ...', Date(Date.now()), sig); process.exit(1); } console.log('%s: Node server stopped.', Date(Date.now()) ); }; /**  * Setup termination handlers (for exit and a list of signals).  */  self.setupTerminationHandlers = function(){ // Process on exit and signals.  process.on('exit', function() { self.terminator(); }); // Removed 'SIGPIPE' from the list - bugz 852598.  ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'  ].forEach(function(element, index, array) { process.on(element, function() { self.terminator(element); }); }); }; /* ================================================================ */  /* App server functions (main app logic here). */  /* ================================================================ */   /**  * Create the routing table entries + handlers for the application.  */  self.createRoutes = function() { self.routes = { }; self.routes['/feedback'] = function(req, res) { console.log("-- Received a customer feedback: [" + req.body.feedback + "]"); res.send("WTCU Feedback
Thanks for your feedback!
"
); }; self.routes['/'] = function(req, res) { res.setHeader('Content-Type', 'text/html'); res.send(self.cache_get('index.html') ); }; }; /** * Initialize the server (express) and create the routes and register * the handlers. */ self.initializeServer = function() { self.createRoutes(); //self.app = express.createServer(); self.app = express(); self.app.set('port', process.env.PORT || 5000); self.app.set('ip', process.env.IP || "127.0.0.1"); self.app.use(express.static(__dirname)); //self.app.use(express.bodyParser()); self.app.use(express.json()); self.app.use(express.urlencoded()); // Add handlers for the app (from the routes). for (var r in self.routes) { self.app.get(r, self.routes[r]); // maps the HTTP GET request self.app.post(r, self.routes[r]); // maps the HTTP POST request } }; /** * Initializes the sample application. */ self.initialize = function() { self.setupVariables(); self.populateCache(); self.setupTerminationHandlers(); // Create the express server and routes. self.initializeServer(); }; /** * Start the server (starts up the sample application). */ self.start = function() { // Start the app on the specific interface (and port). self.app.listen(self.app.get('port'), function() { console.log('%s: Node server started on %s:%d ...', Date(Date.now() ), self.app.get('ip'), self.app.get('port')); }); }; }; /* Sample Application. */ /** * main(): Main code. */ var zapp = new SampleApp(); zapp.initialize(); zapp.start();

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Graph Database Modeling With Neo4j

Authors: Ajit Singh

2nd Edition

B0BDWT2XLR, 979-8351798783

More Books

Students also viewed these Databases questions