Pages

Se afișează postările cu eticheta source code. Afișați toate postările
Se afișează postările cu eticheta source code. Afișați toate postările

marți, 25 martie 2025

News : Google Apps Script - find duplicate files in google drive.

For today, a simple GAScript source code to add into spreadsheet the duplicate files from Google drive.
This Google Apps Script finds duplicate files in Google Drive by comparing file sizes and optionally file types. It then displays the results in a spreadsheet with detailed information about each duplicate file. The script collects information about all files in Drive. Files are grouped by their size and optionally file type. Any group with more than one file is considered a set of duplicates These duplicate sets are displayed in the spreadsheet
Functions
  • checkDuplicatesInDrive(): Main function that searches your entire Google Drive for duplicates
  • checkDuplicatesInFolder(): Alternative function that searches a specific folder and its subfolders
  • findDuplicateFiles(): Core function that identifies duplicate files based on size and type
  • addDuplicatesToSheet(): Adds the found duplicates to a spreadsheet
I used artificial inteligence and this help me much ...
/**
 * Main function to check files in the root folder and add duplicates to the active spreadsheet
 */
function checkDuplicatesInDrive() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  
  // Clear the sheet and set up headers
  sheet.clear();
  sheet.appendRow(["Group", "File Name", "Size", "Type", "File Path", "Date Created", "Last Updated", "URL"]);
  sheet.getRange(1, 1, 1, 8).setFontWeight("bold").setBackground("#f3f3f3");
  
  // Find all duplicates
  const duplicates = findDuplicateFiles(true);
  
  // Check if any duplicates were found
  if (Object.keys(duplicates).length === 0) {
    sheet.appendRow(["No duplicate files found"]);
    sheet.autoResizeColumns(1, 8);
    return;
  }
  
  // Add duplicates to the sheet
  addDuplicatesToSheet(duplicates, sheet);
  
  // Auto-resize columns
  sheet.autoResizeColumns(1, 8);
}

/**
 * Adds duplicate files to the specified sheet
 */
function addDuplicatesToSheet(duplicates, sheet) {
  let groupNumber = 1;
  let rowIndex = 2;
  let totalDuplicateFiles = 0;
  
  for (const key in duplicates) {
    const files = duplicates[key];
    totalDuplicateFiles += files.length;
    
    files.forEach((file, index) => {
      // Get file path
      const filePath = getFilePath(file.id);
      
      sheet.appendRow([
        groupNumber,
        file.name,
        formatFileSize(file.size),
        file.mimeType,
        filePath,
        file.dateCreated.toLocaleString(),
        file.lastUpdated.toLocaleString(),
        file.url
      ]);
      
      // Add hyperlink to the file URL
      sheet.getRange(rowIndex, 8).setFormula(`=HYPERLINK("${file.url}","Open File")`);
      
      rowIndex++;
    });
    
    groupNumber++;
  }
  
  // Add summary at the bottom - only if we have duplicates
  if (totalDuplicateFiles > 0) {
    sheet.appendRow(["SUMMARY"]);
    sheet.appendRow([`Found ${totalDuplicateFiles} duplicate files in ${groupNumber - 1} groups.`]);
  }
  
  return totalDuplicateFiles;
}

/**
 * Gets the file path for a given file ID
 */
function getFilePath(fileId) {
  try {
    const file = DriveApp.getFileById(fileId);
    const parents = file.getParents();
    
    if (parents.hasNext()) {
      const parent = parents.next();
      return getFolderPath(parent) + "/" + file.getName();
    } else {
      return "/" + file.getName();
    }
  } catch (e) {
    return "Path not available";
  }
}

/**
 * Gets the folder path for a given folder
 */
function getFolderPath(folder) {
  try {
    const parents = folder.getParents();
    
    if (!parents.hasNext()) {
      return "/" + folder.getName();
    }
    
    const parent = parents.next();
    return getFolderPath(parent) + "/" + folder.getName();
  } catch (e) {
    return "/Unknown";
  }
}

/**
 * Finds duplicate files in Google Drive based on file size and optionally file type.
 * @param {boolean} considerFileType Whether to consider file type when finding duplicates (default: true)
 * @param {string} folderId Optional folder ID to search in. If not provided, searches in the entire Drive.
 * @return {Object} An object containing groups of duplicate files
 */
