Snippets Collections
$filename = 'D:\PS\CSV\PowerShell-EventLogs.csv'    

# Get file size in bytes
(Get-Item -Path $filename).Length

# get file size in KB in PowerShell
(Get-Item -Path $filename).Length/1KB

# get file size in MB in PowerShell   
(Get-Item -Path $filename).Length/1MB

# get file size in GB in PowerShell
(Get-Item -Path $filename).Length/1GB  
        try (RandomAccessFile fileOnDisk = new RandomAccessFile(storage + path, "rw");
             FileChannel channel = fileOnDisk.getChannel()) {
            channel.lock(); //Exception si un autre process essaie d'y accéder
            channel.truncate(0); //Sinon le fichier n'est pas écrasé
            fileOnDisk.write(bytes);
        } catch (IOException e) {
            throw new StorageException(ERROR_SAVING_FILE, e.getMessage());
        }
//MARK: - Document Picker

// From your project's capabilities, enable both the iCloud and the Key-Sharing.

@IBAction func pickDocumentPressed(_ sender: Any) {
       presentDocumentPicker()
    }

extension OffersReceivedViewController : UIDocumentPickerDelegate,UINavigationControllerDelegate {
    
    func presentDocumentPicker() {
        let sTypes = getSupportedTypes()
        let documentPickerController = UIDocumentPickerViewController(
            forOpeningContentTypes: sTypes)
        
        documentPickerController.delegate = self
        documentPickerController.allowsMultipleSelection = false
        SVProgressHUD.show()
        self.present(documentPickerController, animated: true) {
            SVProgressHUD.dismiss()
        }
    }
    
    public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let myURL = urls.first else {
            return
        }
        print("import result : \(myURL)")
        print("get Image Url")
        fileUrl = myURL
    }
    
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        print("view was cancelled")
        dismiss(animated: true, completion: nil)
    }
    
    func getSupportedTypes() -> [UTType] {
        let supportedTypes : [UTType] = [UTType.utf8TabSeparatedText, UTType.rtf,    UTType.pdf, UTType.webArchive, UTType.image, UTType.jpeg,    UTType.tiff, UTType.gif, UTType.png, UTType.bmp, UTType.ico,    UTType.rawImage, UTType.svg, UTType.livePhoto, UTType.movie,    UTType.video, UTType.audio, UTType.quickTimeMovie, UTType.mpeg,    UTType.mpeg2Video, UTType.mpeg2TransportStream, UTType.mp3,    UTType.mpeg4Movie, UTType.mpeg4Audio, UTType.avi, UTType.aiff,    UTType.wav, UTType.midi, UTType.archive, UTType.gzip, UTType.bz2,    UTType.zip, UTType.appleArchive, UTType.spreadsheet, UTType.epub]
        return supportedTypes
    }
}
let supportedTypes : [UTType] = [UTType.utf8TabSeparatedText, UTType.rtf,    UTType.pdf, UTType.webArchive, UTType.image, UTType.jpeg,    UTType.tiff, UTType.gif, UTType.png, UTType.bmp, UTType.ico,    UTType.rawImage, UTType.svg, UTType.livePhoto, UTType.movie,    UTType.video, UTType.audio, UTType.quickTimeMovie, UTType.mpeg,    UTType.mpeg2Video, UTType.mpeg2TransportStream, UTType.mp3,    UTType.mpeg4Movie, UTType.mpeg4Audio, UTType.avi, UTType.aiff,    UTType.wav, UTType.midi, UTType.archive, UTType.gzip, UTType.bz2,    UTType.zip, UTType.appleArchive, UTType.spreadsheet, UTType.epub]
def create_dir(path, sub_dirs, label_dirs):
    for sub_dir in sub_dirs: 
        for label_dir in label_dirs:
            new_dir = os.path.join(path, sub_dir, label_dir)
            Path(new_dir).mkdir(parents=True, exist_ok=True)
            print(new_dir)
    
    print('All directories created successfully!')

FOLDER_PATH = 'dataset/'
SUB_DIRS = ['train/', 'test/']
LABEL_DIR = ['dogs/', 'cats/']

create_dir(FOLDER_PATH, SUB_DIRS, LABEL_DIR)
train_datagen = image.ImageDataGenerator(
  	rescale = 1./255,  # to normalize bigger values. Convert from 0-255 to 0-1 range.
    shear_range = 0.2,
    zoom_range = 0.2,
    horizontal_flip = True
)


