Snippets Collections
def generate_file(file_size_mb, file_name):
    file_size = file_size_mb * 1024 * 1024
    with open(file_name, 'wb') as f:
        f.write(b'\b' * file_size)


generate_file(file_size_mb=2, file_name='test.test')
from tqdm import tqdm
from time import sleep

text = """
This is text 123
""" * 100

# repeate text 100 times

with open('out.txt', 'w') as f:
    bar = tqdm(total=len(text), unit='B', unit_scale=True)
    for c in text:
        f.write(c)
        bar.update(1)
        sleep(0.0005)

from flask import Flask, render_template
from flask.ext.wtf import Form, SubmitField, Field, TextInput

app = Flask(__name__)
app.config['SECRET_KEY'] = 'Shh!'


class CustomField(Field):
    widget = TextInput()
    
    def _value(self):
        if self.data:
            return u', '.join(self.data)
        else:
            return u''

    def process_formdata(self, valuelist):
        if valuelist:
            self.data = [x.strip() for x in valuelist[0].split(',')]
        else:
            self.data = []


class ExampleForm(Form):
    status = CustomField()
    submit = SubmitField('POST')
//
//  File.swift
//  Service Provider
//
//  Created by Mac HD on 13 Sep, 2023.
//

import Foundation
import UIKit

import ObjectiveC

extension Encodable {
    func toDictionary() -> [String: Any] {
        let mirror = Mirror(reflecting: self)
        var dictionary = [String: Any]()
        for child in mirror.children {
            guard let label = child.label else {
                continue
            }
            dictionary[label] = child.value
        }
        return dictionary
    }
}

extension UIButton {
    private struct AssociatedKeys {
        static var idKey = "idKey"
    }

    var id: String? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.idKey) as? String
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.idKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

extension UIViewController {
    

    func nextVC(identifier: String) {
        
        var storyboard : UIStoryboard
        
        if AppDelegate.selectedLanguage == "en" {
            storyboard = UIStoryboard(name: "Main", bundle: nil)
        } else {
            storyboard = UIStoryboard(name: "arabic", bundle: nil)
        }

            let vc = storyboard.instantiateViewController(withIdentifier: identifier)
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: false, completion: nil)
    }
    
    // MARK: - Toast
    
    func showToast(message : String) {
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.view.backgroundColor = UIColor.lightGray
        alert.view.alpha = 0.3
        alert.view.tintColor = .blue
        alert.view.tintColor = hexStringToUIColor(hex: "FEDA22")
        alert.view.layer.cornerRadius = alert.view.layer.frame.height/3
        
        self.present(alert, animated: true)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
            alert.dismiss(animated: true)
        }
    }
    
    func setToast(message : String, seconds: Double = 1.0) {
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.view.backgroundColor = UIColor.white
        alert.view.alpha = 0.3
        alert.view.tintColor = .blue
        alert.view.tintColor = hexStringToUIColor(hex: "FEDA22")
        alert.view.layer.cornerRadius = alert.view.layer.frame.height/3
        
        self.present(alert, animated: true)
       
        DispatchQueue.main.asyncAfter(deadline:  DispatchTime.now() + seconds) {
            alert.dismiss(animated: true)
        }
    }
    
    // MARK: - Color
    
    func hexStringToUIColor (hex:String) -> UIColor {
        var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

        if (cString.hasPrefix("#")) {
            cString.remove(at: cString.startIndex)
        }

        if ((cString.count) != 6) {
            return UIColor.gray
        }

        var rgbValue:UInt64 = 0
        Scanner(string: cString).scanHexInt64(&rgbValue)

        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }
    
    // MARK: - DateTime
    
    func getCurrentTimeStamp() -> String {
        let time = Double(NSDate().timeIntervalSince1970)
        let timeStamp = String(Int(time * 1000))
        return timeStamp
    }
    
    func getDateTime(timeStamp : String, format: String) -> String {
            var t1 = Int(timeStamp) ?? 1
            t1 = t1/1000
            let date = NSDate(timeIntervalSince1970: TimeInterval(t1))
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = format
            let dateString = dateFormatter.string(from: date as Date)
            print("Date = \(dateString)")
            return dateString
        }
    
    func getDateTimeInArabic(timestamp: TimeInterval, format: String) -> String? {
        // Create a DateFormatter instance with Arabic locale settings
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "ar")
        dateFormatter.dateFormat = "dd MMM, yyyy HH:mm a"

        // Convert the timestamp to a Date object
        let date = Date(timeIntervalSince1970: timestamp)

        // Format the Date as an Arabic datetime string
        let arabicDateTime = dateFormatter.string(from: date)
        
        return arabicDateTime
    }
    
    func getDifference(recent: Date, previous: Date) -> (month: Int?, day: Int?, hour: Int?, minute: Int?, second: Int?) {
          let day = Calendar.current.dateComponents([.day], from: previous, to: recent).day
          let month = Calendar.current.dateComponents([.month], from: previous, to: recent).month
          let hour = Calendar.current.dateComponents([.hour], from: previous, to: recent).hour
          let minute = Calendar.current.dateComponents([.minute], from: previous, to: recent).minute
          let second = Calendar.current.dateComponents([.second], from: previous, to: recent).second

          return (month: month, day: day, hour: hour, minute: minute, second: second)
      }
 
    // MARK: - Validation
    
        func isValidName(testName:String) -> Bool {
            guard testName.count > 2, testName.count < 16 else { return false }

            let predicateTest = NSPredicate(format: "SELF MATCHES %@", "^(([^ ]?)(^[a-zA-Z].*[a-zA-Z]$)([^ ]?))$")
            return predicateTest.evaluate(with: testName)
        }
    
        func isValidEmail(_ email: String) -> Bool {
            let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
            let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
            return emailPred.evaluate(with: email)
        }
    
        func isValidPhone(_ mobilenumber: String) -> Bool {
            // optional plus sign
            let phoneRegex = "^[0-9+]{0,1}+[0-9]{5,16}$"
            let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
            return phoneTest.evaluate(with: mobilenumber)
        }
    
        func isValidPhoneNumber(_ phoneNumber: String) -> Bool {
            // must add plus sign
            let regEx = "^\\+(?:[0-9]?){6,14}[0-9]$"
            let phoneCheck = NSPredicate(format: "SELF MATCHES[c] %@", regEx)
            return phoneCheck.evaluate(with: phoneNumber)
        }
    
    func isValidPassword() {
        
    }
}

