How to clear list files before listing another one? - javascript

function listFiles() {
var x = document.getElementById("ResultShown").value;
var date = new Date();
date.setDate(date.getDate() - 180);
var n = date.toISOString().split('.')[0] ;
var test = false;
gapi.client.drive.files.list({
pageSize: x,
q: "starred = "+test+" and viewedByMeTime < '"+n+"'",
orderBy: 'quotaBytesUsed desc',
fields: "nextPageToken, files(id, name, viewedByMeTime, mimeType, quotaBytesUsed, webViewLink)",
}
).then(function(response) {
var table = document.getElementById('content');
appendPre('Files:');
appendRow(table, ['Name', 'Last Viewed', 'Link', 'Size'], 'th');
var files = response.result.files;
var table = document.getElementById('content');
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
appendRow(table, [
file.name +" ",
file.viewedByMeTime.split('.')[0]+" ",
link(file.webViewLink),
file.quotaBytesUsed + ' bytes'
])
}
} else {
appendPre('No files found.');
}
});
}
Currently, every time I click a button to activate this function, a new list comes up, what can I add to it that will make the button clear the old list before putting a new one out?
Edit #1:
In this screenshot, you can see that every time I press a button to call on list file function, a new list comes up, instead of having a million list, I want it so everytime I clear the button, it clears the old list and replaces it with a new list
I only want one thing showing at a time.

You can remove all but the header row in your table element before adding new rows to it:
var table = document.getElementById('content');
var rows = table.rows;
while (rows.length > 1) rows[1].parentNode.removeChild(rows[1]);
Full Updated Code
appendPre('Files:');
appendRow(table, ['Name', 'Last Viewed', 'Link', 'Size'], 'th');
function listFiles() {
var x = document.getElementById("ResultShown").value;
var date = new Date();
date.setDate(date.getDate() - 180);
var n = date.toISOString().split('.')[0];
var test = false;
gapi.client.drive.files.list({
pageSize: x,
q: "starred = " + test + " and viewedByMeTime < '" + n + "'",
orderBy: 'quotaBytesUsed desc',
fields: "nextPageToken, files(id, name, viewedByMeTime, mimeType, quotaBytesUsed, webViewLink)",
}
).then(function(response) {
var table = document.getElementById('content');
var files = response.result.files;
var table = document.getElementById('content');
var rows = table.rows;
while (rows.length > 1) rows[1].parentNode.removeChild(rows[1]);
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
appendRow(table, [
file.name + " ",
file.viewedByMeTime.split('.')[0] + " ",
link(file.webViewLink),
file.quotaBytesUsed + ' bytes'
])
}
} else {
appendPre('No files found.');
}
});
}
Note: This answer may seem out of context, because it builds on my answers to additional questions OP has asked concerning the same project.

Related

Event will not delete (Google Scripts with Calendar API)

