How to clear terminal using short cut key in java script - javascript

This is GDS command to run on Travelport terminal through API. Every command provide a response and after type clear terminal would be cleaned but same I need using shortcut(ctr+any key)
Command.GDS = {
getFsCallback: function(input, output, response_result) {
setTimeout( function() {
window.scrollTo( {
top: 300000,
behavior: "smooth"
});
}, 1000 );
var gds_provider = $('#gds_provider').val();
var gds_output = build_api_call(gds_provider, input.join(" "));
$('#overlay').fadeOut();
if (input == 'clear') {
return output.clear();
}
if(gds_output == 'Enter Password <br><br>'){
$("#cmdline").attr("type","Password");
}else{
$("#cmdline").attr("type","text");
} this.clear = function() {
outputElement.innerHTML = '';
return this;
};
};
return output.write(gds_output);
return function() {
// Add Dir
Terminal.Filesystem.pwd.getDirectory(input[1], {create: true}, function() {}, Terminal.FilesystemErrorHandler);
};
}
};
This is my js code
this.clear = function() {
outputElement.innerHTML = '';
return this;
};
};
Please any help would be appreciated
I would like to clean terminal using any shortcut key like using(ctr+Q) or any of (ctr+key)
Thanks

You can add a key event listener to the document and detect the combination of the "Ctrl" key and the desired key. If the combination is pressed, you can call the clear function to clear the terminal output
document.addEventListener("keydown", function(event) {
if (event.ctrlKey && event.code === "KeyQ") {
outputElement.innerHTML = '';
}
});
replace "KeyQ" with the desired key code that you want to use as the shortcut

Related

WebRTC-Problem: Cannot create answer in stable (no Chrome but AJAX signalizing involved)

can somebody help me out a little? I am a little stuck.
I am trying to write a signaling process with ajax and a database involved (this is just for learning the basics of WebRTC for now).
I am receiving the SDP fine from the JSON-object as it seems, but then I always get an error "Cannot create answer in stable" when I try to create an answer in get_remote_offer() for pc_partner.
I am pretty sure it is something obvious, but I am pretty new to WebRTC and just can't see what.
I am using Firefox here and just trying to connect two instances of it (one in private mode, one in "normal" mode, but I am trying to make it work for remote users.
This is my code:
var opt;
var video_el_partner;
var video_el_local;
var pc_partner;
var pc_local;
var interval_gro;
var remote_offer_available = false;
var service_url = "https://xyz.de/webrtc";
var pwd = "xxx";
var signaling_url = "https://xyz.de/webrtc/sdp_transfer.php";
function init_stream(video_partner_id, video_local_id, allow_video, allow_audio){
if (location.protocol === 'https:') { // only possible for https!
pc_local = new RTCPeerConnection();
pc_partner = new RTCPeerConnection();
if(document.getElementById(video_partner_id) != null){
video_el_partner = document.getElementById(video_partner_id);
video_el_local = document.getElementById(video_local_id);
if(allow_video == null){
allow_video = true;
}
if(allow_audio == null){
allow_audio = true;
}
opt = { audio: allow_audio, video: allow_video };
if(typeof navigator != 'undefined' && typeof navigator.mediaDevices != 'undefined' && navigator.mediaDevices.getUserMedia != null){
navigator.mediaDevices.getUserMedia(opt).then (
function (this_stream){
// local video directly into video element:
video_el_local.srcObject = this_stream;
// remote one is more insteresting:
pc_local.addStream(this_stream);
pc_local.createOffer().then(
function (this_sdp) {
// sdp (session dependend protocol object) is now available... this would need to go to a server somehow now.
// they use socket.io for that... maybe I can use my own thing to do that?
pc_local.setLocalDescription(this_sdp);
var this_sdp_json = JSON.stringify(this_sdp)
var params_ins = "mode=insert_offer&sdp_con=" + this_sdp_json + "&pass=" + pwd + "&service_url=" + service_url;
ajax_request_simple (
signaling_url,
params_ins,
function (res_ins) {
// insert done. Lets read for another candidate.
console.log('Set Interval!');
interval_gro = window.setInterval('get_remote_offer();', 5000);
}
);
}
);
}
).catch(
function (error) {
console.log('Problem: ');
console.log(error);
}
);
} else {
console.log("navgiator or navigator.mediaDevices is not defined.");
}
}
} else {
console.log('init_stream(): We can only do anything like that on https-connections! Http is not supported by the browser!');
}
}
window.onload = function () {
document.getElementById('button_start_stream').onclick = function () {
init_stream('video_partner', 'video_local', true, false);
}
}
function is_json_str(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
function get_remote_offer() {
var params_read = "mode=get_offer&pass=" + pwd + "&service_url=" + service_url;
ajax_request_simple (
signaling_url,
params_read,
function (res_read) {
// done.
if(is_json_str(res_read)){
// seems like we get one now.
// lets use that to connect and stream the video to the remote view.
var partner_offer = res_read;
partner_offer = JSON.parse(partner_offer);
// clear interval if found.
window.clearInterval(interval_gro);
console.log('Cleared Interval. Found!');
pc_local.setRemoteDescription(
new RTCSessionDescription(partner_offer), function(){
// video_el_partner.srcObject = event.stream;
pc_local.onicecandidate = function (e) {
if ( e.candidate != null ) {
pc_partner.addIceCandidate( new RTCIceCandidate(e.candidate) );
}
};
pc_partner.onicecandidate = function (e) {
if ( e.candidate != null ) {
pc_local.addIceCandidate( new RTCIceCandidate(e.candidate) );
}
};
pc_partner.createAnswer(
function (offer) {
pc_local.setRemoteDescription(offer);
pc_partner.setLocalDescription(offer);
}
);
// pc_local.ontrack = function (evt) {
// video_el_local.srcObject = evt.stream;
// };
pc_partner.ontrack = function (evt) {
video_el_partner.srcObject = evt.stream;
};
},
function(e) {
console.log("Problem while doing client-answer: ", e);
}
);
} else {
console.log("Can not parse: ");
console.log(res_read);
}
}
);
}
Sorry for the mix of promises and callbacks... I tried a couple of things out just in case... when it is working I will rewrite the callback parts.
Thank you very much in advance for any hint you can give me :).
Best regards and thanks for reading till now ;).
Fuchur

