I have a simple script written to hash a cell, however it doesn't work within and array formula, and I am having a hard time figure out how to add that functionality.
function SHA256 (input) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, input);
var txtHash = '';
for (i = 0; i < rawHash.length; i++) {
var hashVal = rawHash[i];
if (hashVal < 0) {
hashVal += 256;
}
if (hashVal.toString(16).length == 1) {
txtHash += '0';
}
txtHash += hashVal.toString(16);
}
return txtHash;
}
Within Google Sheets, the above script allows me to hash using SHA526(A2)
I would like to be able to hash an entire column by using SHA256() within an array formula. =ArrayFormula(SHA256(A2:A))
The error I get is
"Exception: The parameters (DigestAlgorithm,number[]) don't match the method signature for Utilities.computeDigest. (line 2)."
Any direction would be greatly appreciated!
Google Apps Script - Custom Functions Documentation
In order to use an array you need to map the input. Using a simple else if you can test if the input is an array or a single value.
function SHA256 (input) {
if(input.map) {
return input.map(SHA256);
} else {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, input);
var txtHash = '';
for (i = 0; i < rawHash.length; i++) {
var hashVal = rawHash[i];
if (hashVal < 0) {
hashVal += 256;
}
if (hashVal.toString(16).length == 1) {
txtHash += '0';
}
txtHash += hashVal.toString(16);
}
return txtHash;
}
}
Related
I am getting data over websocket every 10 seconds and i am updating the cells using this function:
agentStatSocket.onmessage = function (e) {
data = JSON.parse(e.data);
//console.log(typeof(data));
for (var i = 0; i < data.length; i++) {
var inboundTd = '#' + data[i]['id'] + '-inbound';
var outboundTd = '#' + data[i]['id'] + '-outbound';
if (data[i]['inboundCalls'] != 0) {
$(inboundTd).html(data[i]['inboundCalls']);
}
if (data[i]['outboundCalls'] != 0) {
$(outboundTd).html(data[i]['outboundCalls']);
}
}
};
This is working pretty fine. However, I see some lag with the table being updated. Currently, there are only 150 rows in the table. I do not know what will be the latency if rows will become 1000 or more.
I have the following questions:
What is the correct approach to design these kinds of tables in which data is changing very frequently? I am not using any library like react or angular. This is plain jQuery.I am using dataTables
jQuery to enhance table view.
One thing to consider is that, in many cases, accessing an element based on an ID is usually a lot quicker in vanilla javascript compared to jquery.
A simple example of that is:
function jsTest() {
for (let i = 0; i < 1000; i++) {
document.getElementById("js").innerHTML = i;
}
}
function jqueryTest() {
for (let i = 0; i < 1000; i++) {
$("#jquery").html(i);
}
}
function startup() {
console.time("javascript");
jsTest();
console.timeEnd("javascript");
console.time("jquery");
jqueryTest();
console.timeEnd("jquery");
}
// For testing purposes only
window.onload = startup;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Javascript: <div id="js"></div>
Jquery: <div id="jquery"></div>
So, you could try changing your code to:
agentStatSocket.onmessage = function (e) {
data = JSON.parse(e.data);
//console.log(typeof(data));
for (var i = 0; i < data.length; i++) {
//var inboundTd = '#' + data[i]['id'] + '-inbound';
//var outboundTd = '#' + data[i]['id'] + '-outbound';
var inboundTd = data[i]['id'] + '-inbound';
var outboundTd = data[i]['id'] + '-outbound';
if (data[i]['inboundCalls'] != 0) {
//$(inboundTd).html(data[i]['inboundCalls']);
document.getElementById(inboundTd).innerHTML = data[i]['inboundCalls'];
}
if (data[i]['outboundCalls'] != 0) {
//$(outboundTd).html(data[i]['outboundCalls']);
document.getElementById(outboundTd).innerHTML = data[i]['outboundCalls'];
}
}
};
You can still use jquery for the rest of your code, if you wish, but simple updates to elements that can be targeted by ID are usually quicker with vanilla javascript.
var infiniteResponseAAA= {
Poodwaddle_com: '"Poodwaddle.com", infiniteResponse[1].children[language].children[17].innerHTML, "Images\poodwaddle.com.jpg", searchBResponse[1].children[17].textContent',
SystemRequirementsLab_com: '"System Requirements Lab.com", infiniteResponse[1].children[language].children[18].innerHTML, "Images\systemrequirementslab.com.jpg", searchBResponse[1].children[18].textContent',
BrowsePad: '"BrowsePad.org", infiniteResponse[1].children[language].children[19].innerHTML, "Images\BrowsePad.org.jpg", searchBResponse[1].children[19].textContent',
SMMRY_com: '"SMMRY.com", infiniteResponse[1].children[language].children[20].innerHTML, "Images\smmry.com.jpg", searchBResponse[1].children[20].textContent',
Whatthefuckshouldimakefordinner_com: '"Whatthefuckshouldimakefordinner.com", infiniteResponse[1].children[language].children[21].innerHTML, "Images\Whatthefuckshouldimakefordinner.com.jpg", searchBResponse[1].children[21].textContent',
Coolors_co: '"Coolors.co", infiniteResponse[1].children[language].children[22].innerHTML, "Images\Coolors.co.jpg", searchBResponse[1].children[22].textContent',
Numbeo_com: '"Numbeo.com", infiniteResponse[1].children[language].children[23].innerHTML, "Images\Numbeo.com.jpg", searchBResponse[1].children[23].textContent',
Doesthedogdie_com: '"Doesthedogdie.com", infiniteResponse[1].children[language].children[24].innerHTML, "Images\Doesthedogdie.com.jpg", searchBResponse[1].children[24].textContent',
Online_Convert_com: '"Online-Convert.com", infiniteResponse[1].children[language].children[25].innerHTML, "Images\Online-Convert.com.jpg", searchBResponse[1].children[25].textContent'
}
var infiniteResponse= Object.keys(infiniteResponseAAA).sort();
var sitesOnPage = [];
var brLength= document.querySelectorAll("br").length;
var whereToAddIt= document.querySelectorAll("br")[brLength-1];
var observer = new IntersectionObserver(function(entries){
entries.forEach(function(entry) {
if (entry.isIntersecting) {
getDataInfiniteS();
}
});
});
observer.observe(whereToAddIt);
// Data checker
function getDataInfiniteS() {
InfiniteScrolling();
}
// Actual script
function InfiniteScrolling() {
var code;
// It gets the first 5 sites that are already on the page and puts them inside sitesOnPage
if (sitesOnPage[0] === undefined) {
var h2s= document.querySelectorAll("h2");
infiniteResponseAAA[infiniteResponse[0]].split(",")[0].replace(/["]/g, "");
for (var i=0; i < h2s.length; i++) {
if (h2s[i].innerHTML === infiniteResponseAAA[infiniteResponse[i]].split(",")[0].replace(/["]/g, "")) sitesOnPage.push(i);
}
}
function randomSiteInfosF(siteN) {
// Checks if it's a number and not a string or something else
if (typeof siteN !== "number") return;
siteChecker_RNG(siteN)
// Infos about the site: title
eval(`siteInfo${siteN}= infiniteResponseAAA[infiniteResponse[${eval(`randomSite${siteN}`)}]].split(",")`);
eval(`siteTitle${siteN}= siteInfo${siteN}[0].replace(/["]/g, "")`);
}
function siteChecker_RNG(siteN) {
var sitesAvailable= infiniteResponse.length;
var h2s= document.querySelectorAll("h2");
var randomSiteN= Math.floor(Math.random() * sitesAvailable);
// Return if all sites are loaded
if (h2s.length === sitesAvailable) return;
// Checks if the random number is a correct one
for (var i= 0; i < sitesOnPage.length; i++) {
if (randomSiteN === sitesOnPage[i]) {
siteChecker_RNG(siteN)
} else continue;
}
eval(`randomSite${siteN}= randomSiteN`);
}
var howManySitesPerLoad= 3;
for (let i= 0; i < howManySitesPerLoad; i++) {
randomSiteInfosF(i);
}
// Creates a new div for the sites loaded from the database
if (document.getElementById("InfiniteScrollingID") === null) {
whereToAddIt.insertAdjacentHTML("afterend", "<div id='InfiniteScrollingID'></div>");
}
for (let i= 0; i < howManySitesPerLoad; i++) {
code= `${eval(`siteTitle${i}`)}\n</br></br></br>`
document.getElementById("InfiniteScrollingID").insertAdjacentHTML("beforeend", code);
}
for (var i=0; i < howManySitesPerLoad; i++) {
sitesOnPage.push(eval(`randomSite${i}`))
}
brLength= document.querySelectorAll("br").length;
whereToAddIt= document.querySelectorAll("br")[brLength-1];
observer.disconnect()
observer.observe(whereToAddIt)
}
This is a re-post since nobody answered me before when i provided a working minimal example and this script is super important for my site.
This is part of code that is used for my site in its sections, http://www.coolwebsites.ml/
https://youtu.be/QDrn_9svt6Y
CodePen: https://codepen.io/Attisalva/pen/pojdZXr?editors=1010
In the CodePen example (same problem), it creates (in this case title names to simplify the code) some title names that are already on the page and it should only create titles that aren't yet created (you can find titles in the object "infiniteResponseAAA").
I'm trying to lazy loading new images, titles, descs, etc randomly on the page but it keeps creating without checking properly if everything is already on page.
It's because i didn't end/return the function after i got a good number
I am using the p5.js library, and I am working on a speech recognition - text to speech project. Kind of a chatbot.
Input is voice input which becomes a string.
I am outputting the result from a txt file, using a markov chain. Output is a string contained in a div.
My question is:
Is there a way to hide/show the div containing my input/output (.myMessage and .robotMessage) in intervals?
I want the whole screen first showing only the input when I am talking, then input disappears and only output showing, then when the computer voice finishes speaking my input is shown in the screen and so on...
Here some parts of the code, let me know if it is clear enough.
//bot
function setup() {
noCanvas();
//reads and checks into the text file
for (var j = 0; j < names.length; j++) {
var txt = names[j];
for (var i = 0; i <= txt.length - order; i++) {
var gram = txt.substring(i, i + order);
if (i == 0) {
beginnings.push(gram);
}
if (!ngrams[gram]) {
ngrams[gram] = [];
}
ngrams[gram].push(txt.charAt(i + order));
}
}
//voice recognition
let lang = 'en-US';
let speechRec = new p5.SpeechRec(lang, gotSpeech);
let continuous = true;
let interim = false;
speechRec.start(continuous, interim);
//text-to-speach
speech = new p5.Speech();
speech.onLoad = voiceReady;
function voiceReady() {
console.log('voice ready');
}
//input-ouput
function gotSpeech() {
if (speechRec.resultValue) {
var p = createP(speechRec.resultString);
p.class('myMessage');
}
markovIt();
chooseVoice();
speech.speak(answer);
}
}
and
function markovIt() {
var currentGram = random(beginnings);
var result = currentGram;
for (var i = 0; i < 100; i++) {
var possibilities = ngrams[currentGram];
if (!possibilities) {
break;
}
var next = random(possibilities);
result += next;
var len = result.length;
currentGram = result.substring(len - order, len);
}
var answer = result;
window.answer = answer;
var p2 = createP(answer);
p2.class('robotMessage');
}
how the HTML looks
<div class="container">
<div class="myMessage"></div>
<div class="robotMessage"></div>
</div>
Use select() to get a document element by its id, class, or tag name. e.g:
let my_div = select("myMessage");
Change the style of an element by style().
e.g hide:
my_div.style("display", "none");
e.g. show:
my_div.style("display", "block");
See also Toggle Hide and Show
I got this code:
$(document).ready(function(){
$(".nextForm").on('click',(function(){
//check criteria
if(selectedSlots.length < 1 ||$("#positionAppliedFor").get(0).value.length < 1 ||$("#maxAmountOfHours").get(0).value.length < 1){
//error messages and array
var errorForSlots= "<h5>Select at least one availability slot</h5>";
var errorForPosition = "<h5>Enter the position you wish to apply for<h5>";
var errorForHours = "<h5>Enter the amount of hours you would like to work<h5>";
var errors = [];
//add errors to array
if(selectedSlots.length < 1){errors.push(errorForSlots)};
if($("#positionAppliedFor").get(0).value.length < 1){errors.push(errorForPosition)};
if($("#maxAmountOfHours").get(0).value.length < 1){errors.push(errorForHours)};
//create message
var div = "<div id=\"sectionError\">";
if($("#sectionError").length > 0){$("#sectionError").html('')};
$(div).appendTo($(this).get(0).parentNode);
for(var i = 0; i < errors.length; i++){
$(errors[i]).appendTo($("#sectionError"));
console.log(errors[i]);}
$("</div>").appendTo($(this).get(0).parentNode);
} else {
$("#applicationDetails").slideUp();
$("#personalDetails").slideDown();
if($("#sectionError").length > 0){$("#sectionError").remove()};
}
console.log("function finished");
}));
It all works perfectly, however, I am trying to figure out how to create a function for
//create message
var div = "<div id=\"sectionError\">";
if($("#sectionError").length > 0){$("#sectionError").html('')};
$(div).appendTo($(this).get(0).parentNode);
for(var i = 0; i < errors.length; i++){
$(errors[i]).appendTo($("#sectionError"));
console.log(errors[i]);}
$("</div>").appendTo($(this).get(0).parentNode);
I am planning to re-use this for few other sections on my form and rather than copy/paste I would like to get some help on making my code tidier.
I did try:
function myFunction(){
//message code here
}
$(document).ready(function(){
$(".nextForm").on('click',(function(){
//check criteria
...
//add errors
...
//call func
myFunction();
(I also tried this.myFunction();)
...
}));
});
However, that ended up in TypeError and I don't know where to begin...
I am also concerned about the "this" in my message code so I am also not sure how to address that in my new function...
Admitedly I am a newbie at this and I do not exactly understand all the ins and outs, hopefully you will be able to help.
Maybe there is a better way of doing this?
Let me know your thought either way!
Thanks.
I have created a small reusable framework same as how jQuery is doing behind the scene to expose reusable functions. I didn't tested the append function properly,I just explaining how you can create your own reusable plugin to reuse across the project.
You can change the parameters and method name that you want to expose based on your functionality.
Also I would suggest you to move this code to a javascript file as a plugin and drag after the jquery script.
(function (global, $) {
//you can pass the jQuery object in to this IIFE
var DisplayError = function (elementId) {
return new DisplayError.init(elementId);
}
DisplayError.prototype = {
appendError: function (errors) {
var div = "<div id=\"" + this.elementId + " \">";
if ($(this.elementId).length > 0) {
$(this.elementId).html('')
};
$(div).appendTo($(this.elementId).get(0).parentNode);
for (var i = 0; i < errors.length; i++) {
$(errors[i]).appendTo($(this.elementId));
}
$("</div>").appendTo($(this.elementId).get(0).parentNode);
}
};
DisplayError.init = function (elementId) {
var self = this;
self.elementId = elementId;
}
DisplayError.init.prototype = DisplayError.prototype;
global.DisplayError = global.DisplayError = DisplayError;
}(window, jQuery));
You can write the code for clear the html directly in init function to ensure the element is clearing while initialize the instance itself.
You can invoke the method like below ,
var displayError=DisplayError("#sectionError")
displayError.appendError(["errorId"])
or
DisplayError("#sectionError").appendError(["errorId"])
Hope this helps
New Function
function generateMessage(arg1) {
//create message for each section
console.log("generating message");
var div = "<div id=\"sectionError\">";
if ($("#sectionError").length > 0) {
$("#sectionError").html('')
}
;$(div).appendTo($(arg1).parent());
for (var i = 0; i < errors.length; i++) {
$(errors[i]).appendTo($("#sectionError"));
console.log(errors[i]);
}
$("</div>").appendTo($(arg1).parent());
}
Changed old function
$(document).ready(function() {
$("#adbutnext").on('click', (function() {
//check criteria
if (selectedSlots.length < 1 || $("#positionAppliedFor").get(0).value.length < 1 || $("#maxAmountOfHours").get(0).value.length < 1) {
//error messages and array
var errorForSlots = "<h5>Select at least one availability slot</h5>";
var errorForPosition = "<h5>Enter the position you wish to apply for<h5>";
var errorForHours = "<h5>Enter the amount of hours you would like to work<h5>";
errors = [];
//add errors to array
if (selectedSlots.length < 1) {
errors.push(errorForSlots)
}
;if ($("#positionAppliedFor").get(0).value.length < 1) {
errors.push(errorForPosition)
}
;if ($("#maxAmountOfHours").get(0).value.length < 1) {
errors.push(errorForHours)
}
;
generateMessage(this);
} else {
$("#applicationDetails").slideUp();
$("#personalDetails").slideDown();
if ($("#sectionError").length > 0) {
$("#sectionError").remove()
}
;
}
console.log("function finished");
}
));
});
I am working on a script that creates a tree. The problem i am facing is when large chunk of data comes it gets stuck for some time then rendering every thing at the end.
What i am looking for is can there be a way that make it more interactive. Like as soon as a node is being made it gets popup at the Interface.
For getting into the inside i am posting my code.
function recursiveGenerateTree(objNode, parntSpan, ulContainer, objEditParam) {
var cntLi = 0;
var spnApplyClass;
var rdbValue;
var cntrList = 0;
for (cntLi = 0; cntLi <= objNode.NodeList.length - 1; cntLi++) {
objEditParam.rdbGroup = objEditParam.rdbGroup;
rdbValue = objEditParam.orgRootID + '_' + objNode.NodeList[cntLi].Id;
objEditParam.rdbValue = rdbValue;
objEditParam.selector = 'radio';
objEditParam.selector = '';
objEditParam.isNewNode = false;
addChild('', parntSpan, ulContainer, objEditParam);
$('#txtParent').val(objNode.NodeList[cntLi].Name);
spnApplyClass = $('#txtParent').parents('span:first');
$('#txtParent').trigger('blur', [spnApplyClass]);
spnApplyClass.removeClass('bgLime');
var li = spnApplyClass.parents("li:first");
li.attr("nodeId", objNode.NodeList[cntLi].Id);
li.attr("rootnodeId", objNode.NodeList[cntLi].RootOrgUnitId);
var ulPrsnt = objNode.NodeList[cntLi].NodeList;
if (ulPrsnt != undefined && ulPrsnt.length > 0) {
recursiveGenerateTree(objNode.NodeList[cntLi], spnApplyClass, '', objEditParam);
}
}
}
Second function used is Add child
function addChild(currentbtn, parentSpn, parentUl, objEditParam) {
var spnElement;
if ($(currentbtn).length > 0) {
var dvClick = $(currentbtn).closest('div').siblings('div.OrgGroupLists')
spnElement = $(dvClick).find('span.bgLime');
}
else {
spnElement = parentSpn;
}
if (spnElement.length == 0 && parentUl.length == 0)
return;
var crtUlChild;
if (spnElement.length > 0) {
var dvCurrent = $(spnElement).closest("div");
crtUlChild = $(dvCurrent).find('ul:first');
}
if (parentUl.length > 0) {
crtUlChild = parentUl;
}
if (crtUlChild.length == 0) {
var ulChildrens = createUl();
}
//Next line needs to be updated.
var spnImage = $(dvCurrent).find("span:first");
$(spnImage).removeClass("SpanSpace");
$(spnImage).addClass("L7CollapseTree");
var liChildrens = document.createElement("li");
$(liChildrens).attr("isNew", objEditParam.isNewNode);
$(liChildrens).attr("isTextEdited", false);
var dvChildrens = createDivNode(objEditParam);
$(liChildrens).append(dvChildrens);
if (crtUlChild.length == 0) {
$(ulChildrens).append(liChildrens);
$(dvCurrent).append(ulChildrens);
}
else {
crtUlChild.append(liChildrens);
}
}
Feel free to ask any more details if required to understand the problem more clearly.
What #nnnnnn means is that you call subsequent recursion in setTimeout.
I did not spend time trying to replicate your code locally. Check out JavaScript code below for example. setTimeout works fine for the code below. You can vary variable j's length according to your browser. The inner loop j is to block JS thread.
<html><head>
<script>
var k = 0;
function recursiveTree(){
$("#holder").append("<div>Item</div>");
for(var j =0; j < 100000000; j++){
// blocking thread
}
if (k++ < 20) {
console.log(k);
setTimeout(function(){recursiveTree()},10);
}
}</script>
</head>
<body>
<div id='holder'></div></body>
</html>
I assumed that you are using JQuery.
Just to confirm you need to make recursive call as following
if (ulPrsnt != undefined && ulPrsnt.length > 0) {
setTimeout(function(){recursiveGenerateTree(objNode.NodeList[cntLi], spnApplyClass, '', objEditParam);},10);
}