I am creating a script that takes an existing Google Calendar and matches another calendar with its information. For example, if an event is added in the existing calendar, the other calendar will add an event. If an event date is altered in the existing calendar, the other calendar will delete the event that previously matched and create one to match the altered event. I am having trouble with deleting the events.
I am unsure why I get the error "Failed with error listed_event.deleteEvent is not a function". I have tried for a few days and still have no clue what the issue could be in my code. The line in question is bolded with asterisks, although I have suspicions the issues lie elsewhere.
Any help would be greatly appreciated.
function CleaningCalendar() {
const CleaningId = 'primary';
// Add query parameters in optionalArgs
const HospitableId = 's4h3vvv6r47c3uqiknjhr4hrprgjua5g#import.calendar.google.com';
const optionalArgs = {
timeMin: (new Date()).toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: 300,
orderBy: 'startTime'
// use other optional query parameter here as needed.
};
try {
// call Events.list method to list the calendar events using calendarId optional query parameter
var HospitableEvents = Calendar.Events.list(HospitableId, optionalArgs).items;
var CleaningEvents = Calendar.Events.list(CleaningId, optionalArgs).items;
const property_list = ["BREITHAUPT", "SPRING", "ELLIS 1", "ELLIS 2", "ELLIS 3", "ELLIS 5", "UNION 1", "UNION 2", "UNION 3"]
if (HospitableEvents.length === 0) {
Logger.log('No upcoming events found');
return;
}
for (let i = 0; i < HospitableEvents.length; i++){
event = HospitableEvents[i];
const start_date = event.start.dateTime;
//The fourth semi-colon in the Hospitable Calendar event description pertains to the property name
let first_colon_loc = event.description.indexOf(":");
let second_colon_loc = event.description.slice(first_colon_loc + 1).indexOf(":");
let third_colon_loc = event.description.slice(first_colon_loc + second_colon_loc + 2).indexOf(":");
let fourth_colon_loc = event.description.slice(first_colon_loc + second_colon_loc + third_colon_loc + 3).indexOf(":");
let property_colon_loc = first_colon_loc + second_colon_loc + third_colon_loc + fourth_colon_loc + 5;
let end_of_property_name = event.description.slice(property_colon_loc).indexOf("\n");
let property_name = event.description.slice(property_colon_loc, property_colon_loc + end_of_property_name);
var cleaning_event = {
'summary': property_name,
'location': '',
'description': '',
'start': {
'dateTime': start_date,
'timeZone': 'America/New_York'
},
'end': {
'dateTime': start_date,
'timeZone': 'America/New_York'
},
'recurrence': [
'RRULE:FREQ=DAILY;COUNT=1'
],
'attendees': [''],
'reminders': {
'useDefault': false,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10}
]
}
};
if (property_list.includes(property_name)){
count = 0
for (let i = 0; i < CleaningEvents.length; i++){
if ((property_name == CleaningEvents[i].summary) && (event.start.dateTime == CleaningEvents[i].start.dateTime)){
count = count + 1;
continue;
}}
if (count == 0){
created_event = CalendarApp.getDefaultCalendar().createEvent(property_name,
new Date(start_date),
new Date(start_date));
}}
else{
Logger.log(HospitableEvents[i]);
Logger.log("The above is not valid");
}
}
for (let k = 0; k < CleaningEvents.length; k++){
listed_event = CleaningEvents[k];
var count = 0;
for (let j = 0; j < HospitableEvents.length; j++){
event = HospitableEvents[j];
const start_date = event.start.dateTime;
//The fourth semi-colon in the Hospitable Calendar event description pertains to the property name
let first_colon_loc = event.description.indexOf(":");
let second_colon_loc = event.description.slice(first_colon_loc + 1).indexOf(":");
let third_colon_loc = event.description.slice(first_colon_loc + second_colon_loc + 2).indexOf(":");
let fourth_colon_loc = event.description.slice(first_colon_loc + second_colon_loc + third_colon_loc + 3).indexOf(":");
let property_colon_loc = first_colon_loc + second_colon_loc + third_colon_loc + fourth_colon_loc + 5;
let end_of_property_name = event.description.slice(property_colon_loc).indexOf("\n");
let hospitable_name = event.description.slice(property_colon_loc, property_colon_loc + end_of_property_name);
if ((listed_event.summary == hospitable_name) && (listed_event.start.dateTime == event.start.dateTime)){
count = count + 1;
continue;
}
}
if (count == 0){
**listed_event.deleteEvent();**
Logger.log(listed_event);
}}
}
catch (err) {
// TODO (developer) - Handle exception from Calendar API
Logger.log('Failed with error %s', err.message);
}
}

Comparing JPG files with Photoshop Layers