function findDuplicateFiles(considerFileType = true, folderId = null) {
  // Create a map to store files by their size (and optionally type)
  const fileMap = {};
  
  // Get files to check
  let files;
  if (folderId) {
    const folder = DriveApp.getFolderById(folderId);
    files = folder.getFiles();
  } else {
    files = DriveApp.getFiles();
  }
  
  // Process each file
  while (files.hasNext()) {
    const file = files.next();
    // Skip Google Docs, Sheets, etc. as they don't have a fixed size
    if (file.getSize() === 0) continue;
    
    const fileSize = file.getSize();
    const mimeType = file.getMimeType();
    
    // Create a key based on file size and optionally type
    let key = fileSize.toString();
    if (considerFileType) {
      key += '_' + mimeType;
    }
    
    // Add file to the map
    if (!fileMap[key]) {
      fileMap[key] = [];
    }
    
    fileMap[key].push({
      id: file.getId(),
      name: file.getName(),
      size: fileSize,
      mimeType: mimeType,
      url: file.getUrl(),
      dateCreated: file.getDateCreated(),
      lastUpdated: file.getLastUpdated()
    });
  }
  
  // Filter out unique files (groups with only one file)
  const duplicates = {};
  for (const key in fileMap) {
    if (fileMap[key].length > 1) {
      duplicates[key] = fileMap[key];
    }
  }
  
  return duplicates;
}

/**
 * Alternative function to check files in a specific folder and its subfolders
 */
function checkDuplicatesInFolder() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  
  // Clear the sheet and set up headers
  sheet.clear();
  sheet.appendRow(["Group", "File Name", "Size", "Type", "File Path", "Date Created", "Last Updated", "URL"]);
  sheet.getRange(1, 1, 1, 8).setFontWeight("bold").setBackground("#f3f3f3");
  
  // Collect all files from the folder and subfolders
  var fileMap = {};
  var rootFolder = DriveApp.getRootFolder(); // Change this to your specific folder if needed
  collectFilesFromFolder(rootFolder, fileMap);
  
  // Filter out unique files
  const duplicates = {};
  for (const key in fileMap) {
    if (fileMap[key].length > 1) {
      duplicates[key] = fileMap[key];
    }
  }
  
  // Check if any duplicates were found
  if (Object.keys(duplicates).length === 0) {
    sheet.appendRow(["No duplicate files found"]);
    sheet.autoResizeColumns(1, 8);
    return;
  }
  
  // Add duplicates to the sheet
  addDuplicatesToSheet(duplicates, sheet);
  
  // Auto-resize columns
  sheet.autoResizeColumns(1, 8);
}

/**
 * Recursively collects files from a folder and its subfolders
 */
function collectFilesFromFolder(folder, fileMap, considerFileType = true) {
  // Process files in this folder
  var files = folder.getFiles();
  while (files.hasNext()) {
    const file = files.next();
    // Skip Google Docs, Sheets, etc. as they don't have a fixed size
    if (file.getSize() === 0) continue;
    
    const fileSize = file.getSize();
    const mimeType = file.getMimeType();
    
    // Create a key based on file size and optionally type
    let key = fileSize.toString();
    if (considerFileType) {
      key += '_' + mimeType;
    }
    
    // Add file to the map
    if (!fileMap[key]) {
      fileMap[key] = [];
    }
    
    fileMap[key].push({
      id: file.getId(),
      name: file.getName(),
      size: fileSize,
      mimeType: mimeType,
      url: file.getUrl(),
      dateCreated: file.getDateCreated(),
      lastUpdated: file.getLastUpdated()
    });
  }
  
  // Process subfolders
  var subfolders = folder.getFolders();
  while (subfolders.hasNext()) {
    var subfolder = subfolders.next();
    collectFilesFromFolder(subfolder, fileMap, considerFileType);
  }
}

/**
 * Helper function to format file size in a human-readable format
 */
function formatFileSize(bytes) {
  if (bytes < 1024) return bytes + " bytes";
  else if (bytes < 1048576) return (bytes / 1024).toFixed(2) + " KB";
  else if (bytes < 1073741824) return (bytes / 1048576).toFixed(2) + " MB";
  else return (bytes / 1073741824).toFixed(2) + " GB";
}

/**
 * Creates a new Google Spreadsheet with the duplicate files report
 */