stop an IIFE from execution if a condition occurs

I'm trying to build an application that plans for the user's week, everything is going Ok except one thing when the user inputs a duplicated time an error shows up but my problem is the application is still running the plan shows up in the UI.
so I tried to use the return keyword to prevent the app from continue working but that didn't do the trick so here is my code:
JavaScript:
var internalController = (function(UICtrl) {
var Plan = function(id, from, to, text, goingToCkecked) {
this.id = id;
this.from = from;
this.to = to;
this.text = text;
this.goingToCkecked = goingToCkecked;
};
var data = {
Monday: [],
Tuesday: [],
Wednesday: [],
Thursday: [],
Friday: [],
Saturday: [],
Sunday: []
};
//the array of the from inputs
var fromT = [];
//the array of the to inputs
var toT = [];
var Dom = UICtrl.getDOMstrings();
function removeError(x, y) {
document.querySelector(x).style.visibility = "hidden";
document.querySelector(y).classList.remove("error-red");
}
function showER() {
document.querySelector(Dom.errorCase).style.visibility = "visible";
document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "the \" From time \" is already chosen";
document.querySelector(Dom.inputTimeF).classList.add("error-red");
}
var exit;
return {
refuseDuplicatedPlans: function(from, to) {
var exit;
if (fromT.indexOf(from) === -1) {
fromT.push(from);
exit = false;
} else {
console.log('value already exist');
showER();
exit = true;
}
}
};
})(UIController);
var controller = (function(interCtrl, UICtrl) {
var input, newPlan, DOM;
DOM = UICtrl.getDOMstrings();
function setupEventListeners() {
document.querySelector(DOM.inputBtn).addEventListener("click", ctrlAddPlans);
document.addEventListener("keypress", function(e) {
if (e.keyCode === 13) {
document.activeElement.blur();
ctrlAddPlans();
}
});
}
function removeFocus() {
console.log('remove Focus got trigered');
document.querySelector(DOM.inputTimeF, DOM.inputTimeT, DOM.inputText).addEventListener("focus", function() {
// document.activeElement.blur();
console.log("hello world");
});
}
var ctrlAddPlans = function() {
//3.get the filed input data
input = UICtrl.getInput();
console.log(input);
// 4.Refuse duplicated plans
interCtrl.refuseDuplicatedPlans(input.inputTimeF, input.inputTimeT);
//5.add the plan to the internalController
newPlan = interCtrl.addItem(input.inputDay, input.inputTimeF, input.inputTimeT, input.inputText, input.goingToCkecked);
//6.add the plan to the UI
UICtrl.addPlanList(newPlan, input.inputDay);
//7.clear the fields;
interCtrl.clearFields(UICtrl.getDOMstrings().inputTimeF, UICtrl.getDOMstrings().inputTimeT, UICtrl.getDOMstrings().inputText);
};
return {
init: function() {
console.log('the app has started');
setupEventListeners();
},
};
})(internalController, UIController);
controller.init();
I want the short circuit to be in the controller module after the refuseDuplicatedPlans() method of course if it returns true I want the module to stop it's execution and thank you in advance guys.
Your refuseDuplicatedPlans() method do not return anything right now. Please add a return statement to it as
refuseDuplicatedPlans: function(from, to) {
var exit;
if (fromT.indexOf(from) === -1) {
fromT.push(from);
exit=false;
} else {
console.log('value already exist');
showER();
exit=true;
}
return exit;
}
After that you can put your if else call and stop execution if true.
if(interCtrl.refuseDuplicatedPlans(input.inputTimeF, input.inputTimeT)){
reutrn;
}