# only rescaling done on test dataset
test_datagen = image.ImageDataGenerator(
    rescale = 1./255
)

train_generator = train_datagen.flow_from_directory(
    directory=TRAIN_PATH,
    target_size=(224,224),
    batch_size=32,
    class_mode='binary',
    save_to_dir = SAVE_TRAIN_PATH,
    save_prefix='',
    save_format='png'
)

validation_generator = test_datagen.flow_from_directory(
    VAL_PATH,
    target_size = (224,224),
    batch_size = 32,
    class_mode = 'binary'
)

# 
train_generator.class_indices
validation_generator.class_indices

# generate augmented images and save into the directory
for i in range(5):
  train_generator.next()
  
  
import pathlib
from pathlib import Path

def create_folder(path):
  if Path(path).is_dir():
    print ("Folder already exists!")
  else:
    pathlib.Path(path).mkdir(parents=True, exist_ok=True) 
    print ("Folder created!")    


FOLDER_PATH = '/content/drive/MyDrive/detect-covid19-xray/data-preprocessed'
create_folder(FOLDER_PATH)

/**
 * ## FileBin
 * A little library for dealing with file objects
 *
 * Best to use the methods directoryOpen(), fileOpen(), and fileSave()
 * as these methods ensure the use of the File System Access API is used
 * either the latest version or the legacy one.
 *
 * If the File System Access API isn't supported by the client's browser
 * it will then fallback to using the old-school hacks for opening and
 * saving files and directories.
 */