function createDuplicateFilesSpreadsheet() {
  const duplicates = findDuplicateFiles(true);
  
  // Create a new spreadsheet
  const ss = SpreadsheetApp.create("Duplicate Files Report - " + new Date().toLocaleString());
  const sheet = ss.getActiveSheet();
  
  // Set up headers
  sheet.appendRow(["Group", "File Name", "Size", "Type", "File Path", "Date Created", "Last Updated", "URL"]);
  
  // Format header row
  sheet.getRange(1, 1, 1, 8).setFontWeight("bold").setBackground("#f3f3f3");
  
  // Check if any duplicates were found
  if (Object.keys(duplicates).length === 0) {
    sheet.appendRow(["No duplicate files found"]);
    sheet.autoResizeColumns(1, 8);
    return ss.getUrl();
  }
  
  // Add duplicates to the sheet
  addDuplicatesToSheet(duplicates, sheet);
  
  // Auto-resize columns
  sheet.autoResizeColumns(1, 8);
  
  Logger.log(`Spreadsheet created: ${ss.getUrl()}`);
  return ss.getUrl();
}
See the result into the spreadsheet:

duminică, 29 decembrie 2024

Blender 3D : ... all available nodes !

An old surce code in python for Blender 3D to see available nodes :
import bpy

node_tree = bpy.context.object.active_material.node_tree

location_x = 0
location_y = 0

for type in dir(bpy.types):
    real_type = getattr(bpy.types, type)
    if issubclass(real_type, bpy.types.ShaderNode):
        try:
            node = node_tree.nodes.new(type)
            node.width = 250
            node.location = (location_x, location_y)
            location_x += 300
            if location_x > 3000:
                location_x = 0
                location_y -= 600
        except:
            pass

joi, 15 august 2024

Codapi an interactive code playground service.

Interactive code examples for all types of technical writing.
Embed executable code snippets directly into your product documentation, online course or blog post.
Supports 30 playgrounds out of the box, plus custom sandboxes if you need them.
You can run in-browser playgrounds without a server, use the Codapi cloud, or host a sandbox server yourself.
Read more on the official website.

CodePen : Home RoughJS and Wired elements example .

duminică, 4 august 2024

Inkscape : Create an extension for inkscape.

You can create your own extensions in inkscape with all features you need to improve the working area.
One extension can have minimum two file: the basic Python source code and another file with the graphic user interface ...
The source code of Python file can be link with the G.U.I. source code type file INX.
The source code for python can be customized and this is the main reason is no need to add it here.
Let's see the source code for the INX file:
<?xml version="1.0" encoding="UTF-8"?>
<inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension">
    <name>Default extension example</name>
    <id>default.extensions.example</id>
    <param name="tab" type="notebook">
        <page name="Options" gui-text="Options">
            <param name="value_int" type="int" min="0" max="9" gui-text="INT type value from 0 up to 9 : ">10</param>
            <param name="value_bool" type="bool" gui-text="BOOL value set to false : ">false</param>
            <param name="value_space" type="float" gui-text="FLOAT value set to 0.1 custom range min 0.0 up max=99.0 : " min="0.0" max="99.0">0.1</param>
                <param name="option_group selection" type="optiongroup" appearance="combo" gui-text="Options :">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
            </param>
		<param name="grouppick" type="bool" gui-text="selection pick ..." gui-description="This is gui-description">false</param>
            <param name="pickmode" type="optiongroup" appearance="combo" gui-text="pick values group:">
                <option value="first">first</option>
                <option value="second">second</option>
            </param> 
	</page>
        <page name="Help" gui-text="Help for default extension example">
            <label xml:space="preserve">This is example of default extension example
	You can use this INX file and PY files type named 'default_extension_example'</label>
        </page>
    </param>
    <effect>
        <object-type>all</object-type>
        <effects-menu>
            <submenu name="catafest"/>
        </effects-menu>
    </effect>
    <script>
        <command location="inx" interpreter="python">default_extension_example.py</command>
    </script>
</inkscape-extension>
Bellow you can see some screenshots with these result

marți, 6 februarie 2024

News : Shader Editor source code.

If you follow my blogger, you've seen some shaders I made for my background phone.
These shaders are created with this Android app called Shader Editor.
You can find the source code of this application on this GitHub project.

vineri, 12 ianuarie 2024

CodePen: CodePen Home WebGL Flower Pattern (Voronoi diagram GLSL)

You can find good web development with a great graphics on Ksenia Kondrashova codepen account.
See this example named: CodePen Home WebGL Flower Pattern (Voronoi diagram GLSL):

miercuri, 14 septembrie 2022

CodePen: Simple example with css-doodle web component.

This is a simple example with css-doodle javascript web component for drawing patterns with CSS.

luni, 18 aprilie 2022

BVH and three.js meshes implementation.

This article is about the BVH implementation to speed up raycasting and enable spatial queries against three.js meshes.
The full source code can be found on this GitHub project.
You can see a good example on this demo page with this Tyrannosaurus rex

sâmbătă, 5 martie 2022

