Disable past time for today like an hour, minutes, sec etc using ant design. is there any simple solution than 'disabledHours' like minTime etc.
<TimePicker format="h:mm:ss A" disabledHours={() => [1, 2, 3]} />
You should try to set the disableHours and disabledMinutes of your TimePicker:
<TimePicker
disabledHours={this.getDisabledHours()}
disabledMinutes={this.getDisabledMinutes()}
>
...
getDisabledHours = () => {
var hours = [];
for(var i =0; i < moment().hour(); i++){
hours.push(i);
}
return hours;
}
getDisabledMinutes = (selectedHour) => {
var minutes= [];
if (selectedHour === moment().hour()){
for(var i =0; i < moment().minute(); i++){
minutes.push(i);
}
}
return minutes;
}
And if you want to disable seconds you do the same thing with the disabledSeconds function which has a signature of function(selectedHour, selectedMinute).
Related
Here is my code as below, Please help me to find out solution for add highlight on those dates which I particularly disabled and Sundays.
And Do not want to highlight disabled previous dates from current date.
In this how can add highlights on particular dates which I disabled.
$(document).ready(function(){
jQuery(function() {
var blockedDates = ["12/20/2022", "12/28/2022", "12/24/2022", "12/19/2022"];
var dateFormat = "yy-mm-dd";
$( "#datepicker" ).datepicker({
dateFormat:'yy-mm-dd',
minDate: 0,
daysOfWeekDisabled: [0, 6],
onSelect: function(dateStr) {
var _frmdate = $.trim($(this).val());
jQuery("#blockModalDateItem").modal("show");
jQuery("#bk_blockdt").val(_frmdate);
jQuery(".status_msg").html("");
},
beforeShowDay: function(date){
show = true;
if(date.getDay() == 0 ){show = false;}
for (var i = 0; i < blockedDates.length; i++) {
if (new Date(blockedDates[i]).toString() == date.toString()) {show = false;}
}
var display = [show,'',(show)?'':'Block Settlement Date']; //Disabled Particular dates & all Sundays.
return display;
}
});
});
You can use CSS to apply styles to disabled dates. Specifically targeting dates with title="Block Settlement Date"
.ui-datepicker-unselectable.ui-state-disabled[title="Block Settlement Date"] {
background:red;
}
Thank you to all, For giving precious time to help my queries.
But I found my custom solution for my problem & I would like to share here may this will help to others.
New changes added to datepicker in beforeshowday is here, in this i have added custom class.
$(document).ready(function(){
jQuery(function() {
var blockedDates = ["12/20/2022", "12/28/2022", "12/24/2022", "12/19/2022"];
var dateFormat = "yy-mm-dd";
$( "#datepicker" ).datepicker({
dateFormat:'yy-mm-dd',
minDate: 0,
daysOfWeekDisabled: [0, 6],
onSelect: function(dateStr) {
var _frmdate = $.trim($(this).val());
jQuery("#blockModalDateItem").modal("show");
jQuery("#bk_blockdt").val(_frmdate);
jQuery(".status_msg").html("");
},
beforeShowDay: function(date){
show = true;
if(date.getDay() == 0 ){show = false;}
for (var i = 0; i < blockedDates.length; i++) {
if (new Date(blockedDates[i]).toString() == date.toString()) {show = false;}
}
var display = [show,'highlight-bkdate',(show)?'':'Block Settlement Date']; //Disabled Particular dates & all Sundays.
return display;
}
});
});
In this class i have applied some css for giving highlight purpose.
.highlight-bkdate span {
color: #fff!important;
background-color: red!important;
border: 3px solid #191970!important;
}
Now this state it will highlight all disabled dates, Now I want to only particular dates & sunday should highlight.
So, I called this function after datepicker load. In this I again removed class on those dates which I do not want to highlight.
setTimeout(removeClassHigh, 50);
function removeClassHigh(){
var blockedDates = ["12/20/2022", "12/28/2022", "12/24/2022", "12/19/2022"];
var dayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var currentYear = jQuery(".ui-datepicker-year").text();
var currentMonth = jQuery(".ui-datepicker-month").text();
var oneMonth = 1;
var dat = new Date('1 ' + currentMonth +' ' +currentYear);
var monthNo = dat.getMonth();
oneMonth += Number(monthNo);
var f1 = 1;
var d = new Date();
var day = d.getDate();
$('.ui-state-default').each(function () {
var checkCurrentDt = new Date(oneMonth+'/'+f1+'/'+currentYear);
var checkThisDay = checkCurrentDt.getDay();
var checkThisDate = String(checkCurrentDt.getDate()).padStart(2, '0');
if(day==f1){
return false;
}else{
if(dayNames[checkThisDay]!="Sunday"){
if (jQuery.inArray(oneMonth+'/'+checkThisDate+'/'+currentYear, blockedDates) === -1) {
$(this).parent().removeClass('highlight-bkdate');
}
}
}
f1++;
});
}
So in this way found this solution.
And Result as below:
Thank you to all..!!
Have a great day :)
I have a spreadsheet, in which I need the script to fetch, over two columns, two pieces of information. And when that's true, I add a formula that adds "1 day" into a third column.
I can make the conditionals run individually. But when I put both, they don't work.
function fillColADia() {
var s = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Afazeres');
var dataA = s.getRange("H1:H").getValues();
var dataB = s.getRange("A1:A").getValues();
for(var i=0; i<dataA.length; i++) {
for(var j=0; j<dataB.lenght; j++) {
if (dataB[j][0] == false) {
if (dataA[i][0] == 'Zenon') {
s.getRange(i+1,3).setValue("+1");
}
}
}
}
}
And I also don't know how to add the "add 1 day" formula to the end.
Thanks a lot for the help.
COPY FILE with dummy data
Faaala! Something along these lines as food for thought!
...although I'm certain there are more performant ways to accomplish it:
function fillColADia() {
var s = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Page1');
var data = s.getRange("A1:H").getValues();
for (var a = 0; a < data.length; a++) {//Percorre cada linha do intervalo
if (data[a][0] == false && data[a][7] == 'Zenon') {//Aplica critérios
let date = data[a][2];//Pega a data daquela linha
date1 = Utilities.formatDate(addDays(new Date(date), 1), Session.getTimeZone(), "dd/MM/yyyy");//Formata o objeto data, usando a função abaixo para incrementar o dia
date2 = Utilities.formatDate(addDays(new Date(date), 1), Session.getTimeZone(), "dd/MM/yyyy HH:mmss");
s.getRange(a + 1, 3).setValue(date1);//Põe a data de volta
s.getRange(a + 1, 4).setValue(date2);//Põe a data de volta
}
}
}
//GERA DATAS INCREMENTANDO OS DIAS
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
I have List list= [1,2,3,4,4,4,9,6,7,7,7,8,8,8,8,8,8,8];
how can i return 8 as max repeated value
Something like this?
void main() {
final list = [1, 2, 3, 4, 4, 4, 9, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8];
print(findMaxDuplicatedElementInList(list)); // 8
}
T findMaxDuplicatedElementInList<T>(Iterable<T> list) => list
.fold<Map<T, int>>(
{},
(map, element) =>
map..update(element, (value) => value + 1, ifAbsent: () => 1))
.entries
.reduce((e1, e2) => e1.value > e2.value ? e1 : e2)
.key;
I'd just write it out, as straight-forward as possible:
Assuming the equal elements are always adjacent, and list cannot be empty, return arbitrary element with maximal count if there is more than one:
T maxDuplicated<T>(List<T> elements) {
var element = elements.count;
var count = 1;
var maxElement = element;
var maxCount = count;
for (var i = 1; i < elements.length; i++) {
var nextElement = elements[i];
if (element != nextElement) {
element = nextElement;
count = 1;
} else {
count += 1;
if (count > maxCount) {
maxElement = element;
maxCount = count;
}
}
}
return maxElement;
}
Assuming elements come in random order, so we need to remember every element we have seen,
still not allowing an empty list as input:
T maxDuplicated<T>(List<T> elements) {
var maxCount = 1;
var maxElement = elements.first
var seen = <T, int>{maxElement: maxCount};
for (var i = 1; i < elements.length; i++) {
var element = elements[i];
var count = seen[element] = (seen[element] ?? 0) + 1;
if (count > maxCount) {
maxCount = count;
maxElement = element;
}
}
return maxElement;
}
(Alternatively, I'd sort the list first, if allowed, to always be in the former situation. It's not faster than using a map, if we assume hash map lookup to be a constant time operation, but it will be more memory efficient.)
I have too many columns in the sheet and so many columns to hide as well, but while executing the script it runs half way and stopped saying maximum time reached.
When I again tried to execute it stopped exactly where I stopped previously. So I would like to have some customization that if the column is already hidden can skip that column and work on the others.
Is there any way to do it.
Here is the code I used:
function hideColumns() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('ANALYTIC');
var data = sh.getRange('6:6').getValues();
var numCols = sh.getMaxColumns();
var numRows = sh.getMaxRows();
for(var i = 0; i <= numCols; i++){
if(data[0][i] == ""){
sh.hideColumns(i+1);
} else {
sh.unhideColumn(sh.getRange(1, i+1, numRows, 1));
}
}
}
Please help me.
You can use the documentProperties to store the last column before the end of the execution. To prevent the run from stopping abruptly you stop the run a little prematurely at 5min (execution will terminate at 6min mark) mark and store the column number in the documentProperty. You also display an alert asking you rerun the script.
Then retrieve the column number on the next run and start from there. If the program gets through the complete loop you delete the said properties. So you start from zero if you rerun the script next time.
Below is the code for the same
function hideColumns() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('ANALYTIC');
var data = sh.getRange('6:6').getValues();
var numCols = sh.getMaxColumns();
var numRows = sh.getMaxRows();
var docProp = PropertiesService.getDocumentProperties()
var startCol = Number(docProp.getProperty("startCol")) //if there is no propert called startCol will return Null, Number(Null) = 0
Logger.log(startCol)
var startTime = new Date().getTime()
var ms5min = 5*60*1000 //5min in millseconds
for(var i = startCol; i <= numCols; i++){
if(data[0][i] == ""){
sh.hideColumns(i+1);
} else {
sh.unhideColumn(sh.getRange(1, i+1, numRows, 1));
}
var curTime = new Date().getTime()
var elasped = curTime-startTime
if (elasped >= ms5min){
docProp.setProperty("startCol", i)
SpreadsheetApp.getUi().alert("Please restart Run, exceeded 5min mark")
return
}
}
Logger.log(elasped)
docProp.deleteAllProperties()
}
If your sheet has under 10,000 columns (PropertiesService limit) you can use this script:
function hideColumns() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('ANALYTIC');
var data = sh.getRange('6:6').getValues();
var documentProperties = PropertiesService.getDocumentProperties()
var documentPropertiesVals = documentProperties.getProperties();
var numCols = sh.getMaxColumns();
for(var i = 0; i < numCols; i++){
if (!(cPlusInt(i) in documentPropertiesVals)) {
documentPropertiesVals[cPlusInt(i)] === 'empty';
}
if (documentPropertiesVals[cPlusInt(i)] === 'hidden' && data[0][i] == "") continue;
if (documentPropertiesVals[cPlusInt(i)] === 'unhidden' && data[0][i] != "") continue;
if(data[0][i] == ""){
sh.hideColumns(i+1);
documentProperties.setProperty(cPlusInt(i), 'hidden')
} else {
sh.unhideColumn(sh.getRange(1, i+1, 1, 1));
documentProperties.setProperty(cPlusInt(i), 'unhidden')
}
}
}
function cPlusInt(num) {
return 'c'+num.toString()
}
You at first you may need to run this few times (many write operation to PropertiesService may be sluggish) but later it's "blazingly" fast (0.1 s per new column).
Better answer using #Jack Brown's idea
It is possible to make single save to PropertiesService - you would need to incorporate time limit from #Jack Brown's answer, this way:
function hideColumns() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('ANALYTIC');
var data = sh.getRange('6:6').getValues();
var documentProperties = PropertiesService.getDocumentProperties()
var documentPropertiesVals = documentProperties.getProperties();
var numCols = sh.getMaxColumns();
var startTime = new Date().getTime()
var ms5min = 5*60*1000 //5min in millseconds
for(var i = 0; i < numCols; i++){
if (!(cPlusInt(i) in documentPropertiesVals)) {
documentPropertiesVals[cPlusInt(i)] === 'empty';
}
if (documentPropertiesVals[cPlusInt(i)] === 'hidden' && data[0][i] == "") continue;
if (documentPropertiesVals[cPlusInt(i)] === 'unhidden' && data[0][i] != "") continue;
if(data[0][i] == ""){
sh.hideColumns(i+1);
documentPropertiesVals[cPlusInt(i)] = 'hidden'
} else {
sh.unhideColumn(sh.getRange(1, i+1, 1, 1));
documentPropertiesVals[cPlusInt(i)] = 'unhidden'
}
var curTime = new Date().getTime()
var elapsed = curTime-startTime
if (elapsed >= ms5min){
break;
}
}
documentProperties.setProperties(documentPropertiesVals)
if (elapsed >= ms5min){
SpreadsheetApp.getUi().alert("Please restart Run, exceeded 5min mark")
}
}
cPlusInt function explanation
cPlusInt is necessary because of weird problems with google's PropertiesService. Object gotten from PropertiesService returns undefined at integer keys. To see problem use this code:
function test() {
var obj = {};
for (var i=0; i<10; i++) {
obj[i.toString()] = 'aa' + i.toString();
}
var documentProperties = PropertiesService.getScriptProperties();
documentProperties.deleteAllProperties();
documentProperties.setProperties(obj);
obj = documentProperties.getProperties();
Logger.log(obj)
for (var i in obj) {
Logger.log('%s %s %s', i, obj[i], i === '1');
}
}
How can I compute a MD5 or SHA1 hash of text in a specific cell and set it to another cell in Google Spreadsheet?
Is there a formula like =ComputeMD5(A1) or =ComputeSHA1(A1)?
Or is it possible to write custom formula for this? How?
Open Tools > Script Editor then paste the following code:
function MD5 (input) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, 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;
}
Save the script after that and then use the MD5() function in your spreadsheet while referencing a cell.
This script is based on Utilities.computeDigest() function.
Thanks to gabhubert for the code.
This is the SHA1 version of that code (very simple change)
function GetSHA1(input) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_1, input);
var txtHash = '';
for (j = 0; j <rawHash.length; j++) {
var hashVal = rawHash[j];
if (hashVal < 0)
hashVal += 256;
if (hashVal.toString(16).length == 1)
txtHash += "0";
txtHash += hashVal.toString(16);
}
return txtHash;
}
Ok, got it,
Need to create custom function as explained in
http://code.google.com/googleapps/appsscript/articles/custom_function.html
And then use the apis as explained in
http://code.google.com/googleapps/appsscript/service_utilities.html
I need to handtype the complete function name so that I can see the result in the cell.
Following is the sample of the code that gave base 64 encoded hash of the text
function getBase64EncodedMD5(text)
{
return Utilities.base64Encode( Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, text));
}
The difference between this solution and the others is:
It fixes an issue some of the above solution have with offsetting the output of Utilities.computeDigest (it offsets by 128 instead of 256)
It fixes an issue that causes some other solutions to produce the same hash for different inputs by calling JSON.stringify() on input before passing it to Utilities.computeDigest()
function MD5(input) {
var result = "";
var byteArray = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, JSON.stringify(input));
for (i=0; i < byteArray.length; i++) {
result += (byteArray[i] + 128).toString(16) + "-";
}
result = result.substring(result, result.length - 1); // remove trailing dash
return result;
}
to get hashes for a range of cells, add this next to gabhubert's function:
function RangeGetMD5Hash(input) {
if (input.map) { // Test whether input is an array.
return input.map(GetMD5Hash); // Recurse over array if so.
} else {
return GetMD5Hash(input)
}
}
and use it in cell this way:
=RangeGetMD5Hash(A5:X25)
It returns range of same dimensions as source one, values will spread down and right from cell with formulae.
It's universal single-value-function to range-func conversion method (ref), and it's way faster than separate formuleas for each cell; in this form, it also works for single cell, so maybe it's worth to rewrite source function this way.
Based on #gabhubert but using array operations to get the hexadecimal representation
function sha(str){
return Utilities
.computeDigest(Utilities.DigestAlgorithm.SHA_1, str) // string to digested array of integers
.map(function(val) {return val<0? val+256 : val}) // correct the offset
.map(function(val) {return ("00" + val.toString(16)).slice(-2)}) // add padding and enconde
.join(''); // join in a single string
}
Using #gabhubert answer, you could do this, if you want to get the results from a whole row. From the script editor.
function GetMD5Hash(value) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, value);
var txtHash = '';
for (j = 0; j <rawHash.length; j++) {
var hashVal = rawHash[j];
if (hashVal < 0)
hashVal += 256;
if (hashVal.toString(16).length == 1)
txtHash += "0";
txtHash += hashVal.toString(16);
}
return txtHash;
}
function straightToText() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var r = 1;
var n_rows = 9999;
var n_cols = 1;
var column = 1;
var sheet = ss[0].getRange(r, column, n_rows, ncols).getValues(); // get first sheet, a1:a9999
var results = [];
for (var i = 0; i < sheet.length; i++) {
var hashmd5= GetMD5Hash(sheet[i][0]);
results.push(hashmd5);
}
var dest_col = 3;
for (var j = 0; j < results.length; j++) {
var row = j+1;
ss[0].getRange(row, dest_col).setValue(results[j]); // write output to c1:c9999 as text
}
}
And then, from the Run menu, just run the function straightToText() so you can get your result, and elude the too many calls to a function error.
I was looking for an option that would provide a shorter result. What do you think about this? It only returns 4 characters. The unfortunate part is that it uses i's and o's which can be confused for L's and 0's respectively; with the right font and in caps it wouldn't matter much.
function getShortMD5Hash(input) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, input);
var txtHash = '';
for (j = 0; j < 16; j += 8) {
hashVal = (rawHash[j] + rawHash[j+1] + rawHash[j+2] + rawHash[j+3]) ^ (rawHash[j+4] + rawHash[j+5] + rawHash[j+6] + rawHash[j+7])
if (hashVal < 0)
hashVal += 1024;
if (hashVal.toString(36).length == 1)
txtHash += "0";
txtHash += hashVal.toString(36);
}
return txtHash.toUpperCase();
}
I needed to get a hash across a range of cells, so I run it like this:
function RangeSHA256(input)
{
return Array.isArray(input) ?
input.map(row => row.map(cell => SHA256(cell))) :
SHA256(input);
}