Trying to convert existing synchronous XmlHttpRequest object to be asynchronous to keep up with current fads

Soo, I keep getting slammed with cautions from Chrome about how synchronous XmlHttpRequest calls are being deprecated, and I've decided to have a go at trying to convert my use-case over in order to keep up with this fad...
In this case, I have an ~9 year old JS object that has been used as the central (and exemplary) means of transporting data between the server and our web-based applications using synchronous XHR calls. I've created a chopped-down version to post here (by gutting out a lot of sanity, safety and syntax checking):
function GlobalData()
{
this.protocol = "https://";
this.adminPHP = "DataMgmt.php";
this.ajax = false;
this.sessionId = "123456789AB";
this.validSession = true;
this.baseLocation = "http://www.example.com/";
this.loadResult = null;
this.AjaxPrep = function()
{
this.ajax = false;
if (window.XMLHttpRequest) {
try { this.ajax = new XMLHttpRequest(); } catch(e) { this.ajax = false; } }
}
this.FetchData = function (strUrl)
{
if ((typeof strURL=='string') && (strURL.length > 0))
{
if (this.ajax === false)
{
this.AjaxPrep();
if (this.ajax === false) { alert('Unable to initialise AJAX!'); return ""; }
}
strURL = strURL.replace("http://",this.protocol); // We'll only ask for data from secure (encrypted-channel) locations...
if (strURL.indexOf(this.protocol) < 0) strURL = this.protocol + this.adminPHP + strURL;
strURL += ((strURL.indexOf('?')>= 0) ? '&' : '?') + 'dynamicdata=' + Math.floor(Math.random() * this.sessionId);
if (this.validSession) strURL += "&sessionId=" + this.sessionId;
this.ajax.open("GET", strURL, false);
this.ajax.send();
if (this.ajax.status==200) strResult = this.ajax.responseText;
else alert("There was an error attempting to communicate with the server!\r\n\r\n(" + this.ajax.status + ") " + strURL);
if (strResult == "result = \"No valid Session information was provided.\";")
{
alert('Your session is no longer valid!');
window.location.href = this.baseLocation;
}
}
else console.log('Invalid data was passed to the Global.FetchData() function. [Ajax.obj.js line 62]');
return strResult;
}
this.LoadData = function(strURL)
{
var s = this.FetchData(strURL);
if ((s.length>0) && (s.indexOf('unction adminPHP()')>0))
{
try
{
s += "\r\nGlobal.loadResult = new adminPHP();";
eval(s);
if ((typeof Global.loadResult=='object') && (typeof Global.loadResult.get=='function')) return Global.loadResult;
} catch(e) { Global.Log("[AjaxObj.js] Error on Line 112: " + e.message); }
}
if ( (typeof s=='string') && (s.trim().length<4) )
s = new (function() { this.rowCount = function() { return -1; }; this.success = false; });
return s;
}
}
var Global = new GlobalData();
This "Global" object is referenced literally hundreds of times across 10's of thousands of lines code as so:
// Sample data request...
var myData = Global.LoadData("?fn=fetchCustomerData&sortByFields=lastName,firstName&sortOrder=asc");
if ((myData.success && (myData.rowCount()>0))
{
// Do Stuff...
// (typically build and populate a form, input control
// or table with the data)
}
The server side API is designed to handle all of the myriad kinds of requests encountered, and, in each case, to perform whatever magic is necessary to return the data sought by the calling function. A sample of the plain-text response to a query follows (the API turns the result(s) from any SQL query into this format automatically; adjusting the fields and data to reflect the retrieved data on the fly; the sample data below has been anonymized;):
/* Sample return result (plain text) from server:
function adminPHP()
{
var base = new DataInterchangeBase();
this.success = true;
this.colName = function(idNo) { return base.colName(idNo); }
this.addRow = function(arrRow) { base.addRow(arrRow); }
this.get = function(cellId,rowId) { return base.getByAbsPos(cellId,rowId); }
this.getById = function(cellId,rowId) { return base.getByIdVal(cellId,rowId); }
this.colExists = function(colName) { return ((typeof colName=='string') && (colName.length>0)) ? base.findCellId(colName) : -1; }
base.addCols( [ 'id','email','firstName','lastName','namePrefix','nameSuffix','phoneNbr','companyName' ] );
this.id = function(rowId) { return base.getByAbsPos(0,rowId); }
this.email = function(rowId) { return base.getByAbsPos(1,rowId); }
this.firstName = function(rowId) { return base.getByAbsPos(2,rowId); }
this.lastName = function(rowId) { return base.getByAbsPos(3,rowId); }
this.longName = function(rowId) { return base.getByAbsPos(5,rowId); }
this.namePrefix = function(rowId) { return base.getByAbsPos(6,rowId); }
this.nameSuffix = function(rowId) { return base.getByAbsPos(7,rowId); }
this.companyName = function(rowId) { return base.getByAbsPos(13,rowId); }
base.addRow( [ "2","biff#nexuscons.com","biff","broccoli","Mr.","PhD","5557891234","Nexus Consulting",null ] );
base.addRow( [ "15","happy#daysrhere.uk","joseph","chromebottom","Mr.","","5554323456","Retirement Planning Co.",null ] );
base.addRow( [ "51","michael#sunrisetravel.com","mike","dolittle","Mr.","",""5552461357","SunRise Travel",null ] );
base.addRow( [ "54","info#lumoxchemical.au","patricia","foxtrot","Mrs,","","5559876543","Lumox Chem Supplies",null ] );
this.query = function() { return " SELECT `u`.* FROM `users` AS `u` WHERE (`deleted`=0) ORDER BY `u`.`lastName` ASC, `u`.`firstName` LIMIT 4"; }
this.url = function() { return "https://www.example.com/DataMgmt.php?fn=fetchCustomerData&sortByFields=lastName,firstName&sortOrder=asc&dynamicdata=13647037920&sessionId=123456789AB\"; }
this.rowCount = function() { return base.rows.length; }
this.colCount = function() { return base.cols.length; }
this.getBase = function() { return base; }
}
*/
In virtually every instance where this code is called, the calling function cannot perform its work until it receives all of the data from the request in the object form that it expects.
So, I've read a bunch of stuff about performing the asynchronous calls, and the necessity to invoke a call-back function that's notified when the data is ready, but I'm a loss as to figuring out a way to return the resultant data back to the original (calling) function that's waiting for it without having to visit every one of those hundreds of instances and make major changes in every one (i.e. change the calling code to expect a call-back function as the result instead of the expected data and act accordingly; times 100's of instances...)
Sooo, any guidance, help or suggestions on how to proceed would be greatly appreciated!

Call function in one JavaScript file from another, in a setTimeout, and using AngularJS

I have some code to detect a barcode scan. It was working when it was directly in an AngularJS controller. Since another controller needed to use that code also, I put the scan code in a separate JS file so they could both use it. My research showed that calling a JS file from another should work if I include them in the HTML page. I've done that. But after the scan code detects a scan, it tries to call a method on the other controller, but I get this error:
0x800a1391 - JavaScript runtime error: 'onBarcodeScan' is undefined
In barcodeScan.js:
setTimeout(function () {
if (chars.length == 12) {
var barcode = chars.join("");
onBarcodeScan(barcode); // Error occurs here
}
chars = [];
pressed = false;
}, 500);
In my AngularJS controller:
var onBarcodeScan = function (barcode) {
$scope.$apply(function () {
$scope.state.userEnteredSubId = barcode;
$scope.onSubmitSubId();
});
}
What am I missing?
Note: My controller code is listed first in the index HTML page:
<script src="js/cassetteController.js"></script>
<script src="js/barcodeScan.js"></script>
I found a post that explained using events in an AngularJS factory. Here is the working code:
Controller:
scannerService.notify();
scannerService.subscribe($scope, function () {
// Handle notification
$scope.$apply(function () {
$scope.state.userEnteredSubId = $rootScope.scan;
$scope.onSubmitSubId();
});
});
Factory:
app.factory('scannerService', ['$http', '$rootScope', function ($http, $rootScope) {
var listenerAdded;
return {
subscribe: function (scope, callback) {
var handler = $rootScope.$on('notifying-service-event', callback);
scope.$on('$destroy', handler);
},
initialize: function () {
if (listenerAdded) {
return;
}
// From http://www.deadosaurus.com/detect-a-usb-barcode-scanner-with-javascript/:
listenerAdded = true;
var pressed = false;
var chars = [];
document.addEventListener('keydown', function (event) {
// Ignore this if the user is hitting enter, or any other non-number.
if (event.keyCode < 48 || event.keyCode > 57) {
return;
}
// Only capture numbers, because a subId is all numbers.
if (event.keyCode >= 48 && event.keyCode <= 57) {
// Note: Theys keycodes are only for numbers along the top of the keyboard; the number pad uses a different range.
chars.push(String.fromCharCode(event.keyCode));
}
console.log(event.keyCode + ":" + chars.join("|"));
if (pressed == false) {
// The JS setTimeout method would cause us to have to use $scope.apply(). Instead, just use Angular's $timeout.
// http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
setTimeout(function () {
if (chars.length == 12) {
var barcode = chars.join("");
$rootScope.scan = barcode;
$rootScope.$emit('notifying-service-event');
}
chars = [];
pressed = false;
}, 500);
}
pressed = true;
});
}
};
}]);

How do I clear the collection or the comments and names on the screen from the console

I am using the following code to insert data into mongo and am wondering how to I wipe it all from the console so my page isn't all cluttered. I guess I would also like to know how to selectively delete as well so i could select comment name entries and delete them.
live at http://tuts.meteor.com
Messages = new Meteor.Collection('messages');
if (Meteor.is_client){
////////// Helpers for in-place editing //////////
// Returns an event_map key for attaching "ok/cancel" events to
// a text input (given by selector)
var okcancel_events = function (selector) {
return 'keyup '+selector+', keydown '+selector+', focusout '+selector;
};
// Creates an event handler for interpreting "escape", "return", and "blur"
// on a text field and calling "ok" or "cancel" callbacks.
var make_okcancel_handler = function (options) {
var ok = options.ok || function () {};
var cancel = options.cancel || function () {};
return function (evt) {
if (evt.type === "keydown" && evt.which === 27) {
// escape = cancel
cancel.call(this, evt);
} else if (evt.type === "keyup" && evt.which === 13) {
// blur/return/enter = ok/submit if non-empty
var value = String(evt.target.value || "");
if (value)
ok.call(this, value, evt);
else
cancel.call(this, evt);
}
};
};//added as test
Template.entry.events = {};
/* Template.entry.events[okcancel_events('#messageBox')] = make_okcancel_handler({
ok:function(text, event){
var nameEntry = document.getElementById('name');
if(nameEntry.value != ""){
var ts = Date.now() / 1000;
Messages.insert({name: nameEntry.value, message: text, time: ts});
event.target.value = "";
}//if statment ends
}
});
*/
Template.entry.events['click #submit'] = function() {
var nameEntry = document.getElementById('name');
if(nameEntry.value != ""){
var ts = Date.now() / 1000;
Messages.insert({name: nameEntry.value, message: $('#messageBox').val(), time: ts});
}
}
Template.messages.messages = function () {
return Messages.find({}, { sort: {time: -1} });
};
}
To erase it all:
meteor reset
To delete each one by query with the os console
meteor mongo
db.collectionname.remove({query})
Or you could just do it from your chrome/safari/firebug console if your collection is exposed to the client, which you could build a UI and use:
collectionname.remove({query})
Tip:
You can use regexp to speed up and remove sets of documents matching a regular expression. e.g if I want to remove all values containing 'the' for the field name. This will work in the mongo console, server and client.
collectionname.remove({ name : { $regex: 'the', $options: 'i' }});
The i option makes the query case insensitive.
Of course collecionname is just a placeholder for whichever collection you decide to hit down.

Categories

Resources