// MARK: - UIviews

extension UIView {
    
    func addshadow(top: Bool,
                  left: Bool,
                  bottom: Bool,
                  right: Bool,
                  shadowRadius: CGFloat) {
//            self.backgroundColor = UIColor.white
            self.layer.masksToBounds = false
            self.layer.cornerRadius = 8
            self.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
            self.layer.shadowRadius = shadowRadius
        self.layer.shadowOpacity = 0.6
            self.layer.shadowColor = UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 1.0).cgColor
            let path = UIBezierPath()
            var x: CGFloat = 0
            var y: CGFloat = 0
            var viewWidth = self.frame.width
            var viewHeight = self.frame.height
            // here x, y, viewWidth, and viewHeight can be changed in
            // order to play around with the shadow paths.
            if (!top) {
              y+=(shadowRadius+1)
            }
            if (!bottom) {
              viewHeight-=(shadowRadius+1)
            }
            if (!left) {
              x+=(shadowRadius+1)
            }
            if (!right) {
              viewWidth-=(shadowRadius+1)
            }
            // selecting top most point
            path.move(to: CGPoint(x: x, y: y))
            path.addLine(to: CGPoint(x: x, y: viewHeight))
            path.addLine(to: CGPoint(x: viewWidth, y: viewHeight))
            path.addLine(to: CGPoint(x: viewWidth, y: y))
            path.close()
            self.layer.shadowPath = path.cgPath
          }

       func roundCorners(corners: UIRectCorner, radius: CGFloat) {
            let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            layer.mask = mask
        }
}

// MARK: - Image

extension UIImageView {
  func setImageColor(color: UIColor) {
    let templateImage = self.image?.withRenderingMode(.alwaysTemplate)
    self.image = templateImage
    self.tintColor = color
  }
}
$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 Jan 08 2024 01:09:59 GMT+0000 (Coordinated Universal Time)

#python #file
star

Fri Sep 08 2023 05:23:34 GMT+0000 (Coordinated Universal Time)

#ios #swift #file #extension
star

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

#powershell #file #filesystem #measure
star

Wed Jul 06 2022 10:23:29 GMT+0000 (Coordinated Universal Time)

#file
star

Mon Jun 27 2022 10:53:43 GMT+0000 (Coordinated Universal Time) 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 (Coordinated Universal Time)

#ios #swift #file #pdf #png
star

Mon Apr 18 2022 14:12:38 GMT+0000 (Coordinated Universal Time) 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 (Coordinated Universal Time) 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 (Coordinated Universal Time) 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 (Coordinated Universal Time) 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 (Coordinated Universal Time) 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 (Coordinated Universal Time)

#file
star

Fri Jan 08 2021 00:17:54 GMT+0000 (Coordinated Universal Time)

#python #file
star

Wed Oct 28 2020 02:09:48 GMT+0000 (Coordinated Universal Time) 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