Is it possible to compare filenames for a set of files that are imported as Photoshop layers ?
I have a folder of 50 jpg images which I have used in a PSD file.
Now I want to check whether all the JPG files are used or not ?
Is it possible to do so ?
As I've said, Photoshop scripting can help you achieve this by using File Objects and basic javascript knowledge. I've modified my old script as you've desired and now it should work well with any nested groups and images.
I highly encourage you to learn scripting and ask questions here wherever you feels confused.
Save below code as 'Script.jsx' and run it from 'File > Scripts > Browse'
Update 2 : Now it saves log.txt file too as per you requested. P.S. Learn from this script and tweak it to your desired result.
// Managing Document
var docs = app.documents;
// Progress Bar
var win = new Window("window{text:'Progress',bounds:[100,100,400,150],bar:Progressbar{bounds:[20,20,280,31] , value:0,maxvalue:100}};");
// assigning activeDocument
if (docs.length != 0) {
var docRef = app.activeDocument;
// Defining the folder
alert("You will be prompted for the folder containing your images.\n" +
"Files will be selected with a '.png'/'.jpg/.jpeg' on the end in the same folder.");
var folder = Folder.selectDialog();
if (!folder) {
exit;
}
var photoFiles = folder.getFiles(/\.(jpg|jpeg|png)$/i);
var matchFiles = [];
var photoFilesName = [];
//Searching for used images
var increment = parseFloat(0);
var divider = parseFloat(100/photoFiles.length);
win.show();
for (var i = 0; i < photoFiles.length; i++) {
increment = increment + divider;
var indexPhotoName = removeExtension(photoFiles[i].displayName);
photoFilesName.push(indexPhotoName);
var doc = activeDocument;
var curLayer;
goThroughLayers(doc, indexPhotoName);
}
function goThroughLayers(parentLayer, targetName) {
for (var i = 0; i < parentLayer.layers.length; i++) {
curLayer = parentLayer.layers[i];
doc.activeLayer = curLayer;
if (curLayer.typename == 'LayerSet') {
goThroughLayers(curLayer, targetName)
} else {
if (curLayer.name == targetName) {
// if (curLayer.name.match(/[e]/ig)) {
matchFiles.push(targetName);
// }
} //end if
} //end else
} //end loop
} //end function
function arr_diff(a1, a2) {
var a = [],
diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
}
function removeExtension(str) {
return str.split('.').slice(0, -1).join('.');
}
var missItems = arr_diff(matchFiles, photoFilesName);
if (missItems.length > 0) {
var missFolder = new Folder(photoFiles[0].path + '/Missed%20Files');
if(!missFolder.exists){
missFolder.create();
}
for (var y = 0; y < photoFiles.length; y++) {
var photoTrimName = removeExtension(photoFiles[y].displayName);
for( var x = 0; x < missItems.length ; x++){
if(photoTrimName == missItems[x]){
photoFiles[y].copy(new File(missFolder+'/'+photoFiles[y].displayName));
}
}
};
win.close();
alert("You've missed total " + missItems.length + " files. Press OK to open folder containing missing files. Log report is generated wherever PSD is saved.");
var FileStr = "";
for(var m=0; m<missItems.length; m++){
FileStr = FileStr + '\n' + (m+1) + '. ' + missItems[m];
}
var str = "Your missed files are : " + FileStr;
saveTxt(str);
missFolder.execute();
} else {
win.close();
saveTxt('All Photos are used');
alert('All Photos are used');
}
} else {
alert('Open atleast one document');
}
function saveTxt(txt)
{
var Name = "LogReport_" + app.activeDocument.name.replace(/\.[^\.]+$/, '');
var Ext = decodeURI(app.activeDocument.name).replace(/^.*\./,'');
if (Ext.toLowerCase() != 'psd')
return;
var Path = app.activeDocument.path;
var saveFile = File(Path + "/" + Name +".txt");
if(saveFile.exists)
saveFile.remove();
saveFile.encoding = "UTF8";
saveFile.open("e", "TEXT", "????");
saveFile.writeln(txt);
saveFile.close();
}
In Javascript, it is possible to get some information related to PSD file layers using PSD.js library

What is the correct way to send large CSV Files to Server using jquery

I have a CSV file with ~20,000 records. I send each line using the $.post method to my server using the FileReader API.
The problem is that the browser is buffering each record before starting to send the data and this way is very slow. I want to send each line separately to show a progressbar where it counts the request number of each line.
As this solution is very slow I'm thinking there are must be other ways of doing this to make it faster. Many thanks to your ideas.
$("#form_file").change(function(e) {
if (e.target.files != undefined) {
var reader = new FileReader();
reader.onload = function(e) {
var rows = e.target.result.split("\n");
var index = rows[0];
index = index.split(";");
gesamt = rows.length - 1;
for (var i = 1; i < rows.length; i++) {
var row = rows[i];
cells = row.split(";");
var dataset = {};
for (var ii = 0; ii < cells.length; ii++) {
var value = cells[ii];
var key = index[ii]
var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
dataset[key] = value;
} catch (e) {
if (e instanceof RangeError) {
if (e.message.toLowerCase().indexOf('invalid array') !== -1) {
printError(e, true);
} else {
printError(e, false);
}
} else {
printError(e, false);
}
}
}
console.log(dataset);
row = insertrow(dataset, i);
$('#progressbar').show();
$('#progressvalue').text(i + '/' + gesamt);
$('#progresstitle').text('(' + dataset.title + ')');
}
};
var test = reader.readAsText(e.target.files.item(0));
}
});
function insertrow(mydata, step) {
var token = "{{app.request.query.get('_token')}}";
mydata = JSON.stringify(mydata);
$.post('preferences/upload?_token=' + token, {
data: mydata
}, function(data) {
$('#info').show();
var html = data.message + '<br />';
$('#info').append(html);
}, "json");
}

How to filter content by category in JavaScript

