Skip to content

Instantly share code, notes, and snippets.

@Samasaur1
Samasaur1 / FileHandleOutputStream.swift
Last active January 19, 2025 19:03
print to standard error in Swift
internal struct FileHandleOutputStream: TextOutputStream {
private let fileHandle: FileHandle
let encoding: String.Encoding
init(_ fileHandle: FileHandle, encoding: String.Encoding = .utf8) {
self.fileHandle = fileHandle
self.encoding = encoding
}
mutating func write(_ string: String) {
@Samasaur1
Samasaur1 / Login tracking.md
Last active January 25, 2024 00:41
macOS login tracking

What is this?

This is a set of scripts, along with a LaunchAgent and a LaunchDaemon, that tracks when users login and logout of a macOS systtem, as well as when the system starts up or shuts down.

Why not use last(1)?

Short answer: last is probably fine in most cases.

Long answer: last is three versions out of date, and all the other options are worse.

import Cocoa
let src = CGEventSource(stateID: .hidSystemState)
let down = CGEvent(keyboardEventSource: src, virtualKey: 0x12, keyDown: true)!
let up = CGEvent(keyboardEventSource: src, virtualKey: 0x12, keyDown: false)!
sleep(5)
////down?.post(tap: .cghidEventTap)
@Samasaur1
Samasaur1 / solver.py
Created October 21, 2023 16:33
Find the most four-letter words with the same offsets between letters
alphabet = sorted([*"qwertyuiopasdfghjklzxcvbnm"])
def gen_word(i1, i2, i3, i4):
return alphabet[i1] + alphabet[i2] + alphabet[i3] + alphabet[i4]
with open("/usr/share/dict/words", "r") as file:
word_list = [x[:-1] for x in file.readlines() if len(x) == 5]
print(len(word_list))
# print(word_list)
@Samasaur1
Samasaur1 / cnxshun.swift
Created December 9, 2020 19:41
Simple Swift TCP socket chat server
import Foundation
import Network
internal struct FileHandleOutputStream: TextOutputStream {
private let fileHandle: FileHandle
let encoding: String.Encoding
init(_ fileHandle: FileHandle, encoding: String.Encoding = .utf8) {
self.fileHandle = fileHandle
self.encoding = encoding
@Samasaur1
Samasaur1 / N-Gon.swift
Created November 20, 2019 00:23
Functions to generate the points of a regular n-gon with side length s
import Darwin
func positionOfPoint(_ i: Int, sideLength s: Double, exteriorAngle alpha: Double) -> (x: Double, y: Double) {
if i == 0 {
return (0, 0)
}
let previousResult = positionOfPoint(i - 1, sideLength: s, exteriorAngle: alpha)
return (previousResult.x + (s * cos(Double(i - 1) * alpha)), previousResult.y + (s * sin(Double(i - 1) * alpha)))
}
@Samasaur1
Samasaur1 / ThrowingNonThrowing.swift
Created November 19, 2018 23:22
Throw errors in non-throwing functions
public func nonThrowingFunc() {
do {
try APICall()
} catch let APIError {
try! {
throw MyError
}()
}
}