const handler = new function FileBin () {
    let self = this;

    /**
     * Returns whether the File System Access API is supported and usable in the
     * current context (for example cross-origin iframes).
     * @returns {boolean} Returns `true` if the File System Access API is supported and usable, else returns `false`.
     */
    const supported = (() => {
        if ('top' in self && self !== top) {
            try {
                // This will succeed on same-origin iframes,
                // but fail on cross-origin iframes.
                top.location + '';
            } catch {
                return false;
            }
        } else if ('chooseFileSystemEntries' in self) {
            return 'chooseFileSystemEntries';
        } else if ('showOpenFilePicker' in self) {
            return 'showOpenFilePicker';
        }
        return false;
    })();

    FileBin.prototype.getFiles = async (dirHandle, recursive, path = dirHandle.name) => {
        const dirs = [];
        const files = [];
        for await (const entry of dirHandle.values()) {
            const nestedPath = `${path}/${entry.name}`;
            if (entry.kind === 'file') {
                files.push(
                    entry.getFile().then((file) => {
                        file.directoryHandle = dirHandle;
                        return Object.defineProperty(file, 'webkitRelativePath', {
                            configurable: true,
                            enumerable: true,
                            get: () => nestedPath,
                        });
                    })
                );
            } else if (entry.kind === 'directory' && recursive) {
                dirs.push(self.getFiles(entry, recursive, nestedPath));
            }
        }
        return [...(await Promise.all(dirs)).flat(), ...(await Promise.all(files))];
    };

    FileBin.prototype.getFilesLegacy = async (dirHandle, recursive, path = dirHandle.name) => {
        const dirs = [];
        const files = [];
        for await (const entry of dirHandle.getEntries()) {
            const nestedPath = `${path}/${entry.name}`;
            if (entry.isFile) {
                files.push(
                    entry.getFile().then((file) => {
                        file.directoryHandle = dirHandle;
                        return Object.defineProperty(file, 'webkitRelativePath', {
                            configurable: true,
                            enumerable: true,
                            get: () => nestedPath,
                        });
                    })
                );
            } else if (entry.isDirectory && recursive) {
                dirs.push(self.getFilesLegacy(entry, recursive, nestedPath));
            }
        }
        return [...(await Promise.all(dirs)).flat(), ...(await Promise.all(files))];
    };

    /**
     * Opens a directory from disk using the (legacy) File System Access API.
     */
    FileBin.prototype.openDirLegacy = async (options = {}) => {
        options.recursive = options.recursive || false;
        const handle = await window.chooseFileSystemEntries({
            type: 'open-directory',
        });
        return self.getFilesLegacy(handle, options.recursive);
    };

    /**
     * Opens a directory from disk using the File System Access API.
     */
    FileBin.prototype.openDir = async (options = {}) => {
        options.recursive = options.recursive || false;
        const handle = await window.showDirectoryPicker();
        return self.getFiles(handle, options.recursive);
    };

    FileBin.prototype.getFileWithHandle = async (handle) => {
        const file = await handle.getFile();
        file.handle = handle;
        return file;
    };

    /**
     * Opens a file from disk using the (legacy) File System Access API.
     */
    FileBin.prototype.openFileLegacy = async (options = {}) => {
        const handleOrHandles = await window.chooseFileSystemEntries({
            accepts: [
                {
                    description: options.description || '',
                    mimeTypes: options.mimeTypes || ['*/*'],
                    extensions: options.extensions || [''],
                },
            ],
            multiple: options.multiple || false,
        });
        if (options.multiple) {
            return Promise.all(handleOrHandles.map(self.getFileWithHandle));
        }
        return self.getFileWithHandle(handleOrHandles);
    };

    /**
     * Opens a file from disk using the File System Access API.
     */
    FileBin.prototype.openFile = async (options = {}) => {
        const accept = {};
        if (options.mimeTypes) {
            options.mimeTypes.map((mimeType) => {
                accept[mimeType] = options.extensions || [];
            });
        } else {
            accept['*/*'] = options.extensions || [];
        }
        const handleOrHandles = await window.showOpenFilePicker({
            types: [
                {
                    description: options.description || '',
                    accept: accept,
                },
            ],
            multiple: options.multiple || false,
        });
        const files = await Promise.all(handleOrHandles.map(self.getFileWithHandle));
        if (options.multiple) {
            return files;
        }
        return files[0];
    };

    /**
     * Saves a file to disk using the (legacy) File System Access API.
     */
    FileBin.prototype.saveFileLegacy = async (blob, options = {}, handle = null) => {
        options.fileName = options.fileName || 'Untitled';
        handle =
            handle ||
            (await window.chooseFileSystemEntries({
                type: 'save-file',
                accepts: [
                    {
                        description: options.description || '',
                        mimeTypes: [blob.type],
                        extensions: options.extensions || [''],
                    },
                ],
            }));
        const writable = await handle.createWritable();
        await writable.write(blob);
        await writable.close();
        return handle;
    };

    /**
     * Saves a file to disk using the File System Access API.
     */
    FileBin.prototype.saveFile =  async (
        blob,
        options = {},
        existingHandle = null,
        throwIfExistingHandleNotGood = false
    ) => {
        options.fileName = options.fileName || 'Untitled';
        const accept = {};
        if (options.mimeTypes) {
            options.mimeTypes.push(blob.type);
            options.mimeTypes.map((mimeType) => {
                accept[mimeType] = options.extensions || [];
            });
        } else {
            accept[blob.type] = options.extensions || [];
        }
        if (existingHandle) {
            try {
                // Check if the file still exists.
                await existingHandle.getFile();
            } catch (err) {
                existingHandle = null;
                if (throwIfExistingHandleNotGood) {
                    throw err;
                }
            }
        }
        const handle =
            existingHandle ||
            (await window.showSaveFilePicker({
                suggestedName: options.fileName,
                types: [
                    {
                        description: options.description || '',
                        accept: accept,
                    },
                ],
            }));
        const writable = await handle.createWritable();
        await writable.write(blob);
        await writable.close();
        return handle;
    };

    /**
     * Saves a file to disk using the legacy hidden anchor method.
     */
    FileBin.prototype.legacySave = async (blob, options = {}) => {
        const a = document.createElement('a');
        a.download = options.fileName || 'Untitled';
        a.href = URL.createObjectURL(blob);
        a.addEventListener('click', () => {
            // `setTimeout()` due to
            // https://github.com/LLK/scratch-gui/issues/1783#issuecomment-426286393
            setTimeout(() => URL.revokeObjectURL(a.href), 30 * 1000);
        });
        a.click();
    };

    /**
     * Opens a file from disk using the legacy input click method.
     */
    FileBin.prototype.legacyOpen = async (options = {}) => {
        return new Promise((resolve, reject) => {
            const input = document.createElement('input');
            input.type = 'file';
            const accept = [
                ...(options.mimeTypes ? options.mimeTypes : []),
                options.extensions ? options.extensions : [],
            ].join();
            input.multiple = options.multiple || false;
            // Empty string allows everything.
            input.accept = accept || '';

            let cleanupListenersAndMaybeReject;
            const rejectionHandler = () => cleanupListenersAndMaybeReject(reject);
            if (options.setupLegacyCleanupAndRejection) {
                cleanupListenersAndMaybeReject =
                    options.setupLegacyCleanupAndRejection(rejectionHandler);
            } else {
                // Default rejection behavior; works in most cases, but not in Chrome in non-secure contexts.
                cleanupListenersAndMaybeReject = (reject) => {
                    window.removeEventListener('pointermove', rejectionHandler);
                    window.removeEventListener('pointerdown', rejectionHandler);
                    window.removeEventListener('keydown', rejectionHandler);
                    if (reject) {
                        reject(new DOMException('The user aborted a request.', 'AbortError'));
                    }
                };

                window.addEventListener('pointermove', rejectionHandler);
                window.addEventListener('pointerdown', rejectionHandler);
                window.addEventListener('keydown', rejectionHandler);
            }

            input.addEventListener('change', () => {
                cleanupListenersAndMaybeReject();
                resolve(input.multiple ? Array.from(input.files) : input.files[0]);
            });

            input.click();
        });
    };

    /**
     * Reads the text content from a file. If reader.text()
     * is not available then uses FileReader as a fallback.
     */
    FileBin.prototype.readFile = (file) => {
        if (file.text) {
            return file.text();
        }
        return self.readFileLegacy(file);
    }

    /**
     * Reads the text content from a file.
     */
    FileBin.prototype.readFileLegacy = (file) => {
        return new Promise((resolve) => {
            const reader = new FileReader();
            reader.addEventListener('loadend', (e) => {
                const text = e.target.result;
                resolve(text);
            });
            reader.readAsText(file);
        });
    }

    /**
     * Opens a directory from disk using the legacy input click method.
     */
    FileBin.prototype.legacyOpenDir = async (options = {}) => {
        options.recursive = options.recursive || false;
        return new Promise((resolve, reject) => {
            const input = document.createElement('input');
            input.type = 'file';
            input.webkitdirectory = true;

            let cleanupListenersAndMaybeReject;
            const rejectionHandler = () => cleanupListenersAndMaybeReject(reject);
            if (options.setupLegacyCleanupAndRejection) {
                cleanupListenersAndMaybeReject =
                    options.setupLegacyCleanupAndRejection(rejectionHandler);
            } else {
                // Default rejection behavior; works in most cases, but not in Chrome in non-secure contexts.
                cleanupListenersAndMaybeReject = (reject) => {
                    window.removeEventListener('pointermove', rejectionHandler);
                    window.removeEventListener('pointerdown', rejectionHandler);
                    window.removeEventListener('keydown', rejectionHandler);
                    if (reject) {
                        reject(new DOMException('The user aborted a request.', 'AbortError'));
                    }
                };

                window.addEventListener('pointermove', rejectionHandler);
                window.addEventListener('pointerdown', rejectionHandler);
                window.addEventListener('keydown', rejectionHandler);
            }

            input.addEventListener('change', () => {
                cleanupListenersAndMaybeReject();
                let files = Array.from(input.files);
                if (!options.recursive) {
                    files = files.filter((file) => {
                        return file.webkitRelativePath.split('/').length === 2;
                    });
                }
                resolve(files);
            });

            input.click();
        });
    };


    FileBin.prototype.fileRead = async (file) => {
        return await self.readFile(file);
    }

    const openDirMethod = !supported ? self.legacyOpenDir
        : supported === 'chooseFileSystemEntries'
            ? self.openDirLegacy
            : self.openDir;

    FileBin.prototype.directoryOpen = async (...args) => {
        return await openDirMethod(...args);
    }

    const openFileMethod = !supported
        ? self.legacyOpen
        : supported === 'chooseFileSystemEntries'
            ? self.openFileLegacy
            : self.openFile;

    FileBin.prototype.fileOpen = async (...args) => {
        return await openFileMethod(...args);
    }

    const saveFileMethod = !supported
        ? self.legacySave
        : supported === 'chooseFileSystemEntries'
            ? self.saveFileLegacy
            : self.saveFile;

    FileBin.prototype.fileSave = async (...args) => {
        return await saveFileMethod(...args);
    }

}();
 Save