I have created an accordion with categories. I am pulling the content from a share point list with an ajax call. Each item on the share point list has its category assigned (automotive, entertainment, housing, etc). I need every item to be filtered by category.
https://jsfiddle.net/angelogianopulos/7L392emj/11/
$(document).ready(function() {
/*r container = document.createElement("div");
container.setAttribute('id', 'container');
container.classList.add('container', 'text-center', 'my-5');*/
$.ajax({
url: "http://bc-net/_api/web/lists/GetByTitle('specialDiscounts')/items",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
var items = data.d.results;
console.log(items);
var createRows = function(i, items) {
//Creates 3 Rows inside container
var row = document.createElement("div");
row.setAttribute('id', 'row' + i);
row.classList.add('row', 'animated', 'fadeInUp');
//Appends Row to Container
var getContainer = document.getElementById('automotive');
getContainer.appendChild(row);
createColumns(i, items);
}; //End of creare Rows Function
//Creates columns
var createColumns = function(i, items) {
for (var j = i; j < (i + 3); j++) {
//Creates 3 Columns inside the 3 rows
var columns = document.createElement("div");
columns.setAttribute('id', 'columns' + j);
columns.classList.add('col-md-4');
//appends the 3 columns inside the rows
var getRow = document.getElementById('row' + i);
getRow.appendChild(columns);
//Create single News
var singleNews = document.createElement("div");
singleNews.setAttribute('id', 'singleNews' + j);
singleNews.classList.add("single-news", "mb-4");
var getColumns = document.getElementById('columns' + j);
getColumns.appendChild(singleNews);
//Inside Row
var insideRow = document.createElement("div");
insideRow.setAttribute('id', 'insideRow' + j);
insideRow.classList.add('row');
var getsingleNews = document.getElementById('singleNews' + j);
getsingleNews.appendChild(insideRow);
//Col-md-3
var insideCol = document.createElement("div");
insideCol.setAttribute('id', 'insideCol' + j);
insideCol.classList.add('col-md-3');
//Col-md-9
var insideColRight = document.createElement("div");
insideColRight.setAttribute('id', 'insideColRight' + j);
insideColRight.classList.add('col-md-9');
var getInsideRow = document.getElementById('insideRow' + j);
getInsideRow.appendChild(insideCol);
getInsideRow.appendChild(insideColRight);
//Rounded Image Class
var rounded = document.createElement("div");
rounded.setAttribute('id', 'rounded' + j);
rounded.classList.add('rounded', 'z-depth-1', 'mb-4');
var getinsideCol = document.getElementById('insideCol' + j);
getinsideCol.appendChild(rounded);
//Pulls the images from the list
var image = document.createElement("img");
image.setAttribute('id', 'image' + j);
image.classList.add("img-fluid");
image.src = items[j].Image.Url;
var getRounded = document.getElementById('rounded' + j);
getRounded.appendChild(image);
//Pulls header from the list
var title = document.createElement("p");
title.setAttribute('id', 'title' + j);
title.innerHTML = items[j].Title;
title.classList.add("font-weight-bold", "dark-grey-text");
insideColRight.appendChild(title);
var justifyContent = document.createElement('div');
justifyContent.setAttribute('id', 'justifyContent' + j);
justifyContent.classList.add('d-flex', 'justify-content-between', 'topSpace');
insideColRight.appendChild(justifyContent);
var textTruncate = document.createElement('div');
textTruncate.setAttribute('id', 'textTruncate' + j);
textTruncate.classList.add('col-11', 'text-truncate', 'pl-0', 'mb-3');
justifyContent.appendChild(textTruncate);
//Pulls anchor from the list
var anchor = document.createElement("a");
anchor.setAttribute('id', 'anchor' + j);
anchor.setAttribute('href', items[j].Link.Url, +j);
anchor.setAttribute('target', '_blank', +j);
anchor.classList.add("dark-grey-text");
anchor.innerHTML = items[j].Description;
textTruncate.appendChild(anchor);
var arrowAnchor = document.createElement("a");
arrowAnchor.setAttribute('id', 'arrowAnchor' + j);
arrowAnchor.setAttribute('target', '_blank' + j);
arrowAnchor.setAttribute('href', items[j].Link.Url, +j);
justifyContent.appendChild(arrowAnchor);
var iconArrow = document.createElement('i');
iconArrow.classList.add('fas', 'fa-angle-double-right');
var getarrowAnchor = document.getElementById('arrowAnchor' + j);
getarrowAnchor.appendChild(iconArrow);
//var test = document.getElementById( 'arrowAnchor' + j);
//test.onclick = function() {
// console.log('Hello');
//}
} //End of j Loop
return;
} // End of createColumns function
//Array of categories
var catGroup = [];
console.log(catGroup);
if (items.length > 0) {
for (var i = 0; i < items.length; i++) {
var categories = items[i].Category;
console.log(categories)
catGroup.push(categories);
if (catGroup[i] === "Automotive") {
var automotive = document.getElementById('automotive');
console.log(catGroup[i]);
}
if (catGroup[i] === "Entertainment") {
var entertainment = document.getElementById('entertainment');
console.log(catGroup[i]);
}
if (catGroup[i] === "Health and Beauty") {
var health = document.getElementById('health');
console.log(catGroup[i]);
}
if (catGroup[i] === "Travel") {
var travel = document.getElementById('travel');
console.log(catGroup[i]);
}
if (catGroup[i] === "Electronics") {
var electronics = document.getElementById('electronics');
console.log(catGroup[i]);
}
if (catGroup[i] === "Services") {
var services = document.getElementById('services');
console.log(catGroup[i]);
}
if (catGroup[i] === "Housing") {
var housing = document.getElementById('housing');
console.log(catGroup[i]);
} else {}
if (i % 3 == 0) {
createRows(i, items);
} //end of % if statement
} //End of for loop
} //End of if item.length statement
},
error: function(data) {
alert("Error: " + data);
}
}); //End Service Icons //End Service Icons
}); //End ready function
I expect every item to be placed by category in its own content panelenter image description here
After looking into your question, what I understood is you just want to filter your data on the basis of 'category assigned'.
I will refer you to use JavaScript Filter like so:
const result = items.filter(Category => Category === "Automotive" );
Or, if you can use Lodash, there are a lot of ways to filter and even you can group by the Category.
You can check out here for Lodash:
Documentation Lodash
If I misunderstood your question, please let me know so I can edit my answer.

