Wednesday, September 25, 2024

Controlling key movements in VS Code

// Key bindings to take cursor to Terminal

// C:/Users/student/AppData/Roaming/Code/User/keybindings.json

[   {   "key": "ctrl+down",

        "command": "workbench.action.terminal.focus"

    },

    {   "key": "ctrl+up",

        "command": "workbench.action.focusActiveEditorGroup",

        "when": "terminalFocus"

    }

]


// Key bindings to take cursor to Output

// C:/Users/student/AppData/Roaming/Code/User/keybindings.json

[   {   "key": "ctrl+down",

        "command": "workbench.action.output.toggleOutput",

        "when": "!terminalFocus"

    },

    {   "key": "ctrl+up",

        "command": "workbench.action.focusActiveEditorGroup",

        "when": "editorTextFocus || panelFocus"

    }

]

Tuesday, September 17, 2024

Zipping files

import os

from datetime import datetime

from zipfile import ZipFile


today = datetime.now() # set file name and time of creation

file_name = 'zipper_' + today.strftime('%Y.%m.%dh%H%M') + '.zip'

dir_name = 'To Zip'  # update path

def zipdir(path, zip):

  for root, dirs, files in os.walk(path):

    for file in files:

      zip.write(os.path.join(root, file))


if __name__ == '__main__':

  zipfile = ZipFile(file_name, 'w')

  zipdir(dir_name, zipfile)

  zipfile.close()

Finding execution time

import time, random

class ExecutionTime:

  def __init__(self):

    self.start_time = time.time()

  def duration(self):

    return time.time() - self.start_time


timer = ExecutionTime()

L = [random.randint(1, 888898) for i in range(1, 10_000_000)]

print(f'Finished in {timer.duration()} seconds.')


Renaming files in a folder

import os, glob

for file in glob.glob("*.*"):

  file_name = os.path.splitext(file)[0]

  extension = os.path.splitext(file)[1]

  new_file = file_name[:10] + extension # Choose new filename pattern

  try:

    os.rename(file, new_file)

  except OSError as e:

    print(e)

  else:

    print(f"Renamed {file} to {new_file}")


Find all links on a webpage

import requests, re

url = "https://medium.com/@binoythomas1108/understanding-classification-metrics-through-fairy-tales-5434213aa441"

website = requests.get(url)

html = website.text # read html

links = re.findall('"((http|ftp)s?://.*?)"', html) # re.findall grabs links

for i, link in enumerate(links): # output links

  print(i+1, link[0], "\n")