/**
 * Verifies if passed URL (remote file or any webpage / webresource) exists
 * The check is implemented via method HEAD, so no data is downloaded anyway
 *
 * @param   <string> Remote URL to verify
 * @returns <bool>   Returns true if given URL exists, false otherwise
 */
function file_exists_remote (string $url) : bool
{
    $handle = curl_init();

    curl_setopt_array($handle, [
        CURLOPT_URL => $url,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_NOBODY => 1,
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_AUTOREFERER => 1
    ]);

    curl_exec($handle);

    $responseCode = (int) curl_getinfo($handle, CURLINFO_RESPONSE_CODE);

    curl_close($handle);

    return $responseCode === 200;
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class WriteToFile
{
	public static void main(String[] args) throws IOException
	{
		Path fileName = Path.of("demo.txt");
	    String content  = "hello world !!";
	    Files.writeString(fileName, content);

	    String actual = Files.readString(fileName);
	    System.out.println(actual);
	}
}
file-info:file-name = vcPath.
    if file-info:full-pathname = ? then
      os-create-dir value(vcPath).
def delete_last_line():
    with open('test.txt', "r+", encoding="utf-8") as file:

        # Move the pointer (similar to a cursor in a text editor) to the end of the file
        file.seek(0, os.SEEK_END)

        # This code means the following code skips the very last character in the file -
        # i.e. in the case the last line is null we delete the last line
        # and the penultimate one
        pos = file.tell() - 1

        # Read each character in the file one at a time from the penultimate
        # character going backwards, searching for a newline character
        # If we find a new line, exit the search
        while pos > 0 and file.read(1) != "\n":
            pos -= 1
            file.seek(pos, os.SEEK_SET)

        # save value of last line
        value = file.readline()

        # So long as we're not at the start of the file, delete all the characters ahead
        # of this position
        if pos > 0:
            file.seek(pos, os.SEEK_SET)
            file.truncate()

        return value
import glob
import os

list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print latest_file
star

Mon Oct 31 2022 02:56:23 GMT+0000 (UTC) https://shellgeek.com/powershell-get-file-size/

#powershell #file #filesystem #measure
star

Wed Jul 06 2022 10:23:29 GMT+0000 (UTC)

#file
star

Mon Jun 27 2022 10:53:43 GMT+0000 (UTC) https://stackoverflow.com/questions/37296929/implement-document-picker-in-swift-ios

#ios #swift #file #pdf #doc #document #picker #mp3 #mp4 #video #audio
star

Mon Jun 27 2022 08:05:49 GMT+0000 (UTC)

#ios #swift #file #pdf #png
star

Mon Apr 18 2022 14:12:38 GMT+0000 (UTC) https://machinelearningmastery.com/how-to-develop-a-convolutional-neural-network-to-classify-photos-of-dogs-and-cats/

#python #direcotry #folder #file #creator
star

Mon Apr 18 2022 05:19:13 GMT+0000 (UTC) https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator

#python #direcotry #folder #file #creator
star

Mon Apr 18 2022 04:47:18 GMT+0000 (UTC) https://towardsdatascience.com/dont-use-python-os-library-any-more-when-pathlib-can-do-141fefb6bdb5#:~:text=In%20this%20article%2C%20I%20have,and%20basic%20libraries%20in%20Python.

#python #direcotry #folder #file #creator
star

Sun Feb 06 2022 18:59:43 GMT+0000 (UTC) https://github.com/daemondevin/cdn/blob/main/FileBin.js

#javascript #file #choosefilesystementries #showopenfilepicker #filereader #blob
star

Sun Nov 07 2021 17:09:29 GMT+0000 (UTC) https://howtodoinjava.com/java/io/java-read-file-to-string-examples/

#java #r/w #file
star

Mon Oct 04 2021 12:12:34 GMT+0000 (UTC)

#file
star

Fri Jan 08 2021 00:17:54 GMT+0000 (UTC)

#python #file
star

Wed Oct 28 2020 02:09:48 GMT+0000 (UTC) https://stackoverflow.com/questions/39327032/how-to-get-the-latest-file-in-a-folder-using-python

#python #glob #file #latest

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension