Spliting String and getting appropriate value in JavaScript - javascript
I have a string where |||| means next to it is the directory. ||| means the user is allowed to access this directory and || means the files allocated to these users follow.
I need to find allocated file names of a specific user from this string. I have tried to split the string and assign values to an array but I am not able to get the result I'm looking for.
This is the string:
||||Root|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,||||1400842226669|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,||||1401191909489|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,LimitTest_20140528164643.xlsx,
And here is my attempt:
function getData() {
var user = 'km11285c';
var value = "||||Root|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,||||1400842226669|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,||||1401191909489|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,LimitTest_20140528164643.xlsx,";
var users = null;
var files = null;
var Dir = value.split("||||");
var arrayLength = Dir.length;
for (var i = 0; i < arrayLength; i++) {
users = Dir[i].split("|||");
}
return users;
}
console.log(getData());
and the jsFiddle
I changed your jsfiddle example a bit so maybe you need to change the code here and there, but something like this should work:
function buildTree(data) {
var tree = [];
var dirs = data.split("||||");
// Remove the first entry in the array, since it should be empty.
dirs.splice(0, 1);
for (var i = 0; i < dirs.length; ++i) {
var tempArray = dirs[i].split("|||");
var dirName = tempArray[0];
var usersAndFiles = tempArray[1];
tempArray = usersAndFiles.split("||");
var users = tempArray[0];
var files = tempArray[1];
var treeDir = { name: dirName };
treeDir.users = users.split(",");
treeDir.files = files.split(",");
tree.push(treeDir);
}
return tree;
}
function getData() {
var user = 'km11285c';
var value="||||Root|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,||||1400842226669|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,||||1401191909489|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,LimitTest_20140528164643.xlsx,";
var tree = buildTree(value);
for (var i = 0; i < tree.length; ++i) {
var dir = tree[i];
if (dir.users.indexOf(user) >= 0) {
console.log("User '" + user + "' has access to directory '" + dir.name + "', which contains these files: " + dir.files.join(","));
}
}
}
getData();
Related
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
Google script - parse HTML from Website Forum - and Write Data to Sheet
I'm getting HTML from a forum url, and parsing the post count of the user from their profile page. I don't know how to write the parsed number into the Google spreadsheet. It should go account by account in column B till last row and update the column A with count. The script doesn't give me any errors, but it doesn't set the retrieved value into the spreadsheet. function msg(message){ Browser.msgBox(message); } function onOpen() { var ui = SpreadsheetApp.getUi(); ui.createMenu("Update") .addItem('Update Table', 'updatePosts') .addToUi(); } function getPostCount(profileUrl){ var html = UrlFetchApp.fetch(profileUrl).getContentText(); var sliced = html.slice(0,html.search('Posts Per Day')); sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length); postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>")); return postCount; } function updatePosts(){ if(arguments[0]===false){ showAlert = false; } else { showAlert=true; } var spreadSheet = SpreadsheetApp.getActiveSpreadsheet(); var accountSheet = spreadSheet.getSheetByName("account-stats"); var statsLastCol = statsSheet.getLastColumn(); var accountCount = accountSheet.getLastRow(); var newValue = 0; var oldValue = 0; var totalNewPosts = 0; for (var i=2; i<=accountCount; i++){ newValue = parseInt(getPostCount(accountSheet.getRange(i, 9).getValue())); oldValue = parseInt(accountSheet.getRange(i, 7).getValue()); totalNewPosts = totalNewPosts + newValue - oldValue; accountSheet.getRange(i, 7).setValue(newValue); statsSheet.getRange(i,statsLastCol).setValue(newValue-todaysValue); } if(showAlert==false){ return 0; } msg(totalNewPosts+" new post found!"); } function valinar(needle, haystack){ haystack = haystack[0]; for (var i in haystack){ if(haystack[i]==needle){ return true; } } return false; } The is the first time I'm doing something like this and working from an example from other site. I have one more question. In function getPostCount I send the function profileurl. Where do I declare that ?
Here is how you get the URL out of the spreadsheet: function getPostCount(profileUrl){ var ss = SpreadsheetApp.getActiveSpreadsheet(); var thisSheet = ss.getSheetByName("List1"); var getNumberOfRows = thisSheet.getLastRow(); var urlProfile = ""; var sliced = ""; var A_Column = ""; var arrayIndex = 0; var rngA2Bx = thisSheet.getRange(2, 2, getNumberOfRows, 1).getValues(); for (var i = 2; i < getNumberOfRows + 1; i++) { //Start getting urls from row 2 //Logger.log('count i: ' + i); arrayIndex = i-2; urlProfile = rngA2Bx[arrayIndex][0]; //Logger.log('urlProfile: ' + urlProfile); var html = UrlFetchApp.fetch(urlProfile).getContentText(); sliced = html.slice(0,html.search('Posts Per Day')); var postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>")); sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length); postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>")); Logger.log('postCount: ' + postCount); A_Column = thisSheet.getRange(i, 1); A_Column.setValue(postCount); }; } You're missing var in front of one of your variables: postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>")); That won't work. Need to put var in front. var postCount = .... In this function: function updatePosts(){ if(arguments[0]===false){ showAlert = false; } else { showAlert=true; } There is no array named arguments anywhere in your code. Where is arguments defined and how is it getting any values put into it?
How to save this in a JS variable?
I would like to know how to save the output of this into a "var a=" navigator.plugins.refresh(false); var numPlugins = navigator.plugins.length; for (var i = 0; i < numPlugins; i++){ var plugin = navigator.plugins[i]; if (plugin) { document.write(plugin.name + plugin.description + plugin.filename) } }
Declare a outside of the loop and define it as an empty string, then append results to it as you go: navigator.plugins.refresh(false); var numPlugins = navigator.plugins.length; var a = ''; for (var i = 0; i < numPlugins; i++){ var plugin = navigator.plugins[i]; if (plugin) { a += plugin.name + plugin.description + plugin.filename; } } You may want to use an array of strings though, since you could have many plugins: navigator.plugins.refresh(false); var numPlugins = navigator.plugins.length; var a = []; for (var i = 0; i < numPlugins; i++){ var plugin = navigator.plugins[i]; if (plugin) { a.push(plugin.name + plugin.description + plugin.filename); } } EDIT If you need to hash a into something: var hash = yourMd5Function(a); Or for the second example: var b = a.join(','); // "plugin1,plugin2,..." for example var hash = yourMd5Function(b);
generate list of variables from a FOR loop
var select = []; for (var i = 0; i < nameslots; i += 1) { select[i] = this.value; } This is an extract of my code. I want to generate a list of variables (select1, select2, etc. depending on the length of nameslots in the for. This doesn't seem to be working. How can I achieve this? If you require the full code I can post it. EDIT: full code for this specific function. //name and time slots function gennametime() { document.getElementById('slots').innerHTML = ''; var namelist = editnamebox.children, slotnameHtml = '', optionlist; nameslots = document.getElementById('setpresentslots').value; for (var f = 0; f < namelist.length; f += 1) { slotnameHtml += '<option>' + namelist[f].children[0].value + '</option>'; }; var select = []; for (var i = 0; i < nameslots; i += 1) { var slotname = document.createElement('select'), slottime = document.createElement('select'), slotlist = document.createElement('li'); slotname.id = 'personname' + i; slottime.id = 'persontime' + i; slottime.className = 'persontime'; slotname.innerHTML = slotnameHtml; slottime.innerHTML = '<optgroup><option value="1">00:01</option><option value="2">00:02</option><option value="3">00:03</option><option value="4">00:04</option><option value="5">00:05</option><option value="6">00:06</option><option value="7">00:07</option><option value="8">00:08</option><option value="9">00:09</option><option value="10">00:10</option><option value="15">00:15</option><option value="20">00:20</option><option value="25">00:25</option><option value="30">00:30</option><option value="35">00:35</option><option value="40">00:40</option><option value="45">00:45</option><option value="50">00:50</option><option value="55">00:55</option><option value="60">1:00</option><option value="75">1:15</option><option value="90">1:30</option><option value="105">1:45</option><option value="120">2:00</option></optgroup>'; slotlist.appendChild(slotname); slotlist.appendChild(slottime); document.getElementById('slots').appendChild(slotlist); (function (slottime) { slottime.addEventListener("change", function () { select[i] = this.value; }); })(slottime); } }
You'll have to close in the iterator as well in that IIFE (function (slottime, j) { slottime.addEventListener("change", function () { select[j] = this.value; }); })(slottime, i); and it's only updated when the element actually change
The cool thing about JavaScript arrays is that you can add things to them after the fact. var select = []; for(var i = 0; i < nameSlots; i++) { var newValue = this.value; // Push appends the new value to the end of the array. select.push(newValue); }
Merging arrays in JavaScript not working
When I try var a = ar_url2.concat(ar_desc2); to join my arrays into one it returns null. I'm sure it's trivial but I spent a few hours stuck on this now and an explanation as why this is happening would be great. In my code bellow I tried while(ar_url2.length)a.push(ar_url2.shift()); and it returns same null... function agregar() { var i = 0, textarea; var ar_desc = []; while (textarea = document.getElementsByTagName('textarea')[i++]) { if (textarea.id.match(/^desc_([0-9]+)$/)) { ar_desc.push(textarea.id); } } var desc_count_demo = document.getElementById('desc_count').value; var desc_count = desc_count_demo - 1; i = 0; var ar_desc2 = []; var campo = null; while (i <= desc_count) { campo = document.getElementById(ar_desc[i]).value; ar_desc2[ar_desc[i]] = campo; i++; } i = 0; var input; var ar_url = []; while (input = document.getElementsByTagName('input')[i++]) { if (input.id.match(/^url_([0-9]+)$/)) { ar_url.push(input.id); } } var url_count_demo2 = document.getElementById('url_count').value; var url_count2 = url_count_demo2 - 1; i = 0; var ar_url2 = []; while (i <= url_count2) { campo = document.getElementById(ar_url[i]).value; ar_url2[ar_url[i]] = campo; i++; } // var a = Array.prototype.concat.call(ar_url2, ar_desc2); while (ar_url2.length) a.push(ar_url2.shift()); function url(data) { var ret = []; for (var d in data) ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d])); return ret.join("&"); } window.open('alta1.php?'+url(a)); } EDIT: If I pass to function url(ar_url2) or url(ar_desc2) the returned values in the URL are http://localhost/proj1/alta1.php?url_0=inpit&url_1=input and http://localhost/proj1/alta1.php?desc_0=input&desc_1=input But still cannot merge both into one...
One thing I see is your ar_url Array is filled by: while(input=document.getElementsByTagName('input')[i++]){ if(input.id.match(/^url_([0-9]+)$/)){ ar_url.push(input.id); } } Since you the putting the whole id in the array, it will be filled with things like: 'url_0', 'url_1', 'url_2', etc... Later you do: ar_url2[ar_url[i]] = campo; When you index into ar_url, you get out the 'url_XXX' strings. That means you are setting the 'url_XXX' properties on ar_url2 instead of filling in the elements of the array. Try changing your second loop to: while(input=document.getElementsByTagName('input')[i++]){ var result; if(result = input.id.match(/^url_([0-9]+)$/)){ ar_url.push(+result[1]); } } To use the value captured in the ([0-9]+) portion of the RegExp instead of the entire 'url_XXX' string.