What's wrong with my Google Spreadsheet Script?

I am trying to create a script to automatically take information from a google sheet and put each row of data into individual, formatted docs. However when I run the script it either populates the data as "DOB" (in the date of birth spot) or as a different value. I am not a very good programmer and any help is appreciated. Thanks,
function createDocument() {
var headers =Sheets.Spreadsheets.Values.get('1oycOOxDIAhbAI6Yq54KF4GAnjfVcttywYXOpKDBLHag', ('A1', 'B1', 'C1', 'D1', 'H1', 'I1', 'N1', 'O1'));
var tactics = Sheets.Spreadsheets.Values.get('1oycOOxDIAhbAI6Yq54KF4GAnjfVcttywYXOpKDBLHag', ('A4:O14'));
var templateId = '1NJQHx4TWRQ3EQle5aLr-QV4uqD-tSR8TMP2-f6QjPmY';
for(var i = 0; i < tactics.values.length; i++){
var Patient_name = tactics.values[i][0];
var Date_Scheduled = tactics.values[i][0];
var Surgery_Posting = tactics.values[i][0];
var Start_Time = tactics.values[i][0];
var Hospital = tactics.values[i][0];
//Make a copy of the template file
var documentId = DriveApp.getFileById(templateId).makeCopy().getId();
//Rename the copied file
DriveApp.getFileById(documentId).setName(Patient_name + ' Surgery Posting');
//Get the document body as a variable
var body = DocumentApp.openById(documentId).getBody();
//Insert the Patient_name
body.replaceText('##Patient_name##', Patient_name)
//Insert the Date_Scheduled
body.replaceText('##Date_Scheduled##', Date_Scheduled)
//Insert the Surgery_Posting
body.replaceText('##Surgery_Posting##', Surgery_Posting)
//Insert the Start_Time
body.replaceText('##Start_Time##', Start_Time)
//Insert the Hospital
body.replaceText('##Hospital##', Hospital)
//Append tactics
parseTactics(headers.values[0], tactics.values[i], body);
}
}
function parseTactics(headers, tactics, body){
for(var i = 0; i < tactics.length; i++){
{tactics[i] != '' &&
body.appendListItem(headers[i] + ' | ' + tactics[i] + ' net').setGlyphType(DocumentApp.GlyphType.BULLET);
}
}
}
The column position after the iterator was not changed to the next column.
var Patient_name = tactics.values[i][0];
var Date_Scheduled = tactics.values[i][1]; //this last part the 0 to 1

Categories