miercuri, 24 noiembrie 2021

CodePen: ... challenges every time.

This website comes with challenges all the time, see this week example:
THIS WEEK’S CHALLENGE,Book Text ...Your challenge: Give this book excerpt some tasteful text styles.
Here's what I managed to do for this week:

marți, 23 noiembrie 2021

CodePen: How can share sketchfab 3D models.

The Viewer API lets you build web apps on top of Sketchfab’s 3D viewer. With the API, you can control the viewer in JavaScript. It provides functions for starting, stopping the viewer, moving the camera, taking screenshots and more.

miercuri, 18 august 2021

News : Unity comes with LookDev Studio.

... most people love this game engine, today a new feature comes to show us how good is this game engine. you can see also another character named FIA.
Artists – no matter their expertise – need a place to quickly import, iterate on, and refine their art.
You can find a source code with this project on the GitHub website.

duminică, 1 august 2021

CodePen: RGB colors.

Example with the javascript programming language presented in my codepen account solves the following issues:
  • create HTML tag div for each for iteration;
  • create an id for each div tag;
  • build an RGB color with red, green, and blue using a random function;
  • read that id and used to set the color background of each div;
  • print the RGB value for each color and set background color;
Let's see the example:

sâmbătă, 17 aprilie 2021

CodePen: Lottie for Web, Android, iOS, React Native, and Windows - 001.

Lottie is a mobile library for Web, and iOS that parses Adobe After Effects animations exported as JSON with Bodymovin and renders them natively on mobile!, see GitHub project.
You can find Lottie files on this website
This is a simple example with lottie-player.js:

duminică, 4 aprilie 2021

CodePen: A simple progressbar with CSS.

A simple test with CSS about how to create two simple progress bars. The code source of this example - https://codepen.io/catafest/pen/rNjmdwa show us about the cascading source code in CSS and how this works pe properties in CSS. This difference of the source code in CSS change the speed of the animation:
 animation: animate 6s ease-in-out infinite;
...
 animation: animate 1s ease-in-out infinite;
Some changes to the CSS source code are not allowed because they have no effect on the end result or must be used in order to complete the base code and have the end result. Another good example is flex:
display: flex;
On the parent element also changes how width and height work. CSS codes defines have no effect on a flex container. ... I can tell you that it is not very easy to change a project based on CSS, so the steps of designing and building a website are very important.

duminică, 14 martie 2021

OpenProcessing - simple tree_001.

This is modified example from this in order to build another good tree using openprocessing website interface.
You can see this example on my account.
Let's see the source code:
/*--based on https://openprocessing.org/sketch/396851--*/

var nbranchs = 73;
function setup() {
  createCanvas(640, 400);
  background(0, 0, 128);
  
  noFill();
  stroke(128);
  noLoop();
}

function draw() {
  tree(100, 200, 150, 350);
}
function mousePressed() {
  background(0, 0, 128);
  redraw();
}

function branch(x, y, dx, dy) {
  var sign = random(dx+1.0)/(abs(dx)+5.0);
  
  for (var i = 0; i <= x; i += 3) {
    var idx = i/x;
    
    var xi = bezierPoint(x, x + dx/2,   x + dx, x + dx, idx);
    var yi = bezierPoint(y, y, y + dy, y + dy, idx);

    line(xi, yi, xi + sign*random(8), yi + random(18));  
	
  }
}

function tree(left, right, top, bottom) {
  for (var idx = 0; idx < nbranchs; idx += 1) {
    
    // choose a random y position
    var y = random(bottom, top);
		
    
    // choose a random x position inside of a triangle
    var dx = map(y, bottom, top, 0.0, (right-left)/2.0);
    var x = random(left + dx, right - dx);
		
    var x1 = random(left + dx, right - dx);
    
		// choose the size of the branch according to the position on the tree
    var w = map (x, left, right, random(-25) -25, random(25)+25) + 1;
    var h = map (y, bottom, top, 5 +random(20), 5);
    
		var w1 = map (x, left, right, random(-35), random(35)) + 3;
    var h1 = map (y, bottom, top, random(10), random(10));
    // randonize the size
    var dw = random(-10, 5);
    var dh = random (-5, 5);
  	
		var dw1 = random(-5, 1);
    var dh1 = random (-1, 1);
    // create the new branch
		branch(x1, y, w1 + dw1, h1 + dh1);
		stroke(random(0),random(128),random(15));
		branch(x1, y, w1 + dw1, h1 + dh1);
		stroke(random(25),random(255),random(50));
    branch(x, y, w + dw, h + dh);
    
  }
}