Tuesday, December 17, 24: TIL Hindley–Milner type system

TIL Hindley–Milner type system.

Read The Swift Runtime: Your Silent Partner.



Monday, December 16, 24: TIL markitdown

TIL markitdown from Microsoft - a utility tool for converting various files to Markdown (e.g., for indexing, text analysis, etc.). It presently supports:

  • PDF (.pdf)
  • PowerPoint (.pptx)
  • Word (.docx)
  • Excel (.xlsx)
  • Images (EXIF metadata, and OCR)
  • Audio (EXIF metadata, and speech transcription)
  • HTML (special handling of Wikipedia, etc.)
  • Various other text-based formats (csv, json, xml, etc.)

It did work great for me with .docx, .pdf. For .jpeg it got only image size, nothing was OCRed.



Thursday, December 12, 24: TIL @DebugDescription

TIL @DebugDescription macro in Swift.



Wednesday, December 11, 24: Started to read book A philosophy of software design by John Ousterhout

Started to read a book A philosophy of software design by John Ousterhout. I like it’s less than 200 pages.

Read ChatGPT in Xcode: is it good?.



Sunday, December 08, 24: TIL listing certifications on LinkedIn might be counterproductive

TIL Why you shouldn’t list certifications on LinkedIn. The article is published on interviewing.io, site for anonymous mock interviews with engineers from Amazon, Google, Facebook, and other top companies.



Saturday, December 07, 24: TIL VTracer

TIL VTracer, an open source software to convert raster images (like jpg & png) into vector graphics (svg). It can vectorize graphics and photographs and trace the curves to output compact vector files.

Linearity made Swift package out of rust library: VtracerSwift.



Friday, December 06, 24: TIL @ObservedObject vs @StateObject

TIL @ObservedObject vs @StateObject:

@ObservedObject is for when the an external entity owns the reference to the view model - don’t init in the view or it’ll get recreated on every redraw!

@StateObject is created & owned by the view, and tied to its lifecycle.



Wednesday, November 27, 24: TIL what is Duff’s device

TIL what is Luneburg lens.

TIL what is Duff’s device.

Read about libraries/frameworks on Apple platforms: Static, Dynamic, Mergeable, oh, my!.

If you want to embarrass a senior iOS engineer, ask them to explain the difference between Dynamic Frameworks and Static Libraries.

These concepts are enormously important, but for years, they were packaged up in a box in my brain labelled “I’ll learn about these one day, but until then, I’ll have impostor syndrome”.

Unless you’re working to reduce app bundle size, simplify your dependency graph, optimise launch performance, or speed up build times, you won’t get to put this knowledge into practice.

Let’s change that with a primer on libraries, frameworks, and linking, and then let’s understand what is meant by static and dynamic. We’ll finish by learning about the new mergeable libraries available in Xcode.

Bookmarking Creating a macOS Screensaver in SwiftUI.

Read Reverse Engineering iOS 18 Inactivity Reboot.

Read Impress at Job Interviews by Inspecting their App Bundle. I have been doing this for years.



Monday, November 25, 24: Watched SwiftUI Tutorial: Build a Real App! Payment Calculator

Watched SwiftUI Tutorial: Build a Real App! Payment Calculator 1/6 and part 2/6.



Friday, November 22, 24: TIL Midpoint Circle Algorithm

Read Demo Showcase Reverse Image Search.

TIL The Midpoint Circle Algorithm Explained Step by Step.



Thursday, November 21, 24: TIL Swift Package Description could define iOS app product

TIL Swift Package Description could define product of iOS app. PackageDescription defines following enum: From PackageDescription:

public enum ProductSetting : Equatable {

    case bundleIdentifier(String)

    case teamIdentifier(String)

    case displayVersion(String)

    case bundleVersion(String)

    case iOSAppInfo(PackageDescription.ProductSetting.IOSAppInfo)

    public struct IOSAppInfo : Equatable {

    // ...

This definition is not available in swift-package-manager repo. But is available in Xcode if Control-click on import PackageDescription.



Wednesday, November 20, 24: TIL Apple now provides Swift runtime for AWS Lambda

TIL Apple now provides Swift runtime for AWS Lambda: Introducing Swift AWS Lambda Runtime, its repo swift-aws-lambda-runtime.

Read Developer guide to Swift AWS Lambdas.

Read and followed Create AWS Lambda functions using the AWS SDK for Swift.



Tuesday, November 19, 24: TIL about global actors in Swift

TIL about global actors in Swift: Swift proposal SE-0316 Global actors implemented in Swift 5.5.

Interesting that with await could be called func not marked with async:

class IconViewController: NSViewController {
  @MainActor @objc private dynamic var icons: [[String: Any]] = []
    
  @MainActor var url: URL? {
	didSet {
	  // Asynchronously perform an update
	  Task.detached { [url] in                   // not isolated to any actor
	    guard let url = url else { return }
	    let newIcons = self.gatherContents(url)
	    await self.updateIcons(newIcons)         // 'await' required so we can hop over to the main actor
	  }
	}
  }

  @MainActor private func updateIcons(_ iconArray: [[String: Any]]) {
    icons = iconArray
        
    // Notify interested view controllers that the content has been obtained.
    // ...
  }
}

Another interesting case calling with await a func not marked with async:

actor Counter {
  var value = 0
  
  @MainActor func updateUI(view: CounterView) async {
    view.intValue = value  // error: `value` is actor-isolated to `Counter` but we are in a 'MainActor'-isolated context
    view.intValue = await value // okay to asynchronously read the value
  }
}


Monday, November 18, 24: TIL MainActor.assumeIsolated and @preconcurrency

TIL MainActor.assumeIsolated: What on earth is going on with awakeFromNib?

The thing is, there are examples of NSObject subclasses that mix MainActor and non-MainActor methods. If the compiler were to treat all overrides as matching the isolation of its enclosing type, it would completely break NSDocument. Now, I want to be fair: NSDocument is probably as close to pathological as you can get. It uses a custom concurrency system that is not based on GCD or OperationQueue. And, it regularly mixes in main thread and background work, which is pretty much all configurable at runtime.

So how does this whole @preconcurrency thing work?.

Remember, Swift concurrency is all about the type system. This means that definitions are hugely important to how things function. The @preconcurrency attribute alters how definitions are interpreted by the compiler. In general, it relaxes some rules that might otherwise make a definition difficult or even impossible to use.

The End of Singleton? Why Swift 6 Actors Are the Future of iOS Development

TIL CodeUA.



Saturday, November 16, 24: TIL How async/await works internally in Swift

TIL How async/await works internally in Swift.

TIL Real-time kinematic positioning (RTK).



Friday, November 15, 24: TIL powermetrics

TIL powermetrics CLI on macOS.



Thursday, November 14, 24: TIL Copilot Edits

TIL Copilot Edits: Introducing Copilot Edits (preview).



Wednesday, November 13, 24: Read MainActor usage in Swift explained to dispatch to the main thread

Read MainActor usage in Swift explained to dispatch to the main thread.



Sunday, November 10, 24: TIL Apple Quietly Introduced iPhone Reboot Code Which is Locking Out Cops

TIL Apple Quietly Introduced iPhone Reboot Code Which is Locking Out Cops.



Saturday, November 09, 24: TIL about App Intents in iOS

Watch WWDC 2024 video Bring your app’s core features to users with App Intents.

Prepare for iOS 18: App Intents.



Thursday, November 07, 24: TIL about title case in some scripts

Read MVVM: An architectural coding pattern to structure SwiftUI Views.

TIL about title case in some scripts: What has case distinction but is neither uppercase nor lowercase?.

In other words, it is a character c with the properties that

  • toUpper(c) ≠ toLower(c), yet
  • c ≠ toUpper(c) and c ≠ toLower(c).

Congratulations, you found the mysterious third case: Title case.



Sunday, November 03, 24: Read SwiftUI Architecture #20

Read #20 - SwiftUI Architecture.



Friday, November 01, 24: TIL what are mixins and traits

TIL what are mixins and traits: Unlocking Mixins with Swift 5.9 Macros.

Read Using Binaries as Libraries in Swift. it has condensed snippet for running external binary (ffmpeg in this case) from Swift using Process and Pipe.

Read It’s a trap! React to Unix signals in Swift.

TIL swift-service-lifecycle package.



Thursday, October 31, 24: Read How to use VSCode/Cursor for iOS development

Read How to use VSCode/Cursor for iOS development.

Watched The Mathematics of String Art.

Watched How To Make a Computer Create Something Beautiful: String Art.



Wednesday, October 30, 24: TIL GitHub launched CopilotForXcode

TIL GitHub launched CopilotForXcode



Monday, October 28, 24: TIL What Are Textons

TIL IM2GPS: estimating geographic information from a single image. im2gps/ page on uni site includes even link Code for finding and downloading images on Flickr.

TIL What Are Textons.

TIL what is gist:

In computer vision, GIST descriptors are a representation of a low-dimensional image that contains enough information to identify the scene in an image. Global GIST descriptors allow a very small size representation of an image.

TIL many people started there own TIL sites: 1, 2, 3, 4 by Chris Eidhof from objc.io.



Friday, October 25, 24: TIL jemalloc

TIL jemalloc.



Thursday, October 24, 24: TIL package-benchmark

TIL package-benchmark, Swift benchmark runner with many performance metrics and great CI support: Introducing the Benchmark Package: Complementing Unit Tests with Performance Checks. I wasn’t yet able to use it because of linking error.

Read Apple documentation Improving code assessment by organizing tests into test plans, Test coverage.

TIL about prepareThumbnail(of:completionHandler:) for creating a thumbnail image at the specified size asynchronously on a background thread, available since iOS 15. There’s no need anymore to downscale image manually on iOS.



Tuesday, October 22, 24: Read Apple is Killing Swift

Read Apple is Killing Swift by Jacob Bartlett.



Friday, October 18, 24: TIL Mothbox DIY project for learning insects

TIL Mothbox, a low-cost, high-performance insect monitor. …its low-cost nature means you can build one to study the biodiversity at your home.

Read [iOS/SwiftUI] Explaining and Using @EnvironmentObject in SwiftUI.



Tuesday, October 15, 24: TIL how Discrete Cosine Transform is used in JPEG

Read JPEG DCT, Discrete Cosine Transform (JPEG Pt2)- Computerphile.

Watched The Unreasonable Effectiveness of JPEG: A Signal Processing Approach. TIL what is chrome downsampling (chroma subsampling).



Sunday, October 13, 24: TIL what are Test Doubles

Read Apple’s swift-testing documentation.

Read Hello Swift Testing, Goodbye XCTest.

Read iOS Unit Test Master 101 — Vol. 1. Learned new terms. “Test Doubles”: test objects that are used to mimic the behavior of some real object. I always called this mocks. But no. Test double could be a “Dummy”, “Fake”, “Stub”, “Spy” or “Mock”. “Fixture”: predefined set of conditions or data used to initialize a system or environment for testing, ensuring consistent and repeatable results. I knew what is that. But use case example is very good.



Saturday, October 12, 24: TIL what is blurhash

TIL tools for making nice snippets for blogs exist, like showcode and codetoimg.

Read the best QR code description ever: Reading QR codes without a computer!.

TIL what is blurhash, its repo contains Swift code but only for iOS UIImage. Read blogpost where blurhash explain why and how: How we came to create a new image placeholder algorithm, BlurHash.

Read I sped up the generation of blurhash by 128 times.



Friday, October 11, 24: TIL how to transform colors with matrices

Read Transforming colors with matrices.



Thursday, October 10, 24: TIL what is Immediate Operand

TIL what is Immediate Operand:

Some instructions use data encoded in the instruction itself as a source operand. The operands are called immediate operands. For example, the following instruction loads the EAX register with zero. MOV EAX, 00

Read Swift on RISC-V: Launch of New Toolchain for RISC-V Hardware.



Sunday, October 06, 24: Read some posts about image processing

Read Simple algorithms for adjusting image temperature and tint, A simple algorithm for correcting lens distortion, Real-time Diffuse (Spread) Image Filter.



Saturday, October 05, 24: TIL Apple Watch despite being 64 bit use 32 bit pointers

TIL Apple Watch despite being 64 bit use 32 bit pointers: Reminder: Apple Watches use 32 bit pointers.

Read Seven grayscale conversion algorithms.

Read Top 10 List of Graphics Code Optimizations.



Friday, October 04, 24: TIL what does !$ mean in shell

TIL what does !$ mean in shell. ! means the last command used, $ - the last word. So !$ means the last word of the last command.

TIL Digital Ocean App Platform, it’s possible to write this apps in Swift: App Platform sample Swift application.



Thursday, October 03, 24: Read Image Dithering: Eleven Algorithms and Source Code

Accidently came accross post Image Dithering: Eleven Algorithms and Source Code. Now I understand how dithering works.



Tuesday, October 01, 24: TIL Raspberry Pi AI Camera on sale now at $70, there’s also Raspberry Pi AI Kit available since June 2024

TIL Raspberry Pi AI Camera on sale now at $70. TIL Raspberry Pi AI Kit available now at $70.



Monday, September 30, 24: Watched how Linus Torvalds explains “taste” in code

Watched how Linus Torvalds explains “taste” in code by showing how to remove an entry from a singly linked list in C without adding extra complexity..



Sunday, September 29, 24: TIL nonisolated and isolated keywords in Swift

TIL nonisolated and isolated keywords in Swift: Nonisolated and isolated keywords: Understanding Actor isolation.

Read Improved control over actor isolation.



Saturday, September 28, 24: TIL Swift has a package access level

TIL Swift has a package access level (example). It’s explained in the Access Control chapter, but I still struggle to distinguish internal from package.



Friday, September 27, 24: TIL swift-java, Swift Java Interoperability Tools and Libraries

TIL swift-java, Swift Java Interoperability Tools and Libraries. While I’m not sure how it will be useful to me yet, its existence suggests that Swift is maturing as a language.



Tuesday, September 24, 24: TIL new Synchronization framework available since iOS 18

TIL Kahan summation algorithm.

TIL new Synchronization framework available since iOS 18. Learnt this from Thread safety with Mutex in Swift 6.



Monday, September 23, 24: TIL Noncopyable structs and enums in Swift

Read Announcing Swift 6.

TIL Noncopyable structs and enums in Swift.



Friday, September 20, 24: TIL .mailmap in git

TIL .mailmap in git. There could be also interesting file .mailfilter.



Monday, September 16, 24: TIL how to draw ellipsoid in shapr3d

Read Jailbreak your Enemies with a Link: Remote Execution on iOS.

Read SwiftUI apps at scale.

TIL how to draw complex 3d bodies like ellipsoid in shapr3d.



Friday, September 13, 24: TIL Safe C++

TIL Safe C++, a proposal to make C++ safer.

TIL Apple has entry point for all documentation and sample code: Explore new documentation and sample code from WWDC24.

Read Apple documentation Providing Thumbnails of Your Custom File Types.

Watched WWDC 2019 video What’s New in File Management and Quick Look.



Thursday, September 12, 24: TIL how Linux C coding style argues for using short local variable names

TIL how Linux C coding style argues for using short local variable names: Linux C coding Style: Naming

C is a Spartan language, and so should your naming be. Unlike Modula-2 and Pascal programmers, C programmers do not use cute names like ThisVariableIsATemporaryCounter. A C programmer would call that variable tmp, which is much easier to write, and not the least more difficult to understand.

HOWEVER, while mixed-case names are frowned upon, descriptive names for global variables are a must. To call a global function foo is a shooting offense.

GLOBAL variables (to be used only if you really need them) need to have descriptive names, as do global functions. If you have a function that counts the number of active users, you should call that count_active_users() or similar, you should not call it cntusr().

Encoding the type of a function into the name (so-called Hungarian notation) is brain damaged - the compiler knows the types anyway and can check those, and it only confuses the programmer. No wonder MicroSoft makes buggy programs.

LOCAL variable names should be short, and to the point. If you have some random integer loop counter, it should probably be called i. Calling it loop_counter is non-productive, if there is no chance of it being mis-understood. Similarly, tmp can be just about any type of variable that is used to hold a temporary value.

If you are afraid to mix up your local variable names, you have another problem, which is called the function-growth-hormone-imbalance syndrome. See chapter 6 (Functions).



Wednesday, September 11, 24: Read Customizing the build schemes for a project

Read Smartly organize API/Endpoints in Swift.

Read Apple’s article Customizing the build schemes for a project.



Tuesday, September 10, 24: TIL WhatsApp integrates Signal’s protocols

TIL how to backup configuration of INAV flight controller: Exporting and Importing INAV Configuration.

TIL WhatsApp integrates Signal’s protocols: Signal Is More Than Encrypted Messaging. Under Meredith Whittaker, It’s Out to Prove Surveillance Capitalism Wrong.

Read PID controller tuning by Bitcraze.



Monday, September 09, 24: TIL Delta Debugging

TIL Delta Debugging algorithm: swift-tools-support-core has implementation.

Among another interesting stuff swift-tools-support-core implements AbsolutePath and RelativePath.



Sunday, September 08, 24: TIL pkg-config

TIL about pkg-config - a program used to retrieve information about installed libraries in the system. It’s Linux stuff but is used by Swift packge manager.



Saturday, September 07, 24: TIL dependency mirroring and Package Manager Workspace

TIL about dependency mirroring in Swift package.

TIL about Package Manager Workspace which help Swift package authors to develop packages that depend on each other.



Thursday, September 05, 24: Bookmarking The Unofficial Guide to xcconfig files

Bookmarking The Unofficial Guide to xcconfig files.



Wednesday, September 04, 24: Read Embedded Swift on the Raspberry Pi Pico/RP2040 without the Pico SDK

Read Embedded Swift on the Raspberry Pi Pico/RP2040 without the Pico SDK.

TIL usr in /usr/bin stands for “universal system resources” not “user”, and dev in /dev/vdiskO stands for “device” not “development”.

`usr` in `/usr/bin` stands for "universal system resources" not "user"



Saturday, August 31, 24: TIL kMDItemKeywords entry in Info.plist could be used to improve iOS app visibility on a device

Read Embedded Swift – User Manual. Embedded Swift – Integrating with embedded SDKs, Getting started with Raspberry Pi Pico-series.

Read DIY Dashcam: Car Security Camera with a Raspberry Pi Zero W.

TIL motionEyeOS, a Linux distribution that turns your single board computer into a video surveillance system.

Read IOT in Cars (and Vans): Home Automation on the Road.

TIL kMDItemKeywords entry in Info.plist could be used to improve iOS app visibility on a device.



Friday, August 30, 24: Read and followed Build an embedded application for a microcontroller

Read and followed Build an embedded application for a microcontroller at swift.org.



Thursday, August 29, 24: TIL github cli

TIL it’s not necessary to open github.com to create PR - it could be done with gh pr create:

`gh pr create`

TIL llm cli .



Tuesday, August 27, 24: Bookmarking auto generating git commit message

Bookmarking auto generating git commit message by Andrej Karpathy.



Sunday, August 25, 24: TIL that since iOS 15 BinaryFloatingPoint has formatted()

Read Logging in Swift.

TIL that since iOS 15 BinaryFloatingPoint has formatted(). Learnt that from 100 days of SwiftUI. It’s possible to write:

Stepper("\(sleepAmount.formatted()) hours", value: $sleepAmount, in: 4...12, step: 0.25)


Saturday, August 24, 24: TIL what does “existential type” mean in Swift

TIL What does “existential type” mean in Swift?: an alternate naming of an existential is ‘protocol as type’.



Friday, August 23, 24: TIL what is primary asosiated type in Swift

Read What is type erasure in Swift? An explanation with code samples.

Read What are primary associated types in Swift 5.7?.

TIL what is primary asosiated type in Swift. In snippet below in Element because it is in angle brackets <Element> in protocol declaration.

public protocol Collection<Element> : Sequence {

    @available(*, deprecated, message: "all index distances are now of type Int")
    typealias IndexDistance = Int

    associatedtype Element

    /// A type that represents a position in the collection.
    ///
    /// Valid indices consist of the position of every element and a
    /// "past the end" position that's not valid for use as a subscript
    /// argument.
    associatedtype Index : Comparable where Self.Index == Self.Indices.Element, Self.Indices.Element == Self.Indices.Index, Self.Indices.Index == Self.SubSequence.Index


    /// A lot of other stuff...
}


Thursday, August 22, 24: TIL FIGlet

TIL FIGlet, a program for making large letters out of ordinary text:

 _ _ _          _   _     _     
| (_) | _____  | |_| |__ (_)___ 
| | | |/ / _ \ | __| '_ \| / __|
| | |   <  __/ | |_| | | | \__ \
|_|_|_|\_\___|  \__|_| |_|_|___/


                          .   oooo         o8o           
                        .o8   `888         `"'           
 .ooooo.  oooo d8b    .o888oo  888 .oo.   oooo   .oooo.o 
d88' `88b `888""8P      888    888P"Y88b  `888  d88(  "8 
888   888  888          888    888   888   888  `"Y88b.  
888   888  888          888 .  888   888   888  o.  )88b 
`Y8bod8P' d888b         "888" o888o o888o o888o 8""888P' 

                             _/      _/        _/            
    _/_/    _/  _/_/      _/_/_/_/  _/_/_/          _/_/_/   
 _/    _/  _/_/            _/      _/    _/  _/  _/_/        
_/    _/  _/              _/      _/    _/  _/      _/_/     
 _/_/    _/                _/_/  _/    _/  _/  _/_/_/        

Watched WWDC 2024 video Go small with Embedded Swift.

TIL wokwi, ESP32 simulator.

Read Difference between some and any with Protocols in Swift. Couldn’t say I could explain what’s the difference between using protocol as type, some and any.



Wednesday, August 21, 24: TIL Skip

TIL Skip:

Skip brings Swift app development to Android. It is a tool that enables developers to use a single modern programming language (Swift) and first-class development environment (Xcode) to build genuinely native apps for both iOS and Android.

Skip is the only tool that enables you to develop genuinely native apps for both major mobile platforms with a single codebase.



Sunday, August 18, 24: TIL sending keyword in Swift

Read Migrating to Swift 6.

TIL sending keyword in Swift:

func populate(island: Island, with chicken: sending Chicken) async {
    await island.adopt(chicken)
}

The compiler can now provide the guarantee that at all call sites, the chicken parameter will never be subject to unsafe access. This is a relaxing of an otherwise significant constraint. Without sending, this function would only be possible to implement by requiring that Chicken first conform to Sendable.

Hm. actors could be passed between isolation domains. Here’s quote from Migrating to Swift 6:

Actors are not value types, but because they protect all of their state in their own isolation domain, they are inherently safe to pass across boundaries. This makes all actor types implicitly Sendable, even if their properties are not Sendable themselves.

Watched PointFree episode Cross-Platform Swift: View Paradigms.



Saturday, August 17, 24: TIL how to make XCFramework from swift package

Read Creating XCFramework from SPM package (russian).

Read Building Swift Package as XCFramework.

Read Creating a multiplatform binary framework bundle.



Thursday, August 15, 24: TIL Protocol Conformance Isolation Mismatch

(1/7) INAV for Beginners 2022: What is it and what can it do?, (2/7) INAV for Beginners 2022: Downloading, flashing and basic radio setup, (3/7) INAV for Beginners 2022: Completing the basic setup and adding GPS.

Followed The Basics of Getting INAV Working on an Airplane tuning airplane. I like INAV for supporting macOS. inav-configurator could even be installed with homebrew.

Read Non-Sendable types are cool too you know. That’s very interesting!

TIL Protocol Conformance Isolation Mismatch.

TIL XCTMemoryMetric.



Wednesday, August 14, 24: TIL CocoaPods goes off the scene

TIL CocoaPods goes off the scene: CocoaPods Support & Maintenance Plans.

TIL what sherlocked means: Apple just made your app obsolete? You’ve been ‘Sherlocked’.

It dates back to the 1990s when Apple introduced a desktop search tool called Sherlock that was strikingly similar to another desktop search program, known as Watson. Since then, the term has stuck.

Read Projecting a Value From a Property Wrapper for reminding what does dollar sign mean in SwiftUI code, like Picker("Number of people", selection: $numberOfPeople).



Tuesday, August 13, 24: TIL usvg library

TIL usvg, an SVG parser that tries to solve most of SVG complexity. It’s part of resvg, an SVG rendering library. Some time ago I have looked for decent SVG parser.

TIL esc-configurator (esc-configurator.com), a PWA (Progressive Web App) to flash BLHeli_S and AM32 based ESCs from the browser using the Web-Serial API.

TIL Ring Tone Text Transfer Language, RTTTL. Some ESC support RTTTL.

Read bluejay ESC wiki.

Read DSHOT - the missing Handbook. DSHOT is supported on all BLHELI_S, BLEHLI_32 and KISS ESC’s.

Read Anyone can Access Deleted and Private Repository Data on GitHub: the implication here is that any code committed to a public repository may be accessible forever as long as there is at least one fork of that repository.



Monday, August 12, 24: TIL wcurl and ipatool

TIL wcurl.

Watched nice tips How to Reduce Log Verbosity in the Xcode Debug Console.

TIL ipatool, a command-line tool that allows searching and downloading app packages (known as ipa files) from the iOS App Store. Finally I got a tool for downloading ipa from the App Store.



Sunday, August 11, 24: TIL Why Charset Matters

TIL Encoding Differentials: Why Charset Matters

Another, less common way to indicate the character encoding is the Byte-Order Mark. This is a specific Unicode character (U+FEFF) that can be placed in front of a string to indicate the byte endianness and character encoding. It is mainly used in files, but since these might be served via a web server, modern browsers support it. A Byte-Order Mark at the beginning of an HTML document even takes precedence over a charset attribute in the Content-Type header and the <meta> tag.



Wednesday, August 07, 24: TIL about Retroactive Conformances

TIL about Retroactive Conformances: Swift Regret: Retroactive Conformances. Read Swift Regrets.

Read What is an Electronic Speed Controller & How Does an ESC Work.



Monday, August 05, 24: TIL why airplane electric motors are called outrunner

TIL why airplane electric motors are called outrunner: Brushless Inrunner vs Outrunner motor?.



Sunday, August 04, 24: TIL keystroke CMD + Option + / in Xcode for ceating doc comment

Watched You Need to Document Your Swift Code with DocC. TIL keystroke CMD + Option + / in Xcode creates doc comment.



Friday, August 02, 24: Read how to build QuickLook in SwiftUI

Read Preview files with QuickLook in SwiftUI.

Read How do I show QLPreviewPanel with SwiftUI on macOS?.

Read Configuring a new target in your project in Xcode. Exactly I was interested in Configure a dependency between two targets.



Tuesday, July 30, 24: Read about Uniform Type Identifiers

Read Introduction to Uniform Type Identifiers Overview, Uniform Type Identifiers Reference.



Monday, July 29, 24: TIL swift-testing-revolutionary

TIL swift-testing-revolutionary for converting test cases written in XCTest to swift-testing.

swift-geometrize is safe from data races now:

swift-geometrize is safe from data races now

Read Async await in Swift: The Full Toolkit.

Read Advanced Swift Actors: Re-entrancy & Interleaving.

Watched WWDC 2021 video Swift concurrency: Behind the scenes.

Read Wiki articles Dependency injection and Dependency inversion principle.

The principle states:[1]

A. High-level modules should not import anything from low-level modules. Both should depend on abstractions (e.g., interfaces).

B. Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.



Sunday, July 28, 24: Watched videos about system design interviews

Watched Design Uber Eats - iOS System Design Interview.

Watched iOS System Design Interviews: Introduction & Resources.



Saturday, July 27, 24: TIL it’s not easy install Python dependencies on macOS

Came accross error while trying pip install some packages on macOS: Tackling the “Externally Managed Environment” error while using Pip3.

TIL COMMAND + SHIFT + .` in Finder shows hidden forders.

Came accross cd "$HOME" || exit 1 in bash script. It’s smart to break script execution in case of error whithout explicit branching.



[Friday, July 26, 24: Read Read Scan HTML even faster with SIMD instructions (C++ and C#)

Read Scan HTML even faster with SIMD instructions (C++ and C#).



Thursday, July 25, 24: Read Aerial Robotic Landscape

Read How I’ve made a Widget with info of electricity availability at my home (ukr).

TIL Read the Docs.

Read Aerial Robotic Landscape from which the Education and tutorials section is the most useful. The post by Kimberly McGuire from Bitcraze, Online courses in Aerial Robotics, extends the list of tutorials and online courses.

I’m saving the book Small Unmanned Aircraft: Theory and Practice separately as it contains a lot of interesting links in the Supplemental Material.

This might be a good start: Drone Programming. Software Development for Ardupilot Powered Unmanned Systems.. It seems that only the last point in the curriculum will be more or less new.



Wednesday, July 24, 24: Read Memory management when using async/await in Swift

Read Memory management when using async/await in Swift.

Read Autonomous flight of the micro drone Crazyflie 2.1 through an obstacle course which seems to be report on research work done by students.



Tuesday, July 23, 24: TIL swift-noise

TIL swift-noise - a free, pure Swift procedural noise generation library.

Read SVG noise filter series: Part I — Introduction, Part II — Applying noise to shapes, Part III — Bells and whistles, Part IV — Animating the noise, Part V — Thick noise.

Read [SVG Filter Effects: Creating Texture with ](https://tympanus.net/codrops/2019/02/19/svg-filter-effects-creating-texture-with-feturbulence/). Has nice examples how noise could be added to static images to produce effect of old/broken computer monitor.

Read The beginners guide to Drones by Bitcraze.

“The Beginner’s Guide to Drones” for programmers curious about exploring the world of unmanned aerial vehicles (UAVs). If you’re a coder from another field, this guide will walk you through the basics of drones, their components, and how to start programming them. Let’s dive in and see how your coding skills can take flight!



Monday, July 22, 24: Read FPV Drone Rates Explained: Betaflight & Actual Rates

Played with pid-demo/.

Bookmarking quite useful The Ultimate FPV Shopping List and Drone Parts Recommendations.

Read FPV Drone Rates Explained: Betaflight & Actual Rates.



Friday, July 19, 24: Watched WWDC 2022 video Meet distributed actors in Swift, Read Concurrency chapter of The Swift Programming language book

Watched WWDC 2022 video Meet distributed actors in Swift.

Read Concurrency chapter of The Swift Programming language book.



Thursday, July 18, 24: Watched WWDC videos Beyond the basics of structured concurrency and Protect mutable state with Swift actors

Watched WWDC 2023 video Beyond the basics of structured concurrency.

Watched WWDC 2021 video Protect mutable state with Swift actors



Wednesday, July 17, 24: Read Swift Actors — in depth and watched Explore structured concurrency in Swift

Read Swift Actors — in depth

Watched WWDC 2021 video Explore structured concurrency in Swift.



Tuesday, July 16, 24: Read Swift proposal Sendable and @Sendable closures, implemented in Swift 5.7 and proposal Inferring Sendable for methods and key path literals, implemented in Swift 6.0

Read Swift proposal Sendable and @Sendable closures, implemented in Swift 5.7.

Read Swift proposal Inferring Sendable for methods and key path literals, implemented in Swift 6.0.



Monday, July 15, 24: Read Build settings reference - a detailed list of individual Xcode build settings that control or change the way a target is built

Read Build settings reference - a detailed list of individual Xcode build settings that control or change the way a target is built. Some drew attention.

Misuse of Grand Central Dispatch Setting name: CLANG_ANALYZER_GCD Check for misuses of the Grand Central Dispatch API.

Performance Anti-Patterns with Grand Central Dispatch Setting name: CLANG_ANALYZER_GCD_PERFORMANCE Check for Grand Central Dispatch idioms that may lead to poor performance.

EXPERIMENTAL Buffer overflows Setting name: CLANG_ANALYZER_SECURITY_BUFFER_OVERFLOW_EXPERIMENTAL Check for potential buffer overflows.

Use of ‘strcpy’ and ‘strcat’ Setting name: CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY Warn on uses of the strcpy and strcat functions, which can result in buffer overflows. Use strlcpy or strlcat instead.

Compress PNG Files Setting name: COMPRESS_PNG_FILES If enabled, PNG resource files are compressed as they are copied.

Setting name: GCC_ENABLE_PASCAL_STRINGS Recognize and construct Pascal-style string literals. Its use in new code is discouraged. Pascal string literals take the form “\pstring” . The special escape sequence \p denotes the Pascal length byte for the string, and will be replaced at compile time with the number of characters that follow. The \p may only appear at the beginning of a string literal, and may not appear in wide string literals or as an integral constant.

Setting name: GCC_ENABLE_SSE3_EXTENSIONS Specifies whether the binary uses the builtin functions that provide access to the SSE3 extensions to the IA-32 architecture.

Setting name: GCC_ENABLE_SSE41_EXTENSIONS Specifies whether the binary uses the builtin functions that provide access to the SSE4.1 extensions to the IA-32 architecture.

Setting name: GCC_ENABLE_SSE42_EXTENSIONS Specifies whether the binary uses the builtin functions that provide access to the SSE4.2 extensions to the IA-32 architecture.

App Can Run Independently of Companion iPhone App Setting name: INFOPLIST_KEY_WKRunsIndependentlyOfCompanionApp When GENERATE_INFOPLIST_FILE is enabled, sets the value of the WKRunsIndependentlyOfCompanionApp key in the Info.plist file to the value of this build setting.

Swift Language Version Setting name: SWIFT_VERSION The language version used to compile the target’s Swift code.

Read Swift 6: Incrementally migrate your Xcode projects and packages.

TIL how to stash individual files with git: git stash push [file] or git stash push -m "message" [file] or even git stash push --patch



Sunday, July 14, 24: TIL swiftly - a Swift toolchain installer and manager, written in Swift

TIL https://github.com/swiftlang/swiftly - s Swift toolchain installer and manager, written in Swift.

Building a sub 250g Autonomous Drone with Ardupilot and ExpressLRS AirPort Telemetry. Interesting install with separate pair of ExpressLRS in AirPort mode for telemetry which allow to use Mission Planner to control drone during the flight.



Wednesday, July 10, 24: Read Anatomy of High-Performance Matrix Multiplication

Read Anatomy of High-Performance Matrix Multiplication.

Bookmarking textbook The theory of matrices.



Tuesday, July 09, 24: Read Concurrency-safe global variables to prevent data races

Read Concurrency-safe global variables to prevent data races.



Monday, July 08, 24: TIL about Swift structured concurrency

TIL swift package clean command for deleting build artifacts and swift package purge-cache for purging the global repository cache.

Read Concurrency chapter of Swift documentation. Some quotes follow.

TIL how to transform throwing function into one returning Result:

func availableRainyWeekendPhotos() -> Result<[String], Error> {
    return Result {
        try listDownloadedPhotos(inGallery: "A Rainy Weekend")
    }
}

there’s no safe way to wrap asynchronous code so you can call it from synchronous code and wait for the result. The Swift standard library intentionally omits this unsafe functionality — trying to implement it yourself can lead to problems like subtle races, threading issues, and deadlocks. When adding concurrent code to an existing project, work from the top down. Specifically, start by converting the top-most layer of code to use concurrency, and then start converting the functions and methods that it calls, working through the project’s architecture one layer at a time. There’s no way to take a bottom-up approach, because synchronous code can’t ever call asynchronous code.

This is new for me:

To call an asynchronous function and let it run in parallel with code around it, write async in front of let when you define a constant, and then write await each time you use the constant.

async let firstPhoto = downloadPhoto(named: photoNames[0])
async let secondPhoto = downloadPhoto(named: photoNames[1])
async let thirdPhoto = downloadPhoto(named: photoNames[2])

let photos = await [firstPhoto, secondPhoto, thirdPhoto]
show(photos)

In this example, all three calls to downloadPhoto(named:) start without waiting for the previous one to complete. If there are enough system resources available, they can run at the same time. None of these function calls are marked with await because the code doesn’t suspend to wait for the function’s result. Instead, execution continues until the line where photos is defined — at that point, the program needs the results from these asynchronous calls, so you write await to pause execution until all three photos finish downloading.

TIL why structured concurrency is called so:

Tasks are arranged in a hierarchy. Each task in a given task group has the same parent task, and each task can have child tasks. Because of the explicit relationship between tasks and task groups, this approach is called structured concurrency.



Friday, July 05, 24: Read Plotting a Path to a Package Ecosystem without Data Race Errors

Read Plotting a Path to a Package Ecosystem without Data Race Errors. Here is explained how to enable checks: Enabling Complete Concurrency Checking.

Read Macros Swift documentation.



Wednesday, July 03, 24: TIL about typed throws in Swift

TIL git checkout -. The minus (-) at the end of the command tells git to switch to the previous branch you were on before the current one. It’s a way to quickly toggle back and forth between two branches without needing to type out the full branch names.

TIL pushd and popd: git worktree example:

$ git worktree add -b emergency-fix ../temp master
$ pushd ../temp
# ... hack hack hack ...
$ git commit -a -m 'emergency fix for boss'
$ popd
$ git worktree remove ../temp

TIL about Typed throws in Swift.



Sunday, June 30, 24: Read Quick Look Programming Guide in documentation archive

Read Quick Look Programming Guide in documentation archive while thinking of creating QuickLook for PAM files. New documentation for QuickLook framework is far from be than good.



Saturday, June 15, 24: TIL how to Create Ubuntu bootable USB stick on macOS

TIL how to Create Ubuntu bootable USB stick on macOS.



Friday, June 14, 24: TIl how pbm, pgm, ppm, pam images could be previewed on macOS

TIl how pbm, pgm, ppm, pam images could be previewed on macOS:

pnmtopng feep.ascii.p5.pgm | open -f -a Preview

Preview of netpbm file with means of netpbm on macOS is important as macOS renders these file often incorrectly. E.g. as on following screenshot correct preview is on the bottom.

Finder screenshot with wrongly rendered pgm file

Analogous pipe on Ubuntu will look like pnmtoxwd /Users/valeriyvan/Downloads/surf.ascii.pgm | xwud. This works on macOS as well if X Windows is installed.

Found dithering command line in netpbm - pamditherbw: pamditherbw baboon.ascii.pgm | open -f -a Preview.

This is the result of running jpegtopnm ~/Desktop/me.jpg | ppmtopgm - | pamditherbw - | pnmtopng - | open -f -a Preview: me dithered with pamditherbw



Wednesday, June 12, 24: Watched a bunch of WWDC 2024 videos

Watched WWDC 2024 session video Meet Swift Testing.

Watched WWDC 2024 session video What’s new in Swift. Boyond other things it mentions (9m 50s) how to cross-compile on mac for Linux platform.

Read Iterate Over Parameter Packs in Swift 6.0.

TIL about Swift 6 types throws - from video What’s new in Swift above.

TIL about Atomics And Mutexes in Swift 6, from the same video.

Watched WWDC 2024 session video What’s new in SwiftUI.

Watched Opening safe with Flipper Zero. Interesting how Flipper Zero could be used to inspect what is sent through RX, with the help of minicom CLI (available on macOS over brew):

minicom -b 4800 --displayhex -D /dev/tty.usbmodemflip_Himano1


Tuesday, June 11, 24: TIL about Zig programming language

Came across following tweet: It’s weird how Apple continues to double down on Swift when even the language’s creator says that the type system design is flawed: fundamentally slow and impossible to provide good error messages for. Thread refers to video Mojo🔥: a deep dive on ownership with Chris Lattner. Interesting part starts from 6m 13s. It mentions that Swift expression type checker is slow and error message cumbersome. Thread also mentions Zig programming language. I like how Zig positions itself:

A Simple Language

Focus on debugging your application rather than debugging your programming language knowledge.

  • No hidden control flow.
  • No hidden memory allocations.
  • No preprocessor, no macros.

Watched 2024 Platforms State of the Union.



Monday, June 10, 24: Watched PointFree’s issue Modern UIKit: Sneak Peek, Part 2

Watched PointFree’s issue Modern UIKit: Sneak Peek, Part 2.



Saturday, June 08, 24: Watched Modern UIKit: Sneak Peek, Part 1

Watched PointFree’s issue Modern UIKit: Sneak Peek, Part 1.



Saturday, June 01, 24: Read Different flavors of type erasure in Swift

Read Different flavors of type erasure in Swift.



Friday, May 31, 24: Read ChatGPT for Swift: Top 5 code generation prompts

Read ChatGPT for Swift: Top 5 code generation prompts. Part of these I already use.



Wednesday, May 29, 24: TIL there’re bitmap fonts in textual human readable format

TIL there’re bitmap fonts in textual human readable format: Bitmap_fonts.



Tuesday, May 28, 24: Watched I made an RC flying wing

Bookmark video I made an RC flying wing | Joywing 1.1 an improved version. This one is also funny: Airplane from a Pizza Box?.



Monday, May 27, 24: TIL setjmp/longjmp are undefined behaviors in Swift

setjmp/longjmp are undefined behaviors in Swift and cannot be used with ARC Objective-C either.

Read Netpbm Programming Library Errors. libnetpbm or just exists app in case of any error (io error or broken file) or uses longjpm as alternative.

These two make libnetpbm unusable with Swift. The only way to use libnetpbm in Swift - port it into Swift.



Sunday, May 26, 24: TIL Swift sucks at running initialization code e.g. for framework initialisation

Automatically run Swift code when your framework gets initialized. But all these methods are shit.



Wednesday, May 22, 24: TIL interesting method of reading stdin in Swift

TIL how to build netpbm on macOS. Running ./configure succeeds, but make fails with an error. I checked the netpbm Homebrew formula and reviewed the formula code, which applies some fixes in config.mk. Now I can try wrapping libnetpbm into a Swift package.

Dug in Libnetpbm User’s Guide.

TIL interesting method of reading stdin in Swift:

import Foundation

if let input = try? String(contentsOfFile: "/dev/stdin", encoding: .utf8) {
    print("Input from file: \(input)")
}

This reads the entire content of stdin as a string. This method is useful if you’re dealing with redirected input from files or other streams.



Tuesday, May 21, 24: TIL the Lenna has own website

Read How to use Blackbox in Betaflight FPV Drones.

TIL the Lenna has own website: The Lenna Story. The Lenna (or Lena) picture is one of the most widely used standard test images used for compression algorithms.

Lena

TIL x86’s mov is Turing-complete:

It is well-known that the x86 instruction set is baroque, over-complicated, and redundantly redundant. We show just how much fluff it has by demonstrating that it remains Turing-complete when reduced to just one instruction.

The instruction we choose is mov, which can do both loads and stores. We use no unusual addressing modes, self-modifying code, or runtime code generation. Using just this instruction (and a single unconditional branch at the end of the program to make nontermination possible), we demonstrate how an arbitrary Turing machine can be simulated.



Monday, May 20, 24: Read The case against self-closing tags in HTML

Read The case against self-closing tags in HTML.



Friday, May 17, 24: Read Async Await in Swift: Concurrency Explained [With Examples]

Read Async Await in Swift: Concurrency Explained [With Examples].



Wednesday, May 15, 24: TIL a lot new things about ArduPilot

Read Measuring Vibration in ArduPilot documentation. Interesting if Betaflight has similar means/tool for measuring vibrations. Vibration Damping.

Read Firmware Limitations on AutoPilot Hardware. RAM Limitations section shows possible symptoms when flight controller has insufficient RAM. This symptoms, like compass calibration not starting or logging not starting or parameters download in Ground Control Station are slow are interesting.

in Mission Planner’s STATUS tab, you can monitor the “freemem” status for current free RAM

Read Connect Mission Planner to AutoPilot.

Read Diagnosing some common problems using Logs.

Read Learning the ArduPilot Codebase.

Read Battery Monitors (aka Power Monitors/Modules).



Tuesday, May 14, 24: TIL about test coverage reports in Swift Package apps

Read again Reporting test coverage for Swift packages without Xcode.

swift test --enable-code-coverage --verbose

For me codecove files are in folder ./.build/arm64-apple-macosx/debug/codecov

Read Code coverage for Swift Package Manager based apps.

Watched 15 | Combine a gyroscope and accelerometer to measure angles - precisely.

Read Low-level Swift optimization tips.

Reasonably well-written Swift code without any detailed optimization can easily achieve run time performance within 200 to 250 percent of a bare-metal C implementation.

Ha-ha. Twice slower than plane C.

Came accross nice tutorial Quadcopter build and programming manual how to build Quadcopter from scratch, including PCB bouard for self made flight controller. It’s so nice I checked in Carbon Aeronautics Quadcopter Manual.pdf. Totorial has videos for each of chapters: Carbon Aeronautics video channel.

Read Making a 3D Modeler, in C, in a Week.

Read Get Started with Embedded Swift on ARM and RISC-V Microcontrollers. Embedded Swift Example Projects. Introduce embedded development using Swift has examples of cross compiling.

Read A Vision for Embedded Swift.

TIL terminal on macOS shows preview of a file if you select its URL and press space:

terminal on macOS shows preview of a file if you select its URL and press space



Monday, May 13, 24: Read about developing embedded applications with Swift

Read Developing Embedded Applications with Swift and Create falling sand simulation

Read Balancing cube. Cool engineering.

Read documentation Concurrency. Perform asynchronous operations.



Friday, May 10, 24: Read about Result builders in Swift

Read Result builders.



Thursday, May 09, 24: TIL what are Monads in Swift

Read a very short explanation what are Monads in Swift by Chris Eidhof. Whatched John Gallagher’s talk about Monads.



Friday, May 03, 24: Dug in Netpbm

Diving into the Netpbm sources as I’m currently endeavoring to enhance swift-geometrize’s capability to read and write .PPM files, I stumbled upon the dither.h source file. Quite intriguing! Within it, I discovered a reference to the book “Digital Halftoning” by Robert Ulichney, MIT Press, ISBN 0-262-21009-6. This book is rooted in the PHD thesis (1986) Digital Halftoning and the Physical Reconstruction Function. From what I could discern, both the book and the thesis are closely intertwined in terms of content. I’ll retain these references for when I integrate dithering into swift-geometrize.

When I searched for a “Digital Halftoning” book, I stumbled upon “Beyond Photography: The Digital Darkroom” by Gerard J. Holzmann, published in 1988, the same year I began my studies. It contains numerous intriguing examples of bitmap transformations that could be worth reproducing, either within swift-geometrize package or as part of a separate Bitmap package.



Tuesday, April 30, 24: TIL about Privacy manifest files

TIL about Privacy manifest files for apps and third-party SDKs — distributed as XCFrameworks, Swift packages, or Xcode projects. If some common third-parties are used like AFNetworking or Alamofire, app must include privacy manifest: Upcoming third-party SDK requirements. Some APIs which used for fingerprinting, like NSFileSystemFreeSize, now require explanation why they are used Describing use of required reason API. Watched WWDC 2023 video Get started with privacy manifests. Watched Create your Privacy Nutrition Label. Watched Verify app dependencies with digital signatures.



Monday, April 29, 24: TIL How To Engrave Text On A Part in Shapr3D

Watched Day #2: User Interface and Navigation - Learn Shapr3D in 10 Days for Beginners.

TIL How To Engrave Text On A Part in Shapr3D.



Friday, April 26, 24: Read about telegram bot webhooks

Read about Telegram Bot webhooks: Marvin’s Marvellous Guide to All Things Webhook, How to create a Telegram bot with Swift using Vapor on Ubuntu / macOS. Set webhook for Geometrizebot.



Thursday, April 25, 24: TIL SSH deployment with GitHub actions

Read SSH deployment with GitHub actions. Exact my case:

This article assumes you are deploying to a single machine with a known IP address accessible via SSH.

Also read Deploying to a Server with GitHub Actions using ssh.

Read Herelink User Guides to learn how to setup Herelink Controller unit.

Watched and followed Day #1: 3D Printable One-Hand Book Holder in Shapr3D.



Wednesday, April 24, 24: TIL about .scss

Ran over How to create a “Before & After” image slider with CSS and JS. TIL about .scss but I used SCSS to CSS Compiler to compile it into regular CSS.

While working on slder I failed to make example work and asked ChatGPT for suggestion. The best help I have got from chatgpt so far!.

Interesting reading Why I Keep Failing Candidates During Google Interviews….



Wednesday, April 17, 24: TIL 3MF 3D Manufacturing Format

TIL 3D printing is called additive manufacturing.

TIL about 3MF 3D Manufacturing Format.

3MF is an XML-based data format designed specifically for additive manufacturing. It includes information about materials, colors, and other information that cannot be represented in the STL format.

Microsoft is part of consortium behind 3MF therefore format is natively supported on Windows. macOS lucks native QuickLook viewer and I failed to find working third-party one. 3MF is XML, part describing 3D object structure is not complex. Theoretically it wouldn’t be difficult to convert 3MF into STL inside QuickLook.

3MF 3D Manufacturing Format is open source, lib3mf, a C++ implementation of the 3D Manufacturing Format file standard is opensource either.



Friday, April 12, 24: TIL about Swift evolution proposal Module Aliasing For Disambiguation

TIL about Lockdown Mode on iOS and macOS.

TIL about SPI Playgrounds.app and from latter Arena.

TIL about Swift evolution proposal Module Aliasing For Disambiguation for solving issue I faced some time ago trying to use two Swift packages having identical structure and here is PR for fix.



Thursday, April 11, 24: TIL about Panic’s Playdate console which could be programmed with Swift

TIL about Panic’s Playdate console which could be programmed with Swift: Byte-sized Swift: Building Tiny Games for the Playdate.

TIL swift-http-types package: Introducing Swift HTTP Types.

TIL swift.org got top level Packages page.



Sunday, April 07, 24: Read How to use the rethrows keyword in Swift and Deploying [Vapor] with Nginx

Read How to use the rethrows keyword in Swift.

Looking for solution to make Vapor work on both HTTPS as well as HTTP came to Deploying with Nginx.



Friday, April 05, 24: TIL how to flash flight controller with Ardupilot on Mac without STM32Cube Programmer

TIL how to flash flight controller with Ardupilot on Mac without STM32Cube Programmer, just by using CLI dfu-util. The steps are described at Loading a bootloader with DFU. Note to future self: what you download for wiring this way should be bootloader available by link Bootloaders.

% dfu-util --list
dfu-util 0.11

Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2021 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to http://sourceforge.net/p/dfu-util/tickets/

Found DFU: [0483:df11] ver=0200, devnum=1, cfg=1, intf=0, path="0-1", alt=1, name="@Option Bytes   /0x5200201C/01*128 e", serial="200364500000"
Found DFU: [0483:df11] ver=0200, devnum=1, cfg=1, intf=0, path="0-1", alt=0, name="@Internal Flash   /0x08000000/16*128Kg", serial="200364500000"
% dfu-util -a 0 --dfuse-address 0x08000000 -D ~/Downloads/MatekH743_bl.bin
dfu-util 0.11

Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2021 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to http://sourceforge.net/p/dfu-util/tickets/

dfu-util: Warning: Invalid DFU suffix signature
dfu-util: A valid DFU suffix will be required in a future dfu-util release
Opening DFU capable USB device...
Device ID 0483:df11
Device DFU version 011a
Claiming USB DFU Interface...
Setting Alternate Interface #0 ...
Determining device status...
DFU state(2) = dfuIDLE, status(0) = No error condition is present
DFU mode device DFU version 011a
Device returned transfer size 1024
DfuSe interface name: "Internal Flash   "
Downloading element to address = 0x08000000, size = 17404
Erase   	[=========================] 100%        17404 bytes
Erase    done.
Download	[=========================] 100%        17404 bytes
Download done.
File downloaded successfully


Thursday, April 04, 24: TIL Common Crawl

TIL Common Crawl which dataset uses OpenAI and alike.



Wednesday, April 03, 24: Bookmarking Ray Tracing in One Weekend

Bookmarking Ray Tracing in One Weekend.



Sunday, March 31, 24: Passed over Explore Xcode: Hello, SwiftUI tutorial

Passed over Explore Xcode: Hello, SwiftUI tutorial.



Saturday, March 30, 24: Bookmarking Fast Quicksort Implementation Using AVX Instructions

Bookmarking Fast Quicksort Implementation Using AVX Instructions.

This article describes a technique for implementing the quicksort sorting algorithm. Our method ‘vectorizes’ the computations and leverages the capabilities of the advanced vector extensions (AVX) instructions, available on Intel Core processors, and of the AVX2 instructions that were introduced with Intel’s recent architecture codename Haswell. Our solution offers several advantages when com- pared with other high-performance sorting implementations, such as the radix sort, as implemented in Intel IPP library, or the introsort, as implemented in the C++ STL. In addition to sorting numeric arrays, our method can also be used to sort complex structures with numeric keys and even pointers to such structures.



Friday, March 29, 24: TIL Apple launched new SwiftUI tutorials

TIL Apple launched new SwiftUI tutorials which I definately will follow.



Tuesday, March 26, 24: TIL Adwaita

TIL Adwaita - a framework for creating user interfaces for GNOME with an API similar to SwiftUI: Writing GNOME Apps with Swift.

TIL that Storage section in Settings for Mac allows to clean up storage without third party apps:

Storage section in Settings

E.g. Developer section allows to clean up much more the Xcode DevCleaner which I used to use for this purpose:

Developer section in Storage

Xcode DevCleaner

It also shows that 2.67GB caches of Command Line Tools could be clean up but for whatever reason Delete button is inactive:

Command Line Tools

It also has shown more then year old 22.28GB iOS backup about which I forgotten:

iOS backups



Monday, March 25, 24: TIL list of Mission Commands in ArduPilot

TIL gha-setup-swift for automating installation of the Swift toolchain for Windows hosts on GitHub Actions runners.

TIL list of Mission Commands for ArduPilot plane. The most important ones for creating looping missions are following. DO_JUMP. param1 - index of waypoint to jump to, param2 - number of times that the DO_JUMP command will execute before moving to the next sequential command. If the value is zero the next command will execute immediately. A value of -1 will cause the command to repeat indefinitely. ‘DO_CHANGE_SPEED’. param1 - speed type (0 = Airspeed, 1 = Ground Speed), param2 - target speed (m/s). If airspeed, a value below or above min/max airspeed limits results in no change. a value of -2 uses AIRSPEED_CRUISE, param3 - throttle as a percentage (0-100%). A value of 0 or negative indicates no change.

TIL DO_JUMP command in ArduPilot Mission Planner cannot be the last command in a mission: Problem with DO_JUMP in mission planner.



Sunday, March 24, 24: TIL PETOI maker of open source Arduino and Raspberry Pi-based quadruped robotic pets

TIL PETOI Robot pets for every student to build and code and repo OpenCat is the open-source Arduino and Raspberry Pi-based quadruped robotic pet framework developed by Petoi, the maker of futuristic programmable robotic pets. NonCodeFiles repo has among other resources .stl files for 3d-printing.



Saturday, March 23, 24: TIL SwiftUI View’s Instance Method onChange(of:initial:_:)

Have found strange declaration in SwiftUI sources as for me:

@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public typealias ObservableObject = ObservableObject

TIL SwiftUI View’s Instance Method onChange(of:initial:_:)



Friday, March 22, 24: TIL how macros work in Swift

Browsed Managing model data in your app.

Read Macro Observable().

Read The Swift Programming Language (5.10) Macros.

Whay Macro is called so? WiKi: Macro (computer science):

In computer programming, a macro (short for “macro instruction”; from Greek μακρο- ‘long, large’[1]) is a rule or pattern that specifies how a certain input should be mapped to a replacement output. Applying a macro to an input is known as macro expansion.

Read @Environment documentation.



Thursday, March 21, 24: TIL some debug techniques in SwiftUI

Read Debugging techniques in SwiftUI, Building SwiftUI debugging utilities.



Tuesday, March 19, 24: TIL about app prewarming introduced in iOS 15

TIL about app prewarming introduced in iOS 15: About the app launch sequence.



Monday, March 18, 24: Read Debugging Improvements in Swift 5.9

Udemy course Introduction to Quadrotors and Control Theory.

Read Bad practice: using .lowercased() to compare strings. which I will quote in PRs.

Bookmarking Swift Developer Roadmap 2024: With 7 Samples App.

Read Debugging Improvements in Swift 5.9.



Sunday, March 17, 24: Watched Optimising a VTOL and Configuring GPS Rescue (Return to Home, Failsafe) on Betaflight 4

Watched Optimising a VTOL.

Watched Configuring GPS Rescue (Return to Home, Failsafe) on Betaflight 4.



Friday, March 15, 24: TIL How to use Environment in SwiftUI

TIL How to use Environment in SwiftUI.



Wednesday, March 13, 24: Read and tried How to display a WebView in SwiftUI

Read and tried How to display a WebView in SwiftUI. I have found that SwiftUI’s Text become slow for showing big real life documents so I tried switching back to WKWebView. I found WKWebView is extremely fast in comparison with SwiftUI Text.



Monday, March 11, 24: TIL Correct Horse Battery Staple

TIL phrase Correct Horse Battery Staple and open source password generator with the same name.

Read Arduino Plane Failsafe Function.

TIL git switch and git worktree git commands.



Friday, March 08, 24: TIL about DSHOT

TIL about DSHOT on Betaflight, and DSHOT on Sscar Liang. Read DSHOT - the missing Handbook.

Read What’s New in Betaflight 4.4 | How to Update?.

Looking a way to repair broken .MOV files which SKYZONE goggles live which turned off before recording stops, came across Repairing Corrupt DJI Video Files. Fantastically, it gives at least something from a file.



Thursday, March 07, 24: Read Creating a Betaflight target from scratch

TIL what is HAL.

Read Creating a Betaflight target from scratch from which I have learnt about Betaflight’s new unified targets.

Watched Beginner ➡️ Advanced: Betaflight 4.4 ultimate walkthrough.



Wednesday, March 06, 24: TIL withCheckedContinuation and withUnsafeContinuation in Swift 5.5

TIL withCheckedContinuation and withUnsafeContinuation for interfacing async tasks with synchronous code in Swift.

Read Discovering iOS memory leaks: A case study with Firefox app.



Monday, March 04, 24: TIL about Hardened Runtime

TIL about Hardened Runtime.

Came accross video Build Your Own Drone Tracking Radar: Part 1. The idea is absolutly crazy.



Thursday, February 29, 24: TIL to use tinkercad and have drawn and printed the firsth thing

TIL tinkercad. The first part drawn and printed:

Camera mount bracket in Thinkercad

Camera mount bracket

TIL how to get info about video file, e.g. frame rate: ffmpeg -i RC5_0001.MP4.

TIL what is .gcsv file: https://docs.gyroflow.xyz/app/technical-details/gcsv-format

(short for gyro csv or Gyroflow csv) is a text-based gyro log format that can be implemented in custom hardware/firmware. File contains information about the gyro orientation, scaling, and a unique identifier. If present, file could have accelerometer and magnetometer data as well.

Gyroflow is an advanced video stabilization tool, which uses gyro data for accurate motion compensation (meaning stabilization).



Wednesday, February 28, 24: TIL about image stippling

TIL about image stippling. WiKi page Stippling is quite general. Here what is meant (the image is from stippled-image repo):

Stippled Obama

Watched Coding Challenge 181: Weighted Voronoi Stippling. It’s great! Would be nice make in Swift packages for Voronoi and for stippling images. Stippling is similar to dithering a bit.

Finally I know what FPV frame size means All About Multirotor Drone FPV Frames:

Each frame has a designated size class, based upon the longest distance from motor to motor measured in millimeters, typically taken by measuring diagonally across the frame. A frame measuring less than 150mm motor-to-motor is categorized as a micro. A frame larger than 150mm motor-to-motor is considered a mini. When measuring an unconventional multicopter frame, such as a hexacopter or tricopter, the size will always be given by the greatest motor-to-motor distance.

Browsed Explaining Kalman Filters with the Crazyflie.

Excellent explainer! For those who want to delve a little deeper, or write their own EKF from scratch, I humbly suggest: https://simondlevy.github.io/ekf-tutorial/ https://github.com/simondlevy/TinyEKF

Read how to make a deck to turn crazyflie into FPV drone: FPV deck hack.

TIL difference between Cortex M and Cortex A. ARM Cortex-M

The main difference from Cortex-A cores is that Cortex-M cores have no memory management unit (MMU) for virtual memory, considered essential for “full-fledged” operating systems. Cortex-M programs instead run bare metal or on one of the many real-time operating systems which support a Cortex-M.

Bookmarking link for SIYI HM30 firmware because documentation has broken link.



Tuesday, February 27, 24: TIL How async/await works internally in Swift

Read SwiftUI Toolbar: Everything You Need to Know.

TIL How async/await works internally in Swift.

Unlike traditional DispatchQueues, which creates and terminates threads dynamically as it deems necessary, the Cooperative Thread Pool manages a fixed number of threads that are constantly helping each other with their tasks.



Sunday, February 25, 24: TIL about JSON Pointers

TIL about JSON Pointers - JavaScript Object Notation (JSON) Pointer. It’s a way to query JSON loke XPath for XML.

Read JSON Schema Reference trying to find means of reusing parts of JSON inside same JSON.

Read Swift Macros: Understanding Freestanding & Attached Macros.



Friday, February 23, 24: TIL how to implement searchable lists in SwiftUI

Passed over a number of posts on topic of building searchable lists in SwiftUI: How to add a search bar to filter your data, Building a Searchable List with SwiftUI, SwiftUI Search Bar: Best Practices and Examples.



Wednesday, February 21, 24: TIL setters in Swift could be nonmutating

TIL The SwiftUI Field Guide very nice visual guide on SwiftUI modifiers.

Refreshed knowledge of property wrappers in Swift by reading Property wrappers in Swift. Has good example of @UserDefaultsBacked.

Read Screen vs View in SwiftUI post about how to split SwiftUI views into separate source files and how to name source files. Use *Screen.swift rather then *View.swift for views responsible for whole screen. Extract SwiftUI views into separate files only if they are used in several places. Makes sense for big projects as mean to keep count of files under control.

TIL setters in Swift could be nonmutating as well as getters could be mutating. It is unusual even for Xcode - it cannot highlight code properly:

Swift nonmutating setter

Git Tips 1: Oldies but Goodies. Oh, it’s possible to have git config for some folders which will work for all sub-folders. So I could finally tune git config for my working folder and it will not interfere with the rest.

git push --force-with-lease is nice feature. git config --global column.ui auto as well which makes git branch output much nicer:

git branch
  cicd/build-ubuntu-workflow          fix/reserveCapacity
* feature/asynciterator               main
  feature/bitmap-orientation          minusone
  feature/bresenham                   refactor/bounds
  feature/incremental-export          refactor/bresenham
  feature/string-shapetype            refactor/cleanup
  feature/strokeWidth                 refactor/clear-shape
  fix/accesscontrol                   refactor/comment-color-perception
  fix/assert                          refactor/main
  fix/downsample-public               refactor/shape-equality

I don’t fully understand git push --signed but I will give it a try on my next push.



Tuesday, February 20, 24: Passed through guides and documentation on SwiftUI List

Passed through Getting Started with SwiftUI Tables: A Beginner’s Guide.

Passed through Expandable List In SwiftUI.

Passed through Apple’s documentation on List. Unexpectedly good.

Here’s the result:

SwiftUI Expandible List



Monday, February 19, 24: TIL how to get string from AttributedString in Swift

I was confused today I cannot access regular string of AttributedString in Swift. In case of NSAttributedString, it was trivial as NSAttributedString is subclass of NSString. I haven’t found straight way in documentation so I googled. Thread in swift forums AttributedString to String mentions only what I’ve got from documentation - go over characters view:

let string = String(attributedString.characters)

I could add one more way - use NSAttributedString as middleware:

let string = NSAttributedString(attributedString).string


Saturday, February 17, 24: Ran through Build an iOS app with SwiftUI

Ran through getting started SwiftUI tutorial on swift.org Build an iOS app with SwiftUI.



Tuesday, February 13, 24: Read paper A Systematic Approach to Building High Performance Software-Based CRC Generators

Read PNG (Portable Network Graphics).

TIL alpha is not a must in PNG files. PNG. Specification. Version 1.0. 2. Data Representation:

An alpha channel, representing transparency information on a per-pixel basis, can be included in grayscale and truecolor PNG images.

Alpha channels can be included with images that have either 8 or 16 bits per sample, but not with images that have fewer than 8 bits per sample. Alpha samples are represented with the same bit depth used for the image samples. The alpha sample for each pixel is stored immediately following the grayscale or RGB samples of the pixel.

Transparency control is also possible without the storage cost of a full alpha channel. In an indexed-color image, an alpha value can be defined for each palette entry. In grayscale and truecolor images, a single pixel value can be identified as being “transparent”. These techniques are controlled by the tRNS ancillary chunk type.

If no alpha channel nor tRNS chunk is present, all pixels in the image are to be treated as fully opaque.

TIL PNG uses Latin-1 for textual fields:

A PNG file can store text associated with the image, such as an image description or copyright notice. Keywords are used to indicate what each text string represents. ISO 8859-1 (Latin-1) is the character set recommended for use in text strings [ISO-8859]. This character set is a superset of 7-bit ASCII.

TIL PNG specification includes also rationale which is interesting to read.

PNG. Specification. Version 1.0. 1. Introduction:

The main part of this specification gives the definition of the file format and recommendations for encoder and decoder behavior. An appendix gives the rationale for many design decisions. Although the rationale is not part of the formal specification, reading it can help implementors understand the design. Cross-references in the main text point to relevant parts of the rationale. Additional appendixes, also not part of the formal specification, provide tutorials on gamma and color theory as well as other supporting material.

TIL PNG by intention doesn’t have version number. PNG file signature rationale:

Note that there is no version number in the signature, nor indeed anywhere in the file. This is intentional: the chunk mechanism provides a better, more flexible way to handle format extensions, as explained in Chunk naming conventions.

I have looked in Mac App Store. There’s no app like PNG explorer. For me it would be interesting to have/make such app. Something similar to TweakPNG.

TIL open source exiv2 CLI for exploring

Read paper A Systematic Approach to Building High Performance Software-Based CRC Generators” by Michael E. Kounavis and Frank L. Berry. OpenJDK implements ‘slicing-by-8’ algorithm described in the paper:

Swift uses straightforward naïve CRC32 implementation in at least two places: in Swift standard library and in swift-testing package. Don’t see why Swift standard library couldn’t not have more robust implementation.



Monday, February 12, 24: TIL Galileo AI

TIL Galileo AI, prompt-to-UI generative AI tool for designers and builders. Definately will use it.



Wednesday, February 07, 24: Ran through SwiftUI tutorial Chapter 4 Framework integration. Interfacing with UIKit

Ran through SwiftUI tutorial Chapter 4 Framework integration. Interfacing with UIKit.



Tuesday, February 06, 24: TIL on-crash backtraces introduced in Swift 5.9

TIL typeguard for runtime typechecking in Python:

This library provides run-time type checking for functions defined with PEP 484 argument (and return) type annotations, and any arbitrary objects. It can be used together with static type checkers as an additional layer of type safety, to catch type violations that could only be detected at run time.

TIL On-Crash Backtraces in Swift introduced in Swift 5.9:

The new Swift 5.9 release contains a number of helpful, new features for debugging code, including an out-of-process, interactive crash handler to inspect crashes in real time, the ability to trigger the debugger for just-in-time debugging, along with concurrency-aware backtracing to make it easier to understand control flow in a program that uses structured concurrency.



Monday, February 05, 24: Ran through SwiftUI tutorials App design and layout. Composing complex interfaces And Working with UI controls

Ran through SwiftUI tutorial App design and layout. Composing complex interfaces.

Ran through SwiftUI tutorial App design and layout. Working with UI controls.



Sunday, February 04, 24: Ran through SwiftUI tutorial Drawing and animation. Animating views and transitions

Ran through SwiftUI tutorial Drawing and animation. Animating views and transitions.



Friday, February 02, 24: Ran through SwiftUI tutorial Drawing and animation. Drawing paths and shapes

Ran through SwiftUI tutorial Drawing and animation. Drawing paths and shapes.



Thursday, February 01, 24: TIL how servo motors work

Watched video Servo Motors, how do they work?. TIL how servo motors work. Some technical details have slipped from my mind till now. I was sure servo motors have stepper motors inside. I was wrong. Some really have stepper motors. But most servos use regular DC motors.



Wednesday, January 31, 24: TIL how inner/outer stokes could be recreated in SVG

Read Drawing inner/outer strokes in SVG (clips and masks) while trying to understand how inner/outer stokes could be recreated in SVG.



Tuesday, January 30, 24: Browsed Book Small unmanned aircraft. Theory and Practice

Browsed Book Small unmanned aircraft. Theory and Practice. Too much math as for me. But has a lot of details I am interested in, like GPS Smoothing, Following Waypoints, Transitioning Between Waypoints, Point-to-Point Algorithms (Voronoi Graphs, Rapidly Exploring Random Trees), Vision-guided Navigation (Gimbal Pointing algo, Time to Collision, Precision Landing) and more.



Monday, January 29, 24: Read How Did REST Come To Mean The Opposite of REST

Bookmarking Robotics Academy.

Robotics Academy is an open source collection of exercises and challenges to learn robotics in a practical way. There are exercises about drone programming, about computer vision, about mobile robots, about autonomous cars, etc.

This Drone Cat and Mouse exercise is especially interesting :

The goal of this exercise is to implement the logic that allows a quadrotor to play a game of cat and mouse with a second quadrotor.

Looked FastUI FastUI is a new way to build web application user interfaces defined by declarative Python code.

Read How Did REST Come To Mean The Opposite of REST?. Controversial article.



Saturday, January 27, 24: Ran through SwiftUI tutorial SwiftUI essentials. Handling user input

Ran through SwiftUI tutorial SwiftUI essentials. Handling user input tutorial.

TIL how to move whole line up/down in Xcode with Command + Option + { or } sortcuts respectively:

You can use `Command` + `Option` + `{` or `}` to move the selected lines of code up and down, respectively

TIL how to convert .mov file into animated gif in command line with ffmpeg:

ffmpeg -i ~/Downloads/Screen\ Recording\ Moving\ Line\ in\ Xcode.mov  -pix_fmt rgb24 ~/Downloads/output.gif


Thursday, January 25, 24: Ran through SwiftUI tutorial SwiftUI essentials. Building lists and navigation

Ran through SwiftUI tutorial SwiftUI essentials. Building lists and navigation.



Wednesday, January 24, 24: Read Bloom Filters Explained

Read Bloom Filters Explained. Probabilistic Data Structure To Check Membership.



Monday, January 22, 24: TIL shortcut could include steps like entering free text

TIL shortcut could include steps like entering free text, e.g. how in this shortcut for generating QR for WiFi

Shortcut Generate WiFi QR

Probably, I could create shortcut for geometrizing images with running API call with curl or something similar.



Sunday, January 21, 24: Read The world’s smallest PNG which could serve as short introduction into PNG format

Read The world’s smallest PNG. The post could be short introduction into PNG format. Here are the world’s smallest PNG zoomed 200x times. It’s just one black pixel.

The world's smallest PNG

Here is hex dump of the image:

% xxd world\'s\ smallest\ PNG.png
00000000: 8950 4e47 0d0a 1a0a 0000 000d 4948 4452  .PNG........IHDR
00000010: 0000 0001 0000 0001 0100 0000 0037 6ef9  .............7n.
00000020: 2400 0000 0a49 4441 5478 0163 6000 0000  $....IDATx.c`...
00000030: 0200 0173 7501 1800 0000 0049 454e 44ae  ...su......IEND.
00000040: 4260 82                                  B`.

Browsed shortly Portable Network Graphics (PNG) Specification (Third Edition).

TIL xcbeautify tool for making xcodebuild’s output more readable.



Friday, January 19, 24: Passed over SwiftUI tutorial SwiftUI essentials. Creating and combining views

Passed over SwiftUI tutorial SwiftUI essentials. Creating and combining views.



Thursday, January 18, 24: TIL how to claim back disk space from git repo: git gc --aggressive

Watched Unlock the power of grammatical agreement. Surprized Apple has such an API.

Watched Discover String Catalogs.

Seeking of ways to free some diskspace come to How to clean up the git repo and reduce its disk size.

Only git gc --aggressive did work freeing 1.6GB on 7.9GB .git:

% du -sh .git
7.9G	.git
% git gc --aggressive
Enumerating objects: 734435, done.
Counting objects: 100% (734435/734435), done.
Delta compression using up to 8 threads
Compressing objects: 100% (721093/721093), done.
Writing objects: 100% (734435/734435), done.
Total 734435 (delta 571805), reused 149607 (delta 0), pack-reused 0
Checking connectivity: 734435, done.
% du -sh .git        
6.3G	.git

In another repo in goes from 3.6GB to 1.3GB.



Saturday, January 06, 24: TIL how make Swift package depend another package on local machine

Swift package manager documentation doesn’t show clearly how to make package depend on other package on local machine which is extreemly useful during development. Here is what you use: .package(url: "../swift-geometrize/", branch: "feature/asynciterator"). As alternative .package(path: "../Modules/MySwiftLib") could be used or its variant with package name .package(name: "MyPackage", path: "/local/path/to/package"). This .package(url: "file:///path/to/MySwiftLib", from: "1.0.0") technically is also possible but it is not too much useful during development. This is exert from package manifest which I use during development of geometrizebot:

let package = Package(
    name: "geometrizebot",
    platforms: [
       .macOS(.v12)
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/vapor.git", from: "4.76.0"),
        .package(url: "https://github.com/vapor/leaf", from: "4.2.4"),
        .package(url: "https://github.com/vapor/leaf-kit", from: "1.10.2"),
        .package(url: "https://github.com/nerzh/telegram-vapor-bot", from: "2.4.3"),
        //.package(url: "https://github.com/valeriyvan/swift-geometrize.git", from: "1.1.2"),
        .package(url: "../swift-geometrize/", branch: "feature/asynciterator"),
        .package(url: "https://github.com/valeriyvan/jpeg.git", from: "1.0.2"),
        .package(url: "https://github.com/kelvin13/swift-png.git", from: "4.0.2"),
        .package(url: "https://github.com/awslabs/aws-sdk-swift", exact: "0.17.0")
    ],


Wednesday, January 03, 24: TIL how to use do block in Swift to narrow scope of vars inside block

TIL how to use do block in Swift just how usually {} is used in C to narrow vars scope. Following snippet is take from PR in Vapor:

do {
    let foo = "foo"
    let uri: URI = "/\(foo)/bar/baz"
    XCTAssertEqual(uri.path, "/foo/bar/baz")
}
do {
    let uri = URI(scheme: "foo", host: "host", port: 1, path: "test", query: "query", fragment: "fragment")
    XCTAssertEqual(uri.string, "foo://host:1/test?query#fragment")
}


Saturday, December 30, 23: Read Asynchronous Tests and Expectations

Read Asynchronous Tests and Expectations.



Friday, December 29, 23: TIL how to use xcconfig for setting development team id and bundle id

From opensource app IceCubesApp for accessing the decentralized social network Mastodon learned the idea of putting development team ID and bundle id prefix into xcconfig file IceCubesApp-release.xcconfig.



Wednesday, December 27, 23: TIL git cherry

TIL git cherry. Nice to check if all commits from local branch were merged with rebase.

git cherry [-v] [<upstream> [<head> [<limit>]]]

Every commit that doesn’t exist in the branch has its id (sha1) reported, prefixed by a symbol. The ones that have equivalent change already in the branch are prefixed with a minus (-) sign, and those that only exist in the <head> branch are prefixed with a plus (+) symbol:

E.g. command git cherry -v main feature/bitmap-orientation outputs only commits marked with minus meaning branch feature/bitmap-orientation is all right to be deleted:

git cherry -v main feature/bitmap-orientation
- 29a60b3c8457acf64af5b4c8525458b91af66338 Add transpose
- 3988c4516e45b275a7f7bde236944aa980129db7 Add swap function and test
- f19ae6f7121472d2f1d49995e61a87fdac20bb07 Add reflectVertically function and test
- 93c33708967a72c0642debf685c561ec0dc943d5 Add reflectHorizontally function and test
- f2867487b9491db869dd28430f1d0d9cb7707266 Add snapshots
- af49a3b0aa534d132b50a886cbdc656a67859ea1 Add test for rotateToUpOrientation(accordingTo: .up)
- 0e59f81dd2ab54209d7bbabaabceb7c66856f21a Add test for rotateToUpOrientation(accordingTo: .upMirrored)
- fa3c6783065c240eafa0981925c4229161b5ede3 Add test for rotateToUpOrientation(accordingTo: .down)
- c2891a35301d18efe7873d54fbc9f40d224d72c7 Add test for rotateToUpOrientation(accordingTo: .downMirrored)
- 36ea2c9e584e1092ac1bd7844c3a857db6c57a59 Add test for rotateToUpOrientation(accordingTo: .leftMirrored)
- 016ead45a57013c8a7bcd857fea41ced142fef68 Add test for rotateToUpOrientation(accordingTo: .left)
- 7eb3b5ced68f81705bdabd43d30598f024aad669 Add test for rotateToUpOrientation(accordingTo: .rightMirrored)
- 034e489fe02b95808adf648da0c3a85798f2678f Add test for rotateToUpOrientation(accordingTo: .right)
- 578b31fb2633945cfdb2ad21918683120633239c Rewrite rotation tests
- 3c9735c4a2bcdac61f70f257f07c0a5e24391cee Implement Bitmap rotation according to exif orientation tag

TIL how to copy permissions from one file to another file: chmod --reference=file-to-copy-permissions-from file-to-copy-permissions-to.



Tuesday, December 26, 23: TIL how to install Ubuntu on Raspberry Pi

TIL how to install Ubuntu on Raspberry Pi. It’s much easier now than it used to be.



Sunday, December 24, 23: TIL how to copy whole website onto local machine with just one wget command

TIL how to copy whole website onto local machine with just one wget command.

wget --mirror --convert-links --wait=2 https://example.com


Thursday, December 21, 23: TIL what does ** (double star/asterisk) and * (star/asterisk) for parameters in Python

TIL what does ** (double star/asterisk) and * (star/asterisk) for parameters in Python.

Browsed Quadcopter stabilization based on IMU and Monocamera Fusion.

Browsed Target Recognition and Following in Small Scale UAVs.

All these are about Crazyflie. May be onetime I could run these.

Browsed Autonomous drone hunter operating by deep learning and all-onboard computations in GPS-denied environments referenced from latter.



Monday, December 18, 23: TIL asyncio.sleep

Read Acro Mode vs. Self-Level Mode.

Came across this line in Python code I have been reviewing await asyncio.sleep(1). Intuitively it is understandable what it is for but I wanted to double check and asked ChatGPT. Answer was quite good:



Saturday, December 16, 23: TIL periphery - tool to find dead Swift code

TIL periphery to find dead Swift code. Ran it against swift-geometrize. It really shows not used stuff whci could be eliminated.

TIL Bullet Physics SDK Physics SDK: real-time collision detection and multi-physics simulation for VR, games, visual effects, robotics, machine learning etc.



Friday, December 15, 23: TIL .netrc; TIL how to run specific test case with swift test

TIL .netrc.

TIL how to run specific test case with swift test. Option to use to runs specific test:

--filter <filter>       Run test cases matching regular expression, Format:
                          <test-target>.<test-case> or <test-target>.<test-case>/<test>

swift test --filter "geometrizeTests.BitmapTests/testRotateLeft" runs specific test

swift test --filter "geometrizeTests.BitmapTests" runs all tests in test case.

swift test -l lists all available tests.

TIL how to “rename” git tag if I changed my mind.



Thursday, December 14, 23: TIL how to save image data into a file in debug session in Xcode

How to save image data into a file in debug session in Xcode? Suppose d is Data of PNG image. To save it into a file just run in Xcode console expr try! d.write(to: URL(filePath: "/tmp/1.png")).



Tuesday, December 12, 23: TIL MoCap positioning system

TIL what MoCap positioning system is - it’s Motion Capture positioning. There’s also Loco positioning system - a local positioning system.

Read Go with the Flow: Relative Positioning with the Flow deck of Bitcraze.

TIL what is Architectural decision.



Monday, December 11, 23: TIL How to generate TLS certificate in command line

TIL How to generate TLS certificate in command line.



Friday, December 08, 23: TIL atan2

TIL atan2.



Thursday, December 07, 23: TIL Webber, SwifWeb, swiftlang.xyz; Dug in swiftwasm.org

Dug with swiftwasm.org. Would like to give it a try for web page for geometrize bot.

This is interesting How to Use Swift for Web Development. Besides of Carton it mentions Webber, which is made for SwifWeb projects. SwifWeb is different in that it wraps the entire HTML and CSS standards, as well as all of the web APIs.

TIL swiftlang.xyz, hassle-free install of the Swift programming language on Ubuntu/Debian using the apt package manager.



Sunday, December 03, 23: TIL async/await in JavaScript

TIL async/await in JavaScript: A Beginner’s Guide to JavaScript async/await, with Examples. Used this it pull request Update geometrized svg results in 10 steps on web page.



Saturday, December 02, 23: Watched some intro lectures on topic Control systems engineering

Cool playlist on control systems engineering.



Friday, December 01, 23: TIL Python Decorators

TIL Python Decorators.



Thursday, November 30, 23: TIL how to hide and show HTML elements with JavaScript

TIL how to hide and show HTML elements with JavaScript: Buttons to hide and show an element in JavaScript.

TIL Is Your ESC Broken | HOW TO FIND OUT. If wish I knew this yesterday. This could have saved me a couple of hours.



Wednesday, November 29, 23: TIL ArduPilot Development Site

TIL ArduPilot Development Site - it has a lot of useful information.



Tuesday, November 28, 23: Read Create a Text File in Memory Then Download It on Button Click With Vanilla JS

Read Create a Text File in Memory Then Download It on Button Click With Vanilla JS, used this in PR Add button for downloading svg on web page.



Monday, November 27, 23: TIL what is Balun

TIL what is Balun. It’s from balanced to unbalanced, originally, but now dated from balancing unit. It’s an electrical device that allows balanced and unbalanced lines to be interfaced without disturbing the impedance arrangement of either line.

TIL Odometry - is the use of data from motion sensors to estimate change in position over time. The word odometry is composed of the Greek words odos (meaning “route”) and metron (meaning “measure”).

TIL what is Rotary encoder.

Came across Agilicious: Open-Source and Open-Hardware Agile Quadrotor for Vision-Based Flight.

Read Deep Drone Acrobatics.

Read How to avoid common problems with charts.

Came across great answer for the question Is putting your favicon.ico file in a non-root path a bad idea?.

TIL Vapor 4 supports SSL (TLS), despite of Vapor 3 which needed Ngnx for this.



Saturday, November 25, 23: TIL Ziegler Nichols Method for tuning PID controllers

Read Demystifying FPV Drone Rates: Betaflight & Actual Rates Explained.

Note that my rates differ depending on how I hold the sticks.

Read You are holding the sticks wrong! Thumb, Pinch or Hybrid-Pinch?.

Read How to Tune FPV Drone Filters and PID with Blackbox.

You can totally tune your quad to fly decently without Blackbox as I described in this post, but Blackbox gives you the full insight into what’s really going on with the drone and allows you to unleash its full potential. Things like noise filtering and tiny overshoots you can only see clearly in Blackbox. If you are a perfectionist or just someone who like to tinker, this is going to be the tutorial for you.

TIL Ziegler Nichols Method for tuning PID controllers.



Friday, November 24, 23: TIL ss linux command

TIL about ss, another utility to investigate sockets.



Thursday, November 23, 23: Read Open Source Motion Capture for Autonomous Drones: $20 system for room-scale millimeter level precision motion capture

Read Open Source Motion Capture for Autonomous Drones: $20 system for room-scale millimeter level precision motion capture.



Tuesday, November 21, 23: Read D-Bus Tutorial

Read D-Bus Tutorial.



Monday, November 20, 23: TIL about dbus

Browsed dbus specification.

TIL what is UNIX_FD. Here is ChatGPT’s answer on question “What is UNIX_FD?” The answer is much better then Google search results.

UNIX_FD typically refers to a file descriptor in Unix-like operating systems. In Unix, everything is treated as a file, and file descriptors are a way to represent and manage I/O resources, such as files, pipes, sockets, etc.

A file descriptor is a non-negative integer that uniquely identifies an open file within a process. The three standard file descriptors are:

0: Standard Input (stdin) 1: Standard Output (stdout) 2: Standard Error (stderr)

Additional file descriptors can be opened for other purposes.

I like terms Marshalling/Demarshalling.

TIL about NSAppClipRequestEphemeralUserNotification, ephemeral push notifications to which there’s no need to request user permission.



Saturday, November 18, 23: TIL swift-mmio

Read Command Design Pattern and Command Design Pattern.

TIL swift-mmio.



Tuesday, November 14, 23: TIL Hummingbird

Browsed Deep dive into Swift frameworks - everything about Swift modules, libraries, packages, closed source frameworks, command line tools and more.

Read The repository pattern for Vapor 4.

Read Swift visitor design pattern.

Read Lenses and prisms in Swift.

Read Beginner’s guide to server-side Swift using the Hummingbird framework.

Read Swift Enums Are ‘Sum’ Types. That Makes Them Very Interesting.

Read Swift Metatypes: What They Are and Why You Should Care.



Monday, November 13, 23: TIL what is Proportional navigation

TIL what is Proportional navigation.

TIL formal definition of Guidance, navigation, and control (abbreviated GNC, GN&C, or G&C).

Read The complete guide to Betaflight GPS Rescue Mode. Other posts of the author on various FPV topic also worth attention.

Read GPS Rescue 4.4 chapter of Betaflight WiKi. Side learning:

Use UBlox. GPS units configured to use NMEA often update only once per second, or even slower. This makes GPS Rescue very jerky, and almost unusable. It’s better to use UBlox, which by default return data regularly at 5 times a second.

Read How to Tune Betaflight FPV Drone Filters and PID with Blackbox:

You can totally tune your quad to fly decently without Blackbox as I described in Betaflight FPV Drone Tuning In 10 Simple Steps, but Blackbox gives you the full insight into what’s really going on with the drone and allows you to unleash its full potential. Things like noise filtering and tiny overshoots you can only see clearly in Blackbox. If you are a perfectionist or just someone who like to tinker, this is going to be the tutorial for you.

Above mentioned Betaflight FPV Drone Tuning In 10 Simple Steps also worth reading!

Read Betaflight’s PID Tuning Guide.

This image is so good that I put it here: PID Compensation Animated

  • P = The present (proportional)
  • I = The Past (integral)
  • D = The Future (derivative / damping) !Dangerous

PID-tuning in a nutshell

Raise P till quad is “sharp”

Raise D till it’s soft enough

Raise I till (too much looses control (slow response)

if oscillation is fast, reduce D

if oscillation is slow, raise D (or lower P)



Sunday, November 12, 23: TIL Linker script

While exploring betaflight I learned there’s a programming languge for linker - linker script.

TIL what GPS fix state means: Understanding the 3 States of GPS/GNSS Signals:

GPS or GNSS receiver can pick up signals from at least four satellites, it is said to be in the “Fix” state. In this state, the receiver can determine the user’s location within a high range and can provide accurate information about the user’s movement and velocity. The location is stable and does not change rapidly. This state is common in places with good satellite visibility, such as in open countryside or clear skies.

All three states Of GPS/GNSS are: Single, Float and Fix.



Thursday, November 09, 23: TIL Apple has service to check whether clients connecting to your server are valid instances of your app

TIL Apple has Attest - service to check whether clients connecting to your server are valid instances of your app Validating Apps That Connect to Your Server.

setup-swift GitHub action for configuring Swift for both macOS and Ubuntu which I should definitely use instead of manually installing Swift as I do now.

TIL processorCount in NSProcess which I should use in swift-geometrize.



Wednesday, November 08, 23: Read That is Why You and I Should Become Rustaceans

Read That is Why You and I Should Become Rustaceans.

Crab comes from the fact that Rust developers call themselves, “Rustaceans”, which comes from playing with the English word “Crustacean”. Crustacean refers to marine animals with hard shells. Then, Karen Rustad Tölva designed a cute crab named “Ferris the Crab” and it somehow became an unofficial mascot of the Rust language. The name “Ferris” comes from playing with the word “Ferrous”, which means “related to iron”, and this is in turn a play on the fundamental meaning of the word “Rust”, which means “corrosion”. “Again… it’s really multi-layered. It is slightly beyond my imagination”…

WiKi now defines Rustacean as a user of the Rust programming language.



Monday, November 06, 23: Read paper State Machine Design Pattern

Read paper State Machine Design Pattern.

Browsed classical book PID controllers theory design and tuning.

Played with online PID control simulator allowing you to try out a PID controller interactively by adjusting the tuning parameters in realtime. Would be good task to port this into Swift.

Played with sandbox application where you can play with a basic, manually-tuned PID control loop.



Saturday, November 04, 23: TIL about ExpressLRS Airport

TIL about ExpressLRS Airport.



Friday, November 03, 23: Experimented with сreating drag and drop uploader with Vapor

Experimented with Creating a drag and drop uploader with preview in Javascript and AJAX calls using Vapor 4.

TIL GitHub exposes user’s public keys under https://github.com/username.keys. ssh git@github.com checks if my keys are correct exposes my name to anyone who has my public key.



Wednesday, November 01, 23: Tried neovim-qt for the first time

Installed neovim-qt on Ubuntu server and tried using it on server with X-forwarding GUI to my mac. Note to future self: it’s launched with nvim-qt.

Read Tired of crashing? Use Open Gimbal! by Bitcraze. It’s brilliant idea.



Monday, October 30, 23: TIL what is slug in URL

Read Building static and dynamic Swift libraries using the Swift compiler - it is all about emitting various Swift binaries without the Swift package manager, but only using the Swift compiler.

TIL what noqa means.

TIL library target in Swift Packet Manager has type which could be static or dynamic:

Came accross SystemPackageProvider in systemLibrary(name:path:pkgConfig:providers:) in PackageDescription. System package could install system library with brew or apt on macOS and Linux.

TIL What Is a Slug? URL Slugs and Why They Matter for SEO.



Sunday, October 29, 23: Passed over chapter 3 of Practical Server Side Swift book

Passed over chapter 3 of Practical Server Side Swift book.



Saturday, October 28, 23: TIL about keyboardLayoutGuide in iOS 15

TIL about keyboardLayoutGuide which appeared in iOS 15.

TIL what is Vulkan:

Vulkan is a new-generation graphics and compute API for high-efficiency, cross-platform access to GPUs. As the industry’s only open standard modern GPU API, Vulkan is unique in enabling developers to write applications that are portable to multiple diverse platforms.



Thursday, October 26, 23: TIL what is SGML

TIL what is SGML - Standard Generalized Markup Language.



Wednesday, October 25, 23: TIL how to make Vapor listen port in external IP address

Hung in Improving the Beginner’s PID – Introduction. I should pass through all series. May be, reimplementing everything in Swift package swift-pid.

Read How To Open a Port on Linux. How To Set Up a Firewall with UFW on Ubuntu 22.04. It finds out that in my case a problem was not in closed port when I tried access Vapor app by external IP from another machine, but rather with the fact that by default Vapor waits for connection only from 127.0.0.1. It has to be run like swift run App serve --hostname 164.90.230.212 to wait for connection from external IP address of its host machine: Vapor Server documentation. It funny, that book Server Side Swift never mentions how to launch Vapor app for waiting for external connections.

Read Running Vapor apps in the Cloud using Docker and Digital Ocean.

TIL AWS has special service to run containers - Amazon Elastic Container Service.

TIL what to do when Ctrl-C doesn’t stop process. Short answer: Ctrl-Z and if process reacts on that, then kill -9 PID.



Tuesday, October 24, 23: TIL ssh -A for agent forwarding

TIL ssh -A aka agent forward while setting vscode to work with project on remote computer. I did’t get from man what exactly -A is for so I asked chatGPT:

Explain me please ssh agent forward like I am five years old.

Sure! Imagine you have a magic key that can open a treasure chest, but you don’t want to carry the key with you all the time because it’s very special and important. So, you keep the key in a safe place at home.

Now, let’s say you go to your friend’s house, and your friend also has a treasure chest that you want to open. Instead of bringing your magic key with you, you tell your friend, “Hey, I have a special key at home that can open chests. Can you help me use it?” Your friend says, “Sure, just tell me when you need it.”

When you want to open your friend’s treasure chest, you ask your friend to use your special key, and your friend magically makes it work without giving you the actual key. Your friend helps you open the chest with your key, and you get the treasure without ever having to carry the key around.

In the world of computers, SSH (Secure Shell) Agent Forwarding works in a similar way. Instead of carrying your special key (used for logging into remote computers securely) with you everywhere, you keep it on your own computer. When you connect to another computer using SSH, you can tell that computer to use your special key without actually sharing the key itself. This way, you can log in securely to different computers without carrying your key with you all the time. It’s like having a magical key that you can use wherever you go!



Monday, October 23, 23: Dug in AirSim sources

Dug in AirSim sources and found in RotorParams.hpp interesting link to propeller performance database: UIUC Propeller Data Site.

Read Editing Swift Packages in Visual Studio Code. Looks much more convinient than in Xcode.

Read Understanding Swift Packages and Dependency Declarations. That’s interesting. I used to see swift packages as dependecies in Xcode for once which were used only in test targets. That draw question like “What this package is doing in my project?”.

no longer would you have to download all transitive dependencies if some were only used in testing of your dependencies.

I should look into this post next time I have strange errors resolving dependencies after editing package manifest.



Saturday, October 21, 23: TIL about @unchecked Sendable

TIL about @unchecked Sendable in Swift.



Thursday, October 19, 23: Read slides of VimConf 2019 talk by NeoVim creator Justin Key

Read slides of VimConf 2019 talk by neovim creator Justin Key.



Tuesday, October 17, 23: Dug in interesting 2D geometry C++ library

Googling about rendering thick Bezier curves came across Adaptive Subdivision of Bezier Curves. An attempt to achieve perfect result in Bezier curve approximation. It’s by author of C++ library Anti-Grain Geometry.

For ages I haven’t worked with svn. Now I had to install git svn on macOS. What I wanted to make a copy in git of svn repo is: git svg clone svn://svn.code.sf.net/p/agg/svn/ agg-svn.



Monday, October 16, 23: TIL about withLock existing in all kinds of locks

TIL about withLock existing in all kinds of locks. It’s strange I haven’t encountered it before. It’s declared in NSLocking protocol.

private let lock = NSRecursiveLock()
lock.withLock {
    state[keyPath: keyPath]
}

Set up workflow to build and test swift-geometrize on Ubuntu. Side effect of this - install-swift.sh script for installing Swift 5.9 on Ubuntu 22.04. Currently workflow installs dependencies with apt-get everytime it runs. That’s waist of resources. It could be improved with caching. It looks a bit complicated. May be later I will return to it.

I see this GitHub Actions’ Workflow for Swift Package which builds Swift package on both Ubuntu 22.04 and macOS and uses caching for dependencies. A bit more complex Action Swift Setup of the same author in Actions marketplace. May be I should just use it.

This is nice Action Swift Release for releasing Swift package.

TIL how strange YAML syntax is that it needs dedicated website to explain how to make multi-line string in YAML. I needed multi-line string for incorporating Swift install commands into GitHub workflow.



Thursday, October 12, 23: Read great A Primer on Bézier Curves

TIL how to unstash certain files: git checkout stash@{<index-no>} -- <filename> or git restore -- source=stash@{<index-no>} -- <filename>

It’s gem: A Primer on Bézier Curves.

From [Stack overflow answer on a question how to draw a thick straight line with modified Brasenham algorithm(https://stackoverflow.com/a/20754640/942513) come to working C code on GitHub which I am using now in swift-geometrize.

Found paper A Rasterizing Algorithm for Drawing Curves which I am going to use later to draw Bezier Curves with thickness on swift-geometrize.



Monday, October 09, 23: Found several Swift senseless diagnostics

Found today that Swift inferring type mistakenly insists collection is heterogeneous.

Swift insists collection is heterogeneous

But Swift is happy when type annotation is added.

But Swift is happy when type annotation is added

I guess this edge case or not handled at all or handled incorrectly in Swift compile type inference.

Another case when Swift compiler diagnostic is dummy: Swift cannot get that literal array is a collection.

Swift cannot get that literal array is a collection

One more example of useless Swift diagnostic.

Another case of senseless Swift diagnostic



Wednesday, October 04, 23: TIL what is 6DOF and 9DOF sensor fusion

TIL what is 9DOF and 6DoF Sensor Fusion Algorithms.

Adafruit’s 9DOF (9 Degrees of Freedom) breakout board allows you to capture nine distinct types of motion or orientation related data: 3 degrees each of acceleration, magnetic orientation, and angular velocity.

Six-degree-of-freedom (6DoF) sensors measure translation along three axes and rotation around three axes. These collocated measurements make it possible to fully describe building motion without the need for an external reference point.

Read Basics of 6DOF and 9DOF sensor fusion.

TIL Magnetometer ∞ shaped calibration aka Figure 8 method of calibration.

Read Accelerometer Specifications: Deciphering an Accelerometer’s Datasheet.

Came across a line in documentation: Gyroscope measures angular velocity, in 3 axis, in °/s, scale factor is LSB/(°/s). And I was puzzled how could I convert raw gyro reading into °/s. Googled it but failed to find something helpful. Then I asked ChatGPT. It’s not the first time when ChatGPT come handy:

To convert accelerometer raw readings to degrees per second (°/s), you need to follow these steps:

  1. Understand the Sensitivity: Determine the sensitivity or scale factor of your accelerometer. You mentioned in your question that the scale factor is given as LSB/g, which means it measures acceleration in units of least significant bits per gravitational force (g). This scale factor tells you how many LSBs correspond to 1 g of acceleration.

  2. Calculate Acceleration: Calculate the linear acceleration in g units from your accelerometer’s raw readings. The raw readings may be in counts or LSBs. Let’s call this value “acceleration_g.”

  3. Convert to Angular Velocity: To convert linear acceleration to angular velocity, you need to know the radius (distance from the rotation axis) at which the accelerometer is mounted. Let’s call this “r” in meters.

  4. Apply the Formula: Use the formula for angular velocity due to linear acceleration in circular motion:

    Angular Velocity (ω) = acceleration_g / r

    This formula assumes that the linear acceleration is occurring at a constant radius from the rotation axis. If the radius varies, you’ll need additional information to account for that.

  5. Units: Ensure that the units match your requirement. If your accelerometer’s raw readings were in LSBs per g, and your radius is in meters, the resulting angular velocity will be in °/s.

Here’s an example of the calculation:

Suppose you have an accelerometer with a scale factor of 1000 LSB/g, and it measures a linear acceleration of 2 g. You have it mounted at a radius of 0.1 meters (10 cm) from the rotation axis.

  1. Scale factor (LSB/g) = 1000 LSB/g
  2. Linear acceleration (acceleration_g) = 2 g
  3. Radius (r) = 0.1 meters

Now, calculate the angular velocity:

Angular Velocity (ω) = acceleration_g / r Angular Velocity (ω) = (2 g) / (0.1 meters) Angular Velocity (ω) = 20 °/s

So, in this example, the accelerometer’s raw reading of 2 g corresponds to an angular velocity of 20 °/s when mounted at a radius of 0.1 meters from the rotation axis.

TIL what is UML.

The unified modeling language (UML) is a general-purpose visual modeling language that is intended to provide a standard way to visualize the design of a system.[1]

UML provides a standard notation for many types of diagrams which can be roughly divided into 3 main groups: behavior diagrams, interaction diagrams, and structure diagrams.

Read Sequence Diagram Tutorial – Complete Guide with Examples.

Read interesting Code smells catalog.



Tuesday, October 03, 23: TIL Pipenv

Read Bicraze’s Discussion – How to handle the increasing complexity of the expansion decks

TIL Pipenv: A Guide to the New Python Packaging Tool.

TIL Ctrl+M in Xcode for formatting function parameters. It’s magic.

Formatting function parameters in Xcode



Monday, October 02, 23: Watched ArduPilot UnConference 2019 - ArduPilot Lua Scripting

Watched ArduPilot UnConference 2019 - ArduPilot Lua Scripting - Michael du Breuil about running Lua scripts directly on flight controller.



Friday, September 29, 23: TIL what does process legacyScreenSaver-x84-64 mean on Apple M1

Yesterday I have updated macOS to 14.0 Sonoma and have some difficulties making my beloved Motivation screenshot working after macOS update. Introducing new screen savers Apple has broken screensavers used before 14.0 release. Accidently I have found that process legacyScreenSaver-x84-64 takes ~100% of one of cores. Things are nore broken than I might have expected.

Googling for found this ScreenSaver: legacyScreenSaver process? thread on Apple developer forums. From it I jumped to Screen Saver framework.

Because screen savers are plug-ins for the screen saver engine, the screen saver binary must support the same hardware architecture of the running engine. As with any application, the screen saver engine uses the native architecture of the host computer. For full compatibility, make sure your screen saver supports both the x86_64 and arm64 architectures.

But why do I have legacyScreenSaver-x84-64 on M1?

Inspecting Motivation.saver bundle in /Libary/Screen Savers/ I have found that it was build in 2021. Probably, on Intel. After rebuilding on M1 and installing I see only process legacyScreenSaver (Wallpaper) taking periodically 1.9% of one CPU core. Why to take CPU time at all if screen saver is not running? But anyway it’s better then ~100% of one CPU core.



Thursday, September 28, 23: Read Access Control and protected post in Apple Swift blog

Read Access Control and protected post in Apple Swift blog explaining why Swift doesn’t have protected access control.



Wednesday, September 27, 23: Read 8.3 Customizing Git - Git Hooks of Pro Git book

8.3 Customizing Git - Git Hooks of Pro Git book.



Tuesday, September 26, 23: Read About System Integrity Protection on Mac; TIL about OpenCore Legacy Patcher

Read About System Integrity Protection on Mac.

TIL OpenCore Legacy Patcher which allows to install recent macOS releases on not supported Apple hardware.

Read What Every Programmer Should Know About Memory.



Monday, September 25, 23: TIL how to tune video in Betaflight

Watched Betaflight 4.3 Video Transmitter Tab | COMPLETE WALKTHROUGH PART 9



Saturday, September 23, 23: TIL URL Text Fragments

Puffed LiPo Batteries - Oops! Puffing is caused by gassing of the electrolyte or electrolyte decomposition.

TIL about Text Fragments to select part in URL. E.g. https://www.rchelicopterfun.com/puffed-lipo.html#:~:text=Some%20feel%20once%20a%20LiPo,and%20must%20be%20disposed%20of. opens page with text fragment selected.

Explanation Boldly link where no one has linked before: Text Fragments, Draft URL Fragment Text Directives.

Read RC LiPo Batteries. How to get the most life & fun out of them!. The website itself RC HELICOPTER FUN is dedicated to helicopters but has a lot of useful information related to RC models.

Simple data pipeline powertools: sqlite, pandas, gnuplot and friends. Why my favourite API is a zipfile on the European Central Bank’s website.

TIL Bokeh.

Read Using Uninitialized Memory for Fun and Profit

This is the story of a clever trick that’s been around for at least 35 years, in which array values can be left uninitialized and then read during normal operations, yet the code behaves correctly no matter what garbage is sitting in the array.

Browsed paper An Efficient Representation for Sparse Sets.

swift-collection has an issue discussing possible addition of Sparse Set.

Watched Betaflight 4.4 Tuning Guide + Tips and Tricks for the BEST tune! This include PID tuning.



Friday, September 22, 23: Read extreemly interesting post Exploring EXIF

Read extreemly interesting post Exploring EXIF with examples how to make sql requests to Apple Photo Library on macOS.

Read A Complete Guide to Logging in Python with Loguru.



Thursday, September 21, 23: TIL a lot about PID controller

Read Phenomenological Introduction to PID controllers.

This document focuses on building a phenomenological understanding of PID controllers through demos.

Read Analytical Introduction to PID controllers.

Watched PID controller explained, What are PID Tuning Parameters?, How to Tune a PID Controller. These are very good.



Wednesday, September 20, 23: TIL about Side Force

From In-flight propulsion system test got brilliant idea how to compare different propellers in flight. The site Shrediquette - the award-winning multirotors by William Thielicke is interesting and contains a lot of info about different self built drones. The guy seems to be from Bremen, Germany.

Great 3 parts serie Side Force Generators (SFGs) in FPV Racing, Part 2/3: Side force generators - Forces and turning, can’t find part three.

Read Some thoughts on FPV camera tilt compensation and Explanation video: FPV camera tilt compensation.

Bowsed paper Yaw/Heading optimization by drift elimination on MEMS gyroscope.



Tuesday, September 19, 23: TIL shared memory in Python

Read A Simple Guide to Shared Memory in Python. Interesting the idea to synchonize access with file locks. There’s also more traditional example of using semaphores.

Read Aerodynamics in racing multirotors Part 1, Aerodynamics in racing multirotors Part 2.



Monday, September 18, 23: TIL about SBUS

Googled for SBUS specification and failed to find good source of information. Then I asked ChatGPT: “Give me specification of SBUS protocol used in remote controlled vehicles.” Here is the answer:

SBUS (Serial Bus) is a digital communication protocol commonly used in remote-controlled vehicles, especially in the radio control (RC) hobby industry. It is known for its low latency and high precision, making it suitable for controlling various functions of RC vehicles such as drones, airplanes, helicopters, cars, and boats. Below are the key specifications of the SBUS protocol:

  1. Serial Communication: SBUS uses serial communication to transmit data between the RC transmitter (controller) and the receiver (onboard the vehicle). It operates at a baud rate of 100,000 bits per second (100kbps).

  2. Data Frame: SBUS uses a continuous stream of data frames, with each frame being 25 bytes (200 bits) long.

  3. Channel Information: SBUS supports up to 16 proportional channels, typically used for controlling different functions of the RC vehicle, such as throttle, steering, pitch, roll, yaw, and auxiliary functions. Each channel is represented by a 11-bit data word within the SBUS frame.

  4. Digital Signals: Unlike PWM (Pulse Width Modulation) signals commonly used in older RC systems, SBUS uses digital signals, which are less susceptible to interference and provide more precise control.

  5. Redundancy: SBUS systems often provide redundancy by using dual receivers. If one receiver fails or experiences interference, the system seamlessly switches to the other receiver to maintain control.

  6. Compatibility: SBUS is a common protocol in the RC industry, and many manufacturers produce SBUS-compatible transmitters, receivers, and flight controllers. It is widely used in conjunction with flight controllers in drones and other RC vehicles.

  7. Failsafe: SBUS systems include failsafe functionality. In the event of signal loss or interference, the receiver can be programmed to take specific actions, such as holding the last known control positions or returning the vehicle to a predefined safe state.

  8. Inverted SBUS: Some receivers offer an inverted SBUS signal, which can be useful when connecting to certain flight controllers or other devices that require inverted signals.

  9. Telemetry: In some cases, SBUS receivers can transmit telemetry data back to the transmitter, providing information about the status of the vehicle, such as battery voltage, signal strength, and more.

  10. Compatibility with Flight Controllers: SBUS is often used as the communication protocol between RC receivers and flight controllers in drones and other aircraft. Flight controllers interpret SBUS data to stabilize and control the vehicle.

Then I asked ChatGPT: “How to send SBUS message to Betaflight flight controller from companion computer?” Here’s the quite good answer:

Keep in mind that while SBUS is a widely used protocol in the RC hobby industry, there are other communication protocols available as well, such as PPM (Pulse Position Modulation) and PWM, which have different characteristics and are used in various applications within the RC community.

To send SBUS messages to a Betaflight flight controller from a companion computer (e.g., a Raspberry Pi or any other computer), you will need to use a communication protocol like SBUS or Serial/UART to interface with the flight controller. Here’s a general guide on how to achieve this:

  1. Hardware Setup: Ensure that you have the necessary hardware components in place:
    • Betaflight-compatible flight controller with an SBUS input.
    • Companion computer (e.g., Raspberry Pi).
    • USB-to-Serial adapter (if your companion computer doesn’t have a built-in UART).
    • Appropriate cables and connectors.
  2. SBUS to UART Converter (if needed): If your companion computer doesn’t have a UART port (many Raspberry Pi models do not), you may need to use a USB-to-Serial adapter to create a UART interface for communication. Connect the SBUS signal wire to the adapter’s RX pin and connect the adapter to the USB port on the companion computer.

  3. Configure UART Communication: On your companion computer, configure the UART port (or USB-to-Serial adapter) for communication. This may involve setting the baud rate, parity, and stop bits to match the SBUS protocol requirements. You’ll need to use a programming language like Python or a similar language to interact with the UART port.

  4. Install Appropriate Libraries: Depending on your companion computer’s platform, you may need to install libraries or packages that allow you to work with UART communication. For example, if you’re using a Raspberry Pi, you can use the serial library in Python.

  5. SBUS Message Encoding: Write a program on your companion computer that encodes your control data into the SBUS message format. This should include start and end bytes, status, and channel data, adhering to the SBUS protocol specifications.

  6. Send SBUS Data: Use your program to send the SBUS messages to the Betaflight flight controller via the UART interface. This typically involves opening the UART port, sending the SBUS data frames, and closing the port when you’re done.

  7. Configure Betaflight: Ensure that your Betaflight flight controller is configured to receive SBUS signals. This may involve setting the correct receiver protocol in the Betaflight configurator software and mapping the SBUS channels to the appropriate functions (e.g., throttle, yaw, pitch, roll).

  8. Testing and Calibration: Test your setup thoroughly to ensure that the SBUS data is being transmitted from the companion computer to the flight controller accurately. You may also need to calibrate your RC transmitter and flight controller to ensure proper control response.

  9. Safety Precautions: When testing your setup, always do so in a controlled environment, and ensure that your RC vehicle is securely placed on a stand or surface to prevent unexpected movement.

  10. Debugging and Optimization: Debug and optimize your setup as needed to ensure reliable communication and control. Monitor any error messages or feedback from the flight controller and adjust your code accordingly.

Remember that the specific implementation details may vary depending on the hardware and software you’re using, so consult the documentation for your companion computer and flight controller for more detailed instructions and compatibility information.

Not bad. Far better then I could google.

Some info about S-BUS protocol

SBUS implementation in C++: FUTABA_SBUShttps://github.com/mikeshub/FUTABA_SBUS/tree/master/FUTABA_SBUS with usage example.

Watched Everybody should be using these FPV Lua Scripts.

Browsed ArduPilots Lua Scripts section. This feature looks solid. It seems quite sophisticated algorithms like target following could be implemented by LUA script provided target coordinates in video frame are feed on some port like UART. ArduPilot’s LUA documentation, LUA script examples. Watched ArduPilot Lua scripts - basic examples has several quite interesting examples. ArduPilot Lua Scripting Basics.



Saturday, September 16, 23: TIL “content negotiation” in HTTP

TIL HTTP’s built-in “content negotiation”: How does it know I want csv? — An HTTP trick. cvbase itself is a simple web database which is free for open data - all users can upload and share unlimited public tables completely free of charge.



Friday, September 15, 23: TIL servo can be Positional rotation and Continuous rotation

TIL that regular servo motors which are rotating on some angle are called Positional rotation servo. TIL that beside of Positional rotation servo exist Continuous rotation servos. Introduction to Servo Motors.

Read Anyleaf’s blog post Quadcopter flight controller MCU comparison Or, what H7, G4, F7, F4 etc mean. Estimating drone attitude.

Read Quaternions: A practical guide.



Thursday, September 14, 23: TIL PPM, PGM, PBM, PNM textual file formats for images/bitmaps

In my projects I often reinvent textual formats for images or bitmaps, e.g. like in this unit test of Swift package RaspberryPiSenseHat for Raspberry Pi Sense , or like this bitmap saved for unit test in swift-geometrize Swift package. TIL I learned there is a family of formats for this since 1980s:

  • portable pixmap format (.PPM)
  • portable graymap format (.PGM)
  • portable bitmap format (.PBM)

They are also sometimes referred to collectively as the portable anymap format (.PNM), not to be confused with the related portable arbitrary map format (.PAM).

The “magic number” (Px) at the beginning of a file determines the type, not the file extension, although it is best practice to use the right extension if possible.

P1
# This is an example bitmap of the letter "J"
6 10
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
1 0 0 0 1 0
0 1 1 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0

Here is the resulting image: This is an example bitmap of the letter "J" turned into PNG

It does make sense to make swift package for this and then reuse this package in my projects.

Came across interesting contest for generating PBM file from ASCII text with minimal count of source code lines Generating PBM bitmap files from ASCII text. Swift is missing there. It’s a challenge!

Looking into above mentioned formats came across Netpbm toolkit, here’s Netpbm user manual. It has 300+ programs - here’s Netpbm’s full program list: converters, image generators, image editors, image analyzers and miscellaneous like extracting individual planes from image or combining planes into images and so on.

Read PointFree’s blog post Inline Snapshot Testing about releasing new version of swift-snapshot-testing. 3 years old blog post of initial implementer: Inline Snapshot Testing.

TIL CLI ioreg | grep -i cam for macOS to list all available camera/video devices. Same with ffmpeg: ffmpeg -f avfoundation -list_devices true -i "".



Wednesday, September 13, 23: TIL what does ‘!r’ in format string mean in Python; What ExpressLRS and Crossfire have in common

TIL what does ‘!r’ in format string mean: Python: the !r string format and the __repr__() and __str__() methods.

Some time ago I was confused by one of my colleagues stating and insisting that ExpressLRS and Crossfire are the same and both use Crossfire protocol. So I spent some time googling for that. The answer is “No”. ExpressLRS and Crossfire are different. What they have in common - they both use CRSF protocol.

Following exerts are from AnyLeaf Blog post ExpressLRS overview. AnyLeaf manufactures flight controllers, ExpressLRS receivers and other drone electronics as well as some water products.

Receivers (Rx modules) process RF signals, then pass them to the FC over a pair of UART lines. The protocol they use with the FC is Crossfire (CRSF). (CRSF is also associated with a radio system, but ELRS only uses it to communicate with the FC) This means that FC firmware that supports CRSF supports ELRS. This protocol rarely changes, so FC firmware doesn’t need to be updated to take advantage of ELRS updates.

Recall how we described how ELRS communicates with the FC using CRSF - ELRS maps its own channel configuration on CRSF’s. Unless you write or maintain FC firmware (like Betaflight), you don’t need to worry about this. Note that ELRS channels - including number of channels, what they correspond to, and their bit depth - doesn’t correspond exactly to the CRSF channels your FC reads.

Interesting issue CRSF Protocol Repo where TBS (Team Black Sheep - team behind Crossfire) discussing opening CRSF protocol and making separate repo for it.

Some details of CRSF protocol could be found in crsf.c of betaflight.

Here is WiKi CRSF Protocol in ExpressLRS repo.

If we talk about ExpressLRS - Crossfire differences, here is interesting reddit topic ELRS VS CROSSFIRE. It has very interesting links. ExpressLRS has lower latency and huge distance range.



Tuesday, September 12, 23: TIL git looses commit signature after rebasing and merging with GitHub

TIL git looses commit signature after rebasing and merging with GitHub. Rebasing locally and then force pushing into main is bad idea. Here is one solution Rebase And Sign Multiple Git Commits to do it locally and manually. But it doesn’t solve a problem of need to force push into main.



Monday, September 11, 23: Read Martin Fowler’s CodeSmell

Read Martin Fowler’s CodeSmell.

Some long methods are just fine. You have to look deeper to see if there is an underlying problem there - smells aren’t inherently bad on their own - they are often an indicator of a problem rather than the problem themselves.



Saturday, September 09, 23: TIL class variables and map function in Python

TIL how to use class variables in Python: Class or Static Variables in Python .

TIL how to use map function in Python: Python’s map(): Processing Iterables Without a Loop. I find it ugly map(lambda b: b.bbox.as_cv2_rect, detections) but with it is better then without.



Friday, September 08, 23: TIL how to write unit tests in Python

TIL how to write unit tests in Python A Gentle Introduction to Unit Testing in Python.



Thursday, September 07, 23: TIL ssh -X for X Windows forwarding

TIL -X option to enable X Windows forwarding X Windows Forwarding on Mac OS X. X Windows has to be installed on local Mac. I downloaded XQuartz, a version of X Window System that runs on macOS. Than I could login ssh -X my-ubuntu-server and there run xclock and see:

xclock



Wednesday, September 06, 23: Read great series how to build quadcopter’s Flight Controller from scratch

Read Automatic labeling (russian). Semi-automatic I would say. The idea is to use Grounding DINO model to detect objects of interest and set bounding boxes. Grounding DINO model detects object by their text prompts. Then human in CVAT should manually set a label for each detected box. The post was inspired by Grounding DINO: SOTA Zero-Shot Object Detection and tutorial in format of Jupyter notebook. Provided docker image requires nvidia video card with 3GB RAM. The whole flow in opensource on GitHub. I don’t see the reason why the last step, which essentially object classification, cannot be automated as well.

Was puzzled to come across asterisk before parameter in Python which looked like pointer deaddressing in C:

self.mavlink_connection.mav.rc_channels_override_send(
    self.mavlink_connection.target_system,
    self.mavlink_connection.target_component,
    *rc_channel_values
)

Understanding the asterisk(*) of Python.

Interesting that asterisk (*) and forward slash () could be used in Python instead of parameter in function call. It’s absolutely crazy as for my taste. These two divide positional and keyword parameters. What Are Python Asterisk and Slash Special Parameters For?.

Read great series My Greatest Engineering Accomplishment: The Scout Flight Controller.

I started the project on April 29, 2023. 70 days and 1,194 code commits later, on July 7, 2023, Scout achieved its first successful flight.

How I Developed the Scout Flight Controller, Part 1: Quadcopter Flight Dynamics.

How I Developed the Scout Flight Controller, Part 2: Capturing Telemetry with the Gyroscope

To rectify this issue, we must account for gyroscope bias with a calibration. The calibration process is conceptually simple: upon system boot-up, we dedicate a few seconds to monitor the raw gyroscope readings while the quadcopter remains perfectly stationary. We then calculate the average of these observed values across all three axes. In all subsequent gyroscope readings, we will subtract each axis’ respective calibration reading (the average we calculated) to get the “calibrated” reading; essentially, we are subtracting the bias out of the raw reading. This adjustment effectively eliminates the bias from the raw readings, providing us with a “clean” reading that can be utilized within our flight controller code.

How I Developed the Scout Flight Controller, Part 3: Receiving Control Inputs via an RC Receiver

Following idea I will borrow along with provided normalize function.

Instead of working with these values that range from 1,000 to 2,000, I preferred to normalize each within the range of -1.0 to 1.0 for the roll, pitch, and yaw, and between 0.0 and 1.0 for the throttle. This makes the values easier to understand and work with. I wrote the following simple function in Python to handle the normalization process:

def normalize(value:float, original_min:float, original_max:float, new_min:float, new_max:float) -> float:
    """ Normalizes (scales) a value to within a specific range. """
    return new_min + ((new_max - new_min) * ((value - original_min) / (original_max - original_min)))

How I Developed the Scout Flight Controller, Part 4: Stabilizing Flight with PID Controllers. It’s described here how 3 PID controllers for pitch, roll, yaw work together to calculate thrust for 4 drone motors.

# calculate throttle values
t1:float = adj_throttle + pid_pitch + pid_roll - pid_yaw
t2:float = adj_throttle + pid_pitch - pid_roll + pid_yaw
t3:float = adj_throttle - pid_pitch + pid_roll + pid_yaw
t4:float = adj_throttle - pid_pitch - pid_roll - pid_yaw

Beside of above snippet, article contain full PID controller implementation.

How I Developed the Scout Flight Controller, Part 5: Controlling Brushless Motors with ESC’s and PWM.

How I Developed the Scout Flight Controller, Part 6: Hardware.

TIL that a circuit to convert DC current to lower voltage is called battery eliminator circuit (BEC). BEC to 5V is integrated in some ESC.

The BEC, a separate circuit within the ESC, provides power to other 5V components on the quadcopter. Instead of needing to install a secondary 5V battery, we can tap into the BEC of one of the ESCs. It handles the conversion from the LiPo’s 16.8V to a stable 5V, which we can utilize to power these devices.

Please note that not every ESC includes a BEC.

How I Developed the Scout Flight Controller, Part 7: Full Flight Controller Code. This contain full code. I am surprised how minimalistic this code is. Create work!



Monday, September 04, 23: Read The Worst Programmer I Know essay; Requested access to llama

Read The Worst Programmer I Know essay. It’s so good! I would have shown this essay to some of my past employers.

Requested access to llama. Will try to use it.



Sunday, September 03, 23: TIL how to set up in Betaflight newly built drone

Watched once again Betaflight for Beginners | The settings you need to get your drone in the air.

Some notes for future self.

GPS didn’t want to start working.

Set baud rate taken from GPS module datasheet: "Set baud rate taken from GPS module datasheet"

Set protocol from same datasheet: Set protocol from GPS module datasheet

It stays unclear how do I setup TX/RX channels for GPS and radio receiver if at all. I set GPS receiver and radio receiver on lines which match RX/TX channels where they are soldered. But that UART channels, not RX/TX channels.

GPS receiver is soldered to RX/TX

Here are final settings:

Final settings

Finally everything worked and I firstly got self built drone in the air:

Self built drone in the air



Saturday, September 02, 23: TIL about Sensor Fusion algorithms

Read Concept of Sensor Fusion and Its Types.

Read Sensor Fusion Algorithms Explained.

Read paper Experimental Comparison of Sensor Fusion Algorithms for Attitude Estimation.



Thursday, August 31, 23: TIL Read ExpressLRS Vs Crossfire

Read ExpressLRS Vs Crossfire: Which to Choose for FPV Drones?

How to set hostname on Raspberry Pi.



Tuesday, August 29, 23: TIL htop, human top

TIL htop, human top.

htop sceenshot



Thursday, August 24, 23: Read git: fetch and merge, don’t pull

Read git: fetch and merge, don’t pull.



Wednesday, August 23, 23: Read iOS Architecture: A State Container based approach; Passed over Tutorial Your First Simulation in Webots

Read iOS Architecture: A State Container based approach. Has very good introduction which might make sense to cite on some interviews.

Passed Tutorial 1: Your First Simulation in Webots (30 Minutes).



Tuesday, August 22, 23: Watched Lecture 1 | Stanford CS193p 2023

Watched Lecture 1 | Stanford CS193p 2023.

Read Bash Reference Manual | 7 Job Control.

Read Composition over inheritance.



Saturday, August 19, 23: TIL script

TIL script shell command for recording termial session.

The script utility makes a typescript of everything printed on your terminal. It is useful for students who need a hardcopy record of an interactive session as proof of an assignment, as the typescript file can be printed out later with lpr(1).



Friday, August 18, 23: TIL suckless.org

Serendipity led me to libschrift, a lightweight TrueType font rendering library, which a candidate to be used for rendering fonts for swift-geometrize.

libschrift refers suckless.org philosophy

We are the home of quality software such as dwm, dmenu, st and plenty of other tools, with a focus on simplicity, clarity and frugality. Our philosophy is about keeping things simple, minimal and usable. We believe this should become the mainstream philosophy in the IT sector. Unfortunately, the tendency for complex, error-prone and slow software seems to be prevalent in the present-day software industry. We intend to prove the opposite with our software projects.

SwiftTrueTypeFont is one more candidate to explore reading TrueType fonts.



Thursday, August 17, 23: TIL what is Filesystem Hierarchy Standard (FHS) and difference between /tmp and /var/tmp

TIL difference between /tmp and /var/tmp.

TIL what is Filesystem Hierarchy Standard (FHS).

TIL about PiJuice. It’s HAT for Raspberry Pi (not only Zero) which allows powering it on scedule to run some short periodic tasks.

Provides a full uninterrupted power supply solution for the Raspberry Pi Zero. These boards are compatible with any single-cell Lithium Polymer (LiPo) battery. The PiJuice Zero includes an integrated real-time clock and onboard intelligent on/off switch. These boards feature two programmable multi-colored RGB LEDs and are fully CE and FCC-tested. The PiJuice Zero comes with a full power management API for Raspberry Pi OS with auto shutdown capability when running low on batteries. These boards are also compatible with Raspberry Pi A+, B+, 2B, 3B, 3B+, 4B, Pi Zero, and Pi Zero W. The PiJuice Zero board is ideal for portable Pi, RasPi portable games console, point-and-shoot cameras, weather stations, and compact robots.



Sunday, August 13, 23: Wasted time trying to launch BLHeli Configurator on macOS

Wasted time trying to launch BLHeli Configurator. It just doesn’t run on macOS anymore. There are lot of posts searching for help how to launch it on macOS. There’s open source for it: blheli-configurator. It’s not maintained. Building instruction are tedious as for Apple developer. Might be commercially viable idea to make paid app for this.



Saturday, August 12, 23: TIL how to setup Raspbery Pi with Raspberry Pi Imager

Was surprised today how easy it is to make bootable SD card for Raspberry Pi with help of Raspberry Pi Imager Raspberry Pi OS.

Raspberry Pi Imager

TIL how to setup WiFi on Raspberry Pi. The first one could be adjusted with Raspberry Pi Imager mention above. Later new SSID could be added with raspi-config.

TIL CLI for macOS to show WiFi SSID in terminal: /System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport -I. Source - stackoverflow.



Friday, August 11, 23: TIL CLI for macOS system_profiler SPUSBDataType to list available USB devices

Noce reading Building Wireless Soil Moisture Sensors With Custom PCB.

TIL CLI for macOS terminal to list available USB devices system_profiler SPUSBDataType.



Wednesday, August 09, 23: TIL what is the “bookmark” in my terminal when I touch the icon on my touchbar

Read How to Open Websites Automatically with Automator.

I have googled exactly this: What is the “bookmark” in my terminal when I touch the icon on my touchbar?.

Terminal User Guide: Use marks and bookmarks in Terminal on Mac.

TIL with keyword in Python.

Followed Nonblocking stdin read works differently in Python 3 developing keyboard control for drone.



Tuesday, August 08, 23: TIL about foobar.withgoogle.com

TIL about foobar.withgoogle.com. Google cought me when I googled about multithreading in Python.

Read D-Bus WiKi page.



Monday, August 07, 23: TIL brave search

TIL brave search.



Sunday, August 06, 23: Watched Learn To Test Your Flight Controller With A Multimeter

Watched Learn To Test Your Flight Controller With A Multimeter! Don’t Throw It Away!.



Saturday, August 05, 23: TIL Raspberry Pi Zero doesn’t have power LED

TIL Raspberry Pi Zero doesn’t have power LED: Raspberry Pi Zero Headless Quick Start: Is There Even Life?.



Friday, August 04, 23: TIL about Xcode Releases and how now old Xcode releases could be launched

TIL about Xcode Releases with download links to all versions of Xcode.

TIL downloaded old version of Xcode couldn’t be just run as earlier. :

  • Download the desired xcode version app from https://xcodereleases.com
  • Unzip the app and rename it to Xcode-<version>.app;
  • Move it to /Applications directory;
  • Run xcode-select command: xcode-select -s /Applications/Xcode-<version>.app;
  • Confirm that the correct Xcode version is selected with xcode-select -p.


Thursday, August 03, 23: TIL Python 3.10 intoduced match case

TIL How to add Google Analytics to a blog hosted on Github pages to find out that no one is reading this.

TIL Python 3.10 intoduced match case which is fo switch case exists in C and Swift.



Wednesday, August 02, 23: TIL different ways to detect key presses in Python

TIL about Curses - terminal-independent screen-painting and keyboard-handling facility for text-based terminals. Nice to build GUI inside terminal. But it’s not what I need.

TIL pynput. Library allows to control and monitor input devices. Currently, mouse and keyboard input and monitoring are supported. Very nice but in monitors keyboard input even if app is not active which need special rights which I don’t like. And on Ubuntu it says platform is not supported:

 raise ImportError('this platform is not supported: {}'.format(
ImportError: this platform is not supported: ('failed to acquire X connection: Bad display name ""', DisplayNameError(''))

Try one of the following resolutions:

 * Please make sure that you have an X server running, and that the DISPLAY environment variable is set correctly

TIL keyboard, but it requires sudo on Linux so isn’t practical.

So I stopped on python-keyboard-detection.



Monday, July 31, 23: TIL what is Real-time kinematic positioning

Bookmarking ARDU Remote: simple RC radio controller. Radio remote controller - that’s what is missing for Crazyflie.

Read about UAVCAN.

TIL about GStreamer - an extremely powerful and versatile framework for creating streaming media applications.

TIL Real-time kinematic positioning.

Bookmarking post about selecting drone components DIY autonomous drone controlled over Internet. From above learned about xcopterCalc - Multicopter Calculator.

Read Choosing platform for experiments with drones.



Saturday, July 29, 23: TIL Ubuntu cannot be installed from packages on Raspberry Pi Zero v1; Played with GPIO on Jetson

TIL that Ubuntu cannot be installed from packages on Raspberry Pi Zero v1, but on v2 can. But Raspbian could be installed on both. That works for me.

Played with GPIO on Jetson. I could blink with LED connected to GPIO (plus of LED connected to GPIO, minus over resistor 330 Ohm - to ground). But reading button state didn’t work for me (one pin of button is connected to GPIO, another over same resistor - to 3.3V pin).



Friday, July 28, 23: TIL where Xcode stores derived data

Bookmarking SwiftDraw. It’s candidate to be used to convert characters into vector to build vector font to be used to build new feature for swift-geometrize

TIL where Xcode stores logs - in DerivedData/{ProjectName}/Logs. DerivedData itself resides in ~/Library/Developer/Xcode/DerivedData by default (could be changed in Xcode settings).



Thursday, July 27, 23: TIL arp -a for listing devices in local network

TIL arp -a discovers and lists devices in local network. Could be helpful if network has not too many devices connected.

arp -a
? (192.168.99.80) at dc:4a:3e:7d:dc:e8 [ether] on wlp5s0
? (192.168.99.101) at f2:b8:bb:a6:12:02 [ether] on wlp5s0
? (192.168.99.206) at f0:d5:bf:2e:46:59 [ether] on wlp5s0
? (192.168.99.49) at 7e:b9:e5:d7:ea:d2 [ether] on wlp5s0
? (192.168.99.248) at c0:b8:83:a5:bb:9e [ether] on wlp5s0
work.local (192.168.99.115) at b4:2e:99:93:c1:ac [ether] on wlp5s0

TIL nmap could be more helpful.

nmap 192.168.99.0/24
Starting Nmap 7.80 ( https://nmap.org ) at 2023-07-27 19:23 EET
Nmap scan report for routerdr.lan (192.168.99.1)
Host is up (0.0012s latency).
Not shown: 995 closed ports
PORT     STATE SERVICE
53/tcp   open  domain
80/tcp   open  http
1723/tcp open  pptp
2000/tcp open  cisco-sccp
8291/tcp open  unknown

Nmap scan report for 192.168.99.14
Host is up (0.0028s latency).
Not shown: 997 closed ports
PORT     STATE SERVICE
80/tcp   open  http
443/tcp  open  https
9000/tcp open  cslistener

Nmap scan report for 192.168.99.49
Host is up (0.0045s latency).
All 1000 scanned ports on 192.168.99.49 are closed

Nmap scan report for 192.168.99.80
Host is up (0.0018s latency).
Not shown: 990 closed ports
PORT     STATE SERVICE
80/tcp   open  http
222/tcp  open  rsh-spx
443/tcp  open  https
1935/tcp open  rtmp
3000/tcp open  ppp
5000/tcp open  upnp
7070/tcp open  realserver
8080/tcp open  http-proxy
8443/tcp open  https-alt
9080/tcp open  glrpc

Nmap scan report for ThinkPad (192.168.99.119)
Host is up (0.000092s latency).
All 1000 scanned ports on VV-ThinkPad-E490 (192.168.99.119) are closed

Nmap done: 256 IP addresses (5 hosts up) scanned in 32.47 seconds


Wednesday, July 26, 23: TIL Dunder methods in Python

TIL how to create symlinks.

TIL what git commit hash depend on.

TIL What’s the Meaning of Single and Double Underscores In Python?. Dunder methods (short for Double Underscore methods) - that’s funny. Dunder/Magic Methods in Python.

Form above learned what is wildcard import - from module import *. Now I have a question how is it different from import module.



Tuesday, July 25, 23: TIL what is OpenMP

TIL Ctrl-R trick of using history in Linux How to use the history command in Linux. history -d <line number> removes a line from history and history -c clears history. !sudo searches in history last command starting from “sudo” and reruns it, while !sudo:p just displays found command without running it. !?echo searching and runs last command having substring “echo”.

TIL what is OpenMP.

OpenMP (Open Multi-Processing) is an application programming interface (API) that supports multi-platform shared-memory multiprocessing programming in C, C++, and Fortran, on many platforms, instruction-set architectures and operating systems, including Solaris, AIX, FreeBSD, HP-UX, Linux, macOS, and Windows. It consists of a set of compiler directives, library routines, and environment variables that influence run-time behavior.

TIL what is Proportional control in engineering and process control. Not really learned. Every engineer intuitively understands and uses proportional control not knowing how it’s called.

Proportional control is a type of linear feedback control system in which a correction is applied to the controlled variable, and the size of the correction is proportional to the difference between the desired value (setpoint, SP) and the measured value (process variable, PV).

Read How to Make Sense of Distributed Processing With Python Daemons.



Monday, July 24, 23: TIL MAVLink drone movements commands

TIL how to use abstract classes in Python.

TIL pass statement in Python. It’s NOP in Python.

Dug in drone movements commands.



Sunday, July 23, 23: Bookmarking TextPaths

Bookmarking TextPaths which I am going to use to generate vector for some alphabet to swift-geometrize feature to produce art similar to James Cook The Type Writer Artist.



Saturday, July 22, 23: Dug with MavLink whole day

Read A Review of Open-Source Flight Control Systems.

Watched 04 Pymavlink Movement.

MAVLink Messages | Dissecting the Protocol.



Friday, July 21, 23: TIL argparse Python module

TIL argparse Python module.



Thursday, July 20, 23: TIL simple-pid Python library; TIL what for is ~/.local folder

TIL simple-pid Python library.

TIL what for is ~/.local folder on Ubuntu. If find some apps on macOS, e.g. Neovim, also use it.



Wednesday, July 19, 23: Read Telegram Bot API documentation

Read Marvin’s Marvellous Guide to All Things (Telegram Bot) Webhook.

Read Telegram Bot API.



Tuesday, July 18, 23: TIL MAVSDK is sh*t mostly capable of controlling simulated drones

Watched Controlling MAVLink Drones with MAVSDK.

Unfortunately, because of this issue Is there any tutorial explaining connecting to real done instead of SITL using mavsdk? it’s not usable in real life.

Bookmarking post Developing Telegram bot on Go and AWS Lambda. I should deploy two my Telegram bots to AWS Lambda instead of Digital Ocean.



Monday, July 17, 23: TIL how to download file with CLI on macOS; TIL Gezebo simulator doesn’t work on macOS; TIL how to launch Linux on macOS with new Vurtualization framework

TIL how to download file with CLI on macOS. I tried to download a video file hosted on github. wget got 404 while curl downloaded file successfully.

wget url-to-file
curl -o url-to-file

Watched How To Start a Mission Using Pymavlink.

Installed Gazebo Garden for macOS. Didn’t work on macOS for me. Ended up with openning issue Fail to start shapes.sdf on macOS after fresh install.

Read about ArduPilot’s Flight Modes.

Watched WWDC 2022 video Create macOS or Linux virtual machines. Same in form of article: Creating and Running a Linux Virtual Machine. Absolutly marvelouse sample code Running GUI Linux in a virtual machine on a Mac.

This sample code project demonstrates how to install and run GUI Linux virtual machines (VMs) on a Mac.

The Xcode project includes a single target, GUILinuxVirtualMachineSampleApp, which is a macOS app that installs a Linux distribution from an ISO image into a VM, and subsequently runs the installed Linux VM.

Ubuntu desktop image for ARM could be found here.

No Virtual desktop, no Parallels Desktop anymore!

No Virtual desktop, no Parallels Desktop anymore!.



Sunday, July 16, 23: Watched video 5” Freestyle FPV Drone Build

Watched video 2022 - 5” Freestyle FPV Drone Build. There’ra some useful tip on how to setup drone with Betaflight.



Friday, July 14, 23: Dug with MAVLink

Came accross pymavlink examples which containe snippets for common tasks like:

  • Autopilot connected to the computer via serial
  • Run pyMavlink on the surface computer
  • Run pyMavlink on the companion computer
  • Send Message to QGroundControl
  • Arm/Disarm the vehicle
  • Change flight mode
  • Send RC (Joystick)
  • Send Manual Control
  • Read all parameters
  • Read and write parameters
  • Receive data and filter by message type
  • Request message interval
  • Control Camera Gimbal
  • Set Servo PWM
  • Advanced Servo/Gripper Example
  • Set Target Depth/Attitude
  • Send GPS position
  • Send rangefinder/computer vision distance measurement to the autopilot

Watched PX4 and the art of Custom MAVLink Messages - Hamish Willee, Auterion.



Thursday, July 13, 23: TIL PWM (Pulse Width Modulation) works to control servos; TIL how to takeoff and move drone with MAVLink

Read how PWM (Pulse Width Modulation) works to control servos. Whole post is interesting. It explains topics like “How to select a servo motor for your application”.

Watched and fallowed video 03 Pymavlink Takeoff and 04 Pymavlink Movement.

Googling for SBUS have found a series How to Write your own Flight Controller Software. Marvelous! How to Write your own Flight Controller Software — Part 3 has quite interesting info about PID regulators.

Following image, explaining effect of changing PID coefficients I find useful: Effect of Changing PID Loop Gains: Kp, Ki and Kd

How to Write your own Flight Controller Software — Part 4 has good explanation about cascading PID loops as one possible approach of controlling multirotor.

Motor Mixing Algorithm

How to Write your own Flight Controller Software — Part 5.

In Part 5 of our series on writing your own flight controller software we will focus on the IMU and in particular explain the best ways to convert the gyro rate and accelerometer force data to a roll and pitch angle. The yaw angle is then calculated using the pitch and roll and magnetometer data.

It’s discussed building of IMU based on Arduino Nano 33 BLE.

How to Write your own Flight Controller Software — Part 6. It’s about LiPo Battery Monitoring using a scheduler.

How to Write your own Flight Controller Software — Part 7 which covers the Attitude and Heading Reference System (AHRS), IMU Filters and Sensor Fusion. We have released the open source ReefwingAHRS Arduino library to demonstrate these techniques on the Nano 33 BLE.

How to Write your own Flight Controller Software — Part 8 covers building A light weight Arduino implementation of the MultiWii Serial Protocol.

How to Write your own Flight Controller Software — Part 9 ESC Arming and an Introduction to BLDC Motors.

How to Write your own Flight Controller Software — Part 10 Understanding and Controlling Brushed DC Motors

How to Write your own Flight Controller Software — Part 11 Managing Brushless DC (BLDC) Motors

Looking ExpressLRS Configurator found something I didn’t know: how to launch app if macOS complains app cannot be opened because the developer cannot be identified - press Control keyboard key and [Open] button on error pane. Alternatively, following could be used: sudo xattr -rd com.apple.quarantine /Applications/ExpressLRS\ Configurator.app. Error pane should be closed before issuing command in terminal.



Wednesday, July 12, 23: TIL a lot about MAVLink; TIL what is Antenna Tracking

Browsed again Guide on MAVLink.

Hung on MAVLink CRC which refers to Brief tutorial on CRC computation in Linux documentation. Last refers to “High Octane CRC Generation with the Intel Slicing-by-8 Algorithm”. Message in a group refers to this implementation made public by Intel which gives 2.6 performance boost (according to message).

I have yet to go over all of MAVLink Microservices.

TIL what is Antenna Tracking.



Tuesday, July 11, 23: TIL swift-http-types package; TIL how to control drone servoes with MAVLink

TIL new swift package Swift HTTP Types which provides a shared set of currency types for client/server HTTP operations in Swift. It’s repo swift-http-types.

Watched Connecting Raspberry Pi w/ Pixhawk and Communicating via MAVLink Protocol. It shows shortly how to communicate with flight controller with MAVProxy. Following screenshot saved my day:

In my case command launching MAVProxy was ~/mavlink/bin/mavproxy.py --master=/dev/ttyACM0 --baudrate 57600 --aircraft MyDrone. Later I found out that all parameters could be omitted and MAVProxy launches fine without parameters.

TIL git has its own GUI which could be called with git gui.

Watched 02 Pymavlink Arm Command.

Read section Command Protocol of MAVLink documentation.

TIL how to control servos with MAVLink.



Monday, July 10, 23: TIL a lot about MAVLink and ArduPilot

Watched 01 Pymavlink Connect by Intelligent Quads.

From video learned how to launch VS Code in command line with code .. It needed additional setup for macOS.

Followed Connecting PixHawk to Raspberry Pi and NVIDIA Jetson. But actually I could just connect USB-USB - in may case both have USB, USB-C on PixHawk and USB-A on Jetson carrier board.

Passed through Python Virtual Environments: A Primer.

TIL lsusb cli for Linux which I installed on mac with brew as well.

MavLink Tutorial for Absolute Dummies (Part –I).

TIL that APM in context of drones stands for ArduPilot Mega

Ardupilot Mega (APM) is a professional quality IMU autopilot that is based on the Arduino Mega platform. This autopilot can control fixed-wing aircraft, multi-rotor helicopters, as well as traditional helicopters.

TIL APM Planner 2 which works on macOS and Linux, contrary to ArduPilot Mission Planer.

TIL ArduPilot’s documentation is quite good.

Documentation on MAVLink Interface

ArduPilot has a section “Companion Computers” which lists different hardware and software for companion computers. This worth looking and bookmarking Maverick. As well as rpanion-server. It has several promising looking features like configurations over WiFi and Ethernet, Flight Controller telemetry forwarding, Telemetry log management and so on.

Bookmarking amazing video of a drone Flying Fast through Tight Passages and Avoiding Moving Obstacles. Here’s companion repo aerial_navigation_development_environment.

Bookmaking building instructions DRONE WITH APM (EASIEST WAY).

Watched VSCode SSH setup (and remote Python interpreter).



Friday, July 07, 23: TIL AT Protocol; TIL how to simulate robots in Webots

TIL The AT Protocol. It has dedicated Protocol website.

The “AT Protocol” is a new federated social network. It integrates ideas from the latest decentralized technologies into a simple, fast, and open network.

What’s a “federated” network? It’s a way for servers to communicate with each other — like email. Instead of one site running the network, you can have many sites. It means you get a choice of provider, and individuals and businesses can self-host if they want.

TIL Big Rocks strategy.

Watched Bitcraze Dev meeting July 2023 about simulating Crazyflie in Webots.

Dug in Coco dataset a bit. It has very nice interface for explore mode. Would be nice to create something similar for my Ukrainian traffic signs dataset.

Browsed all documentation for Webots.

Read interesting post Aibo and Webots: Simulation, wireless remote control and controller transfer.

Watched Installation and Introduction to Webots &vert; Make your first custom world in minutes from playlist Webots Crash Course.

It took me a while to find how do I launch Guided Tour on Mac. It took me a while to find how do I launch Guided Tour on Mac



Thursday, July 06, 23: TIL how to mount on a mac a folder on remote machine using sshfs

TIL how to mount on a mac a folder from remote machine:

sudo sshfs -o 'allow_other,gid=NNN,uid=MMM' user-on-remote@remotehost:/folder /mountpoint/folder

TIL id CLI command which among others prints numeric values for user id (UID) and group id (GID). I needed these for sshfs.

Mount point for sshfs should be preliminary created as:

sudo mkdir -p /mount/point
sudo chown -R $USER:staff /mount/point/

I don’t get why chown is needed. For me it didn’t change any rights.

I don’t know if sshfs needs any fuse software for its use. I installed previously extFS from Paragon to be able to read flashcards formatted for Linux.

It’s interesting that extFS from Paragon is the only software for mac to read/write Linux volumes which I was able to make work. And it costed me 39.95$. It’s might be viable idea to make an app for this. It’s about implementing linux FUSE interface. Mounting volumes from cloud services like Google Cloud or S3 bucket - another application where FUSE could be used. CloudMounter works this way.

TIL what FUSE stands for in macFuse, fuseFS and so on. FUSE stands for Filesystem in Userspace which originates in Linux. How to mount and manage non-native file systems in OS X with FUSE.

Useful link on topic The reference implementation of the Linux FUSE (Filesystem in Userspace) interface.



Wednesday, July 05, 23: TIL characteristics for LiPo batteries for FPV drones

Bookmarking Everything about LiPo batteries for FPV drones.



Tuesday, July 04, 23: TIL GitHub Projects; How to copy files to S3 bucket with CLI; URLSessionConfiguration’s waitsForConnectivity property

TIL GitHub Projects.

TIL how to copy files to s3 bucket with cli: aws s3 cp /path/to/file s3://bucket-name.

TIL that URLSessionConfiguration has property waitsForConnectivity. By default, the system will wait seven days to see if internet connectivity becomes available, but it can be controlled with the timeoutIntervalForResource property on configuration.



Monday, July 03, 23: TIL how to use Albumentations

TIL how to use Albumentations.



Sunday, July 02, 23: TIL protocols used in radio control

Bookmarking quick list/explanation of different protocols used in radio control (russian).



Saturday, July 01, 23: TIL MAVLink capabilities; ArduPilot’s Mission Planner capabilities

Read MAVLink Interface documentation trying to understand what is it and how it could be used.

TIL Mission Planner. Waypoints and events of mission are set with MAVLink commands. Cool stuff. Why havn’t I played with it earlier with my Phantoms doing missions to automatically run photo/video recording sessions? Cool that mission even could be extended with running any python code.

TIL what is orthophoto, orthophotograph, orthoimage or orthoimagery - it is an aerial photograph or satellite imagery geometrically corrected (“orthorectified”) such that the scale is uniform: the photo or image follows a given map projection.

TIL about ByteTrack.



Friday, June 30, 23: TIL how to bind ExpressLRS remote control with drone

TIL difference between plane propellers and drone propellers. Drones have clockwise and counterclockwise propellers. You can use a multirotor prop on an airplane as long as it is rotating the right way, and visa versa.

TIL how to bind ExpressLRS remote control.



Thursday, June 29, 23: TIL about Webots capabilities; Dug in Core Graphics documentation

Read Webots (open-source three-dimensional mobile robot simulator) User Guide.

Webots is a professional mobile robot simulation software package. It offers a rapid prototyping environment, that allows the user to create 3D virtual worlds with physics properties such as mass, joints, friction coefficients, etc. The user can add simple passive objects or active objects called mobile robots. These robots can have different locomotion schemes (wheeled robots, legged robots, or flying robots). Moreover, they may be equipped with a number of sensor and actuator devices, such as distance sensors, drive wheels, cameras, motors, touch sensors, emitters, receivers, etc. Finally, the user can program each robot individually to exhibit the desired behavior.

This bug in WeScan gets me dipper and dipper. This code for rotating UIImage which I was intended to use has a bug which I am struggling to find. Something important related to affine transform and user/device coordinate systems slippers from my mind.

New Core Graphics reference documentation starts nicely, but later refers to looking old but still useful Quartz 2D Programming Guide.

Coordinate Systems and Transforms.

Completely missed following.

Getting the User to Device Space Transform

Typically when you draw with Quartz 2D, you work only in user space. Quartz takes care of transforming between user and device space for you. If your application needs to obtain the affine transform that Quartz uses to convert between user and device space, you can call the function CGContextGetUserSpaceToDeviceSpaceTransform.

Quartz provides a number of convenience functions to transform the following geometries between user space and device space. You might find these functions easier to use than applying the affine transform returned from the function CGContextGetUserSpaceToDeviceSpaceTransform.

  • Points. The functions CGContextConvertPointToDeviceSpace and CGContextConvertPointToUserSpace transform a CGPoint data type from one space to the other.
  • Sizes. The functions CGContextConvertSizeToDeviceSpace and CGContextConvertSizeToUserSpace transform a CGSize data type from one space to the other.
  • Rectangles. The functions CGContextConvertRectToDeviceSpace and CGContextConvertRectToUserSpace transform a CGRect data type from one space to the other.

Read Coordinate Transforms in iOS using Swift, Part 0: The Problems. Coordinate Transforms in iOS using Swift, Part 1: The L Triangle. But now. Instead of explaining and making things simpler it brings new staff to the table and make more complex.

Bookmarking usage of exiftool CLI for removing all exifs from a file: exiftool -all= path_to_files. Space after = is important! Original photos are saved in file with extension like .jpeg_original.



Wednesday, June 28, 23: TIL software for simulating robots

TIL a bit about Real-Time Transport Protocol (often referred to as RTP streaming) and Real-Time Streaming Protocol (RTSP).

TIL about remote desktop NoMachine. Will not use it as it installs on macOS startup items which I don’t like.

TIL ssh-copy-id. I used to copy ~/.ssh/id_rsa.pub manually from machine to machine. it founds out that I should have copied key to ~/.ssh/authorized_keys, not to ~/.ssh/.

Read A Survey on Open-Source Simulation Platforms for Multi-Copter UAV Swarms.

Downloaded and installed the first one, Webots. It could be launched as CLI /Applications/Webots.app/Contents/MacOS/webots --help.



Tuesday, June 27, 23: TIL mktmp cli for making temporary files/directories in Linux

TIL mktmp cli for making temporary files/directories in Linux.



Monday, June 26, 23: TIL FIFTYONE utility for building/browsing datasets for computer vision models

Bookmarking What are the URL tricks to save YouTube offline.

TIL FIFTYONE - open-source tool for building high-quality datasets and computer vision models. Repo. Failed to install it on mac so far.

TIL how to extract directory, filename and extension in bash: ```bash [[ $path =~ ^(.{1,2}|./.{0,2})$|^(./)([^/]+)(.[^/])$|^(./)(.+)$|^(.+)(..*)$|^(.+)$ ]] dirpath=${BASH_REMATCH[1]}${BASH_REMATCH[2]}${BASH_REMATCH[5]} filename=${BASH_REMATCH[3]}${BASH_REMATCH[6]}${BASH_REMATCH[7]}${BASH_REMATCH[9]} filext=${BASH_REMATCH[4]}${BASH_REMATCH[8]}



Friday, June 23, 23: TIL how to rotate UIImage properly

TIL iOS 17 introduces new initializer for UIImage init(resource: ImageResource). ImageResource is opaque structure having initializer init(name: String, bundle: Bundle).

Last several days I have been working on issue in WeScan. This is kind of bug which is eaiser to fix then to test. After spending several days with playing with UIImage rotation, I’ve created repo Understand UIImage rotation.

From WeScan TIL about Measurement. I didn’t know this is possible: let finalImage = rotated(by: Measurement(value: imageAngle, unit: .radians)) { ... }.



Monday, June 19, 23: TIL how to use ffmpeg for reducing video size

TIL again ffmpeg for reducing mp4 video size. I need this to upload screen recording to issue for WeScan on GitHub.

ffmpeg -i input.mp4 -vcodec h264 -acodec aac output.mp4


Sunday, June 18, 23: TIL AWS allows to add your own code to S3 GET requests

TIL AWS allows to add your own code to S3 GET requests to modify and process data as it is returned to an application. Filter rows, resize images dynamically, redact confidential data, and more.



Thursday, June 15, 23: TIL how to make webpage with Vapor

Read Vapor documentation, post File upload using Vapor 4, book Practical Server Side Swift to make a web page for geometrizing images which shares server and code with Telegram bot Geometrizebot.

I am going change the page using AJAX with help of AJAX calls using Vapor 4.



Tuesday, June 13, 23: Watched WWDC 2023 session video Debug with structured logging and Discover machine learning enhancements in Create ML

Watched WWDC 2023 session video Debug with structured logging.

Watched WWDC 2023 session video Discover machine learning enhancements in Create ML.



Monday, June 12, 23: Watched WWDC23 Platforms State of the Union

Watched Platforms State of the Union.



Thursday, June 08, 23: TIL Double Protocol Conformance could be a problem in Swift

TIL Double Protocol Conformance could be problematic in Swift. Different target could implement conformance differently and Xcode some time doesn’t even warn.



Thursday, June 08, 23: Read Rules of Thumb for Software Development Estimations

Read Rules of Thumb for Software Development Estimations.

Ah, software estimation - the bane of many developers’ existence and the scourge of project managers everywhere. A constant battle of “tell me how much it’s going to take you” and “give me a clear description of the task first.”

😂



Wednesday, June 07, 23: Passed Getting Started With Vapor 4 tutorial

Passed Getting Started With Vapor 4 - Learn By Building a Todo Application.



Friday, June 02, 23: TIL what’s AWS S3 bucket policy to allow public read access to all objects in bucket looks like; TIL double click on brace/bracket in Xcode jumps to opposite one and selects block

TIL what’s AWS S3 bucket policy to allow public read access to all objects in bucket looks like:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": "*",
      "Action": [
        "s3:GetObject"
      ],
      "Resource": "arn:aws:s3:::YOUR_BUCKET_NAME/*"
    }
  ]
}

Screen recording of Xcode showing how double click on brace/bracket works



Wednesday, May 31, 23: TIL capitalization matters in URLs

TIL capitalization matters in URLs.



Monday, May 29, 23: TIL difference between Sequence, AsyncSequence, and AsyncStream

Read Hacking with Swift’s What’s the difference between Sequence, AsyncSequence, and AsyncStream?.

Read Swift by Sudlell’s Async sequences, streams, and Combine.

TIL the difference between prefixes and folders in S3: Organizing objects using prefixes, For Amazon S3 request rates, what’s the difference between prefixes and nested folders? How many prefixes can I have in an S3 bucket?, Organizing objects in the Amazon S3 console by using folders.



Sunday, May 28, 23: Watched WWDC 21 session video Meet AsyncSequence

Watched WWDC 21 session video Meet AsyncSequence.



Friday, May 26, 23: TIL how to use URLSession on Linux

Working on geometrizebot Telegam bot learned URLSession is not available on Linux. From URLSession Concurrency on Linux learned that FoundationNetworking module provides implementation of URLSession for Linux and implementation of URLSession differs a bit in Apple platforms and Linux.



Wednesday, May 24, 23: TIL Swift Package Manager treats dependencies based on branch as unstable

Trying to build telegram bot for geometrizing images using my swift package swift-geometrize as dependency I came across error:

error: Dependencies could not be resolved because root depends on 'swift-geometrize' 0.0.0..<1.0.0.
'swift-geometrize' cannot be used because no versions of 'swift-geometrize' match the requirement {0.0.0..<0.9.0, 0.9.1..<1.0.0} and package 'swift-geometrize' is required using a stable-version but 'swift-geometrize' depends on an unstable-version package 'jpeg'.

From this I have learned that Swift Package manager treats dependencies based on branch unstable version because branch means variable version.

TIL Getting started with AWS SDK for Swift.



Monday, May 22, 23: TIL Swift 5.7 have added functions trimPrefix and trimmingPrefix

TIL Swift 5.7 have added functions trimPrefix and trimmingPrefix to collections and sequences. Documentation is incorrect so I have fixed it.



Friday, May 19, 23: Watched iOS Architect Crash Course Lecture #3 - The fastest and simplest way to become a complete Senior iOS Developer

Watched Lecture #3 - The fastest and simplest way to become a complete Senior iOS Developer of iOS Architect Crash Course.



Thursday, May 18, 23: TIL using tmux

From A beginner’s guide to tmux TIL tmux is a terminal multiplexer.

  • tmux ls lists active tmux sessions
  • tmux attach -t 0 attaches to session 0
  • Ctrl+B D — Detach from the current session.
  • Ctrl+B % — Split the window into two panes horizontally.
  • Ctrl+B “ — Split the window into two panes vertically.
  • Ctrl+B Arrow Key (Left, Right, Up, Down) — Move between panes.
  • Ctrl+B X — Close pane.
  • Ctrl+B C — Create a new window.
  • Ctrl+B N or P — Move to the next or previous window.
  • Ctrl+B 0 (1,2…) — Move to a specific window by number.
  • Ctrl+B : — Enter the command line to type commands. Tab completion is available.
  • Ctrl+B ? — View all keybindings. Press Q to exit.
  • Ctrl+B W — Open a panel to navigate across windows in multiple sessions.
  • Ctrl+B [ - Turns on scrolling in windows, Q exits scrolling.


Wednesday, May 17, 23: Watched iOS Architect Crash Course Lecture #2 - What every Senior iOS Dev should know Principles & Patterns Applied

Watched Lecture #2 - What every Senior iOS Dev should know Principles & Patterns Applied of iOS Architect Crash Course.



Tuesday, May 16, 23: TIL what is Hardened Runtime and watched bonus Threading Operations and Queues of iOS Architect Crash Course

TIL what is Hardened Runtime.

Watched bonus Threading Operations and Queues of iOS Architect Crash Course.

TIL github somehow makes impossible mp4 files committed to repo be to played. So I have had to find a place to host media files. It would selfhosting on own server or on Digital Ocean Spaces or in AWS S3 bucket.

TIL S3 would be quite inexpensive alternative to storing files online. I have found out that one my S3 bucket exists since 2018 and I pay nothing for it for last years as data is not accessed. S3 pricing model could be chip for rarely accessed data in comparison to Digital Ocean 5$ per Space per month minimal price.



Monday, May 15, 23: Watched iOS Architect Crash Course Lecture #1 - Common mistakes preventing iOS devs from becoming true seniors of iOS Architect Crash Course

Watched Lecture #1 - Common mistakes preventing iOS devs from becoming true seniors of iOS Architect Crash Course.



Friday, May 12, 23: Read Telegram’s Bots: An introduction for developers

Read Telegram’s Bots: An introduction for developers.

TIL that Swift package Manager needs 4GB RAM to compile medium project like example project in telegram-vapor-bot.

Filed an issue to Swift Package manager swift build fails with error error: emit-module command failed due to signal 9 on Ubuntu 22.10 x64. Guys in comment there write that it’s not a problem of Swift Package Manager but of compiler/linker.

Launched the first Telegram bot today, written in Swift and hosted in droplet in Digital Ocean.



Monday, May 08, 23: Watched Stanford’s CS193P Spring 2021 Lecture 4: Memorize Game Logic and 5 SwiftUI Concepts Every Beginning SwiftUI Developer Needs To Know

Watched Stanford’s CS193P Spring 2021 Lecture 4: Memorize Game Logic.

Watched 5 SwiftUI Concepts Every Beginning SwiftUI Developer Needs To Know (2020).

TIL Editor in Xcode allows copy Qualified Symbol Name. Here is how copied qualified symbol name looks like: ContentView.getter:body. Screenshot of Xcode showing contextual menu with Copy Qualified Symbol Name item.

TIL there’s a thing in Xcode called Code Actions. If code is selected, code action for it could be called with CMD-Shift-A or with CMD-Shift-Click on a Symbol. Screenshot from Youtube video 5 SwiftUI Concepts Every Beginning SwiftUI Developer Needs To Know (2020) showing Code Actions in Xcode.



Sunday, May 07, 23: Watched Stanford’s CS193P Spring 2021 Lecture 2: Learning more about SwiftUI and Lecture 3: MVVM and the Swift type system

Watched Stanford’s CS193P Spring 2021 Lecture 2: Learning more about SwiftUI and Lecture 3: MVVM and the Swift type system. I like it! Once per several years I watch these couse updated and every time I enjoy it.



Saturday, May 06, 23: Watched Stanford’s CS193P Spring 2021 Lecture 1: Getting started with SwiftUI

Watched Stanford’s CS193P Spring 2021 Lecture 1: Getting started with SwiftUI.

Looked for View protocol declaration. Interesting notation View/body-swift.property, View/opacity(_:). Have never seen this.

/// A type that represents part of your app's user interface and provides
/// modifiers that you use to configure views.
///
/// You create custom views by declaring types that conform to the `View`
/// protocol. Implement the required ``View/body-swift.property`` computed
/// property to provide the content for your custom view.
///
///     struct MyView: View {
///         var body: some View {
///             Text("Hello, World!")
///         }
///     }
///
/// Assemble the view's body by combining one or more of the built-in views
/// provided by SwiftUI, like the ``Text`` instance in the example above, plus
/// other custom views that you define, into a hierarchy of views. For more
/// information about creating custom views, see <doc:Declaring-a-Custom-View>.
///
/// The `View` protocol provides a set of modifiers — protocol
/// methods with default implementations — that you use to configure
/// views in the layout of your app. Modifiers work by wrapping the
/// view instance on which you call them in another view with the specified
/// characteristics, as described in <doc:Configuring-Views>.
/// For example, adding the ``View/opacity(_:)`` modifier to a
/// text view returns a new view with some amount of transparency:
///
///     Text("Hello, World!")
///         .opacity(0.5) // Display partially transparent text.
///
/// The complete list of default modifiers provides a large set of controls
/// for managing views.
/// For example, you can fine tune <doc:View-Layout>,
/// add <doc:View-Accessibility> information,
/// and respond to <doc:View-Input-and-Events>.
/// You can also collect groups of default modifiers into new,
/// custom view modifiers for easy reuse.
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol View {

    /// The type of view representing the body of this view.
    ///
    /// When you create a custom view, Swift infers this type from your
    /// implementation of the required ``View/body-swift.property`` property.
    associatedtype Body : View

    /// The content and behavior of the view.
    ///
    /// When you implement a custom view, you must implement a computed
    /// `body` property to provide the content for your view. Return a view
    /// that's composed of built-in views that SwiftUI provides, plus other
    /// composite views that you've already defined:
    ///
    ///     struct MyView: View {
    ///         var body: some View {
    ///             Text("Hello, World!")
    ///         }
    ///     }
    ///
    /// For more information about composing views and a view hierarchy,
    /// see <doc:Declaring-a-Custom-View>.
    @ViewBuilder @MainActor var body: Self.Body { get }
}


Friday, May 05, 23: Watched How to create a Generic Networking Layer in iOS apps

Watched How to create a Generic Networking Layer in iOS apps - iOS Dev Live Mentoring.

Run at Brilliant Algorithms and Data Structures. Big O.. I like how material is presented.



Thursday, April 27, 23: Dag in swift-foundation

Dug in swift-foundation repo. Interesting, that Data.swift is using mapping of files into memory.



Wednesday, April 26, 23: Watched WWDC 2021 session video Meet async/await in Swift

Watched WWDC 2021 session video Meet async/await in Swift.

Whaaaaat? UIImage has async method prepareThumbnail(of:completionHandler:). How could I miss that!?



Tuesday, April 25, 23: TIL utf8everywhere.org

TIL utf8everywhere.org.

In particular, we believe that the very popular UTF-16 encoding (often mistakenly referred to as ‘widechar’ or simply ‘Unicode’ in the Windows world) has no place in library APIs except for specialized text processing libraries, e.g. ICU.

Nothing new or interesting. Thanks God, NSString in Objective-C and String in Swift are extremely good designed pieces of software.

Read, probably, not the first time, The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!). Hm, this page is 20 years old.

Finally, I’ve got Hackers Delight book by Henry Warren. A lot of interesting stuff! Hope will use it occasionally.



Thursday, April 20, 23: TIL how to connect to droplets in DigitalOcean with SSH

Bookmarking swift-markdown-ui.

TIL How to Connect to Droplets in DigitalOcean with SSH.



Wednesday, April 19, 23: TIL Swift Power Asserts; Punycode

Read Automating Swift command line tool releases with GitHub Actions. Good tutorial to automate Homebrew releases.

TIL what is Punycode.

TIL Swift Power Asserts (also known as diagrammed assertions). It allows asserts like:

#expect(max(a, b) == c)
        |   |  |  |  |
        7   4  7  |  12
                  false

Registered at buymeacoffee.com. Now you can buy me coffee if you wish.

Buy Me A Coffee



Tuesday, April 18, 23: Read AI-deck Documentation and Examples Update

Read AI-deck Documentation and Examples Update.



Wednesday, April 12, 23: TIL how to create private fork of public repo on GitHub

TIL how to create private fork of public repo on GitHub Importing.



Tuesday, April 11, 23: TIL how to make static parking page for website with DigitalOcean Functions or with DigitalOcean’s static website App

Read Why open source. I feel I will need it.

Decided to setup temporary static parking page with DigitalOcean. DO’s documentation mentions only API creation. It took some time to guess what function returning HTML should be. Below it’s. DO gives URL for this function. Private domain could be forwarded to this URL. HTML for this parking page is generated with ChatGPT, by the way.

def main(args):
    html = """
        <!DOCTYPE html>
        <html>
            <head>
                <title>Coming Soon</title>
                <style>
                    html, body {
                        height: 100%;
                        margin: 0;
                        padding: 0;
                    }
                    body {
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    }
                </style>
            </head>
            <body>
                <h1>Coming soon...</h1>
            </body>
        </html>
    """
    return {"body": html}

Setting up parking found out that redirect for https isn’t so easy to setup, it’s impossible to set it up on DNS level. HTTP REDIRECTS WITH DNS, AND WHY HTTPS REDIRECTS ARE SO &!$%-ING HARD. Finally I had to move my domain to DNS of DO. That it become easy to setup domain for App for static website.



Saturday, April 08, 23: TIL how to make several blank lines in markdown

TIL how to make several blank lines in markdown. Following will create three blank lines.

&nbsp;<br>
&nbsp;<br>
&nbsp;<br>


Friday, April 07, 23: TIL how to make Swift on Windows for after Swift or Visuyal Studio update

Swift on Windows is bizarre. Updated Swift to 5.8 and Swift Package Manager stopped to work. I have openned issue.

Documentation at https://www.swift.org/getting-started/ has paragraph how to repair:

Repairing after Visual Studio Updates If Visual Studio is updated, you may have to repair the installation. See Microsoft’s instructions for repairing installed programs.

It’s not clear exactly what has to be “repaired” and how.

Here are the steps.

  • Launch Control Panel.
  • In Control Panel launch Programs and Features.
  • In Programs and Features find Swift Developer Package for Windows x86_64.
  • Right click on Swift Developer Package for Windows x86_64 and click Change in contectual menu.
  • In launched installer click Repair and follow instructions.

Знімок екрана 2023-04-07 100939

After these steps swift build builds package normally.

Bookmarking repo for IceCubesApp iOS app, it’s iOS client for Mastodon. It’s quite big production app build with SwiftUI.

Bookmarking Building Large-Scale Apps with SwiftUI: A Guide to Modular Architecture.



Wednesday, April 05, 23: TIL how make Swift command line interactive

TIL how to make an interactive picker for a Swift command-line tool. The package clack-swift for this is still work in progress.

TIL Windows still has to be kind of hacked to accept ANSI sequences: Windows console with ANSI colors handling. I haven’t been editing Widnows Registry for at least 20 years.



Tuesday, April 04, 23: TIL ChatGPT could give better results than organic search results

Reading The Cassowary Linear Arithmetic Constraint Solving Algorithm I was puzzled why Cassowary Algorithm is called such. So I googled for it. For the first time ChatGPT has given better result then organic search: Search results screenshot



Friday, March 31, 23: TIL what’s new in Swift 5.8

TIL @backDeployed attribute was introduced in Swift 5.8.

From its swift evolution proposal, I’ve got what exactly @_alwaysEmitIntoClient attribute means (official documentation for it is a bit obscure):

While @_alwaysEmitIntoClient can be used to back deploy APIs, there are some drawbacks to using it. Since a copy of the function is always emitted, there is code size overhead for every client even if the client’s deployment target is new enough that the library API would always be available at runtime. Additionally, if the implementation of the API were to change in order to improve performance, fix a bug, or close a security hole then the client would need to be recompiled against a new SDK before users benefit from those changes.

TIL about Clock protocol introduced yet in Swift 5.7: Clock, Instant, and Duration. This is cool:

let clock = ContinuousClock()

let time = clock.measure {
    // complex work here
}

print("Took \(time.components.seconds) seconds")

TIL Swift 5.8 changes Buffer API again: Pointer Family Initialization Improvements and Better Buffer Slices. I find Swift’s API for buffers manipulation verbose, difficult to remember, being changed too frequently and slow. And this change doesn’t improve these much.

From Swift evolution proposal Enable multi-statement closure parameter/result type inference I’ve got why closure parameter and return value inference is so fragile in Swift prior to 5.8. Will see what changed in 5.8.

Multi-statement closures, unlike their single-statement counterparts, currently cannot propagate information, e.g. parameter and result types from their body, back to the enclosing context, because they are type-checked separately from the expression containing the closure. Information in such closures flows strictly in one direction - from the enclosing context into the body, and statement by statement from the top to the bottom of the closure.

TIL Swift implemented multiple trailing closure syntax: Multiple Trailing Closures. It will be released in Swift 6.



Sunday, March 26, 23: TIL dig +short ns example.com and how to manage DNS with DigitalOcean

TIL how to check name servers set for domain: dig +short ns example.com.

TIL how to manage DNS with DigitalOcean How to Create, Edit, and Delete DNS Records.



Friday, March 24, 23: TIL jq

From GitHub’s We updated our RSA SSH host key TIL about jq - commandline JSON processor.

``` jq can transform JSON in various ways, by selecting, iterating, reducing and otherwise mangling JSON documents. For instance, running the command jq ´map(.price) | add´ will take an array of JSON objects as input and return the sum of their “price” fields.

Hung a bit in Apple Swift issue #55222 SIMD generates bad code for string processing use-cases looking on Godbolt for generated code. It’s really looks bad. Would be interesting for experimenting if this code is faster then no-SIMD code.



Tuesday, March 21, 23: Tinkered with Swift code with simultaneous accesses to mutable struct

Came accross this tweet. I was sure code from tweet (below) will print all but 3 elements of array:

var array = [3, 2, 1]
array.removeAll(where: { $0 == array.count })
print(array) // I expected "[2, 1] to be printed

I was sure that array.count will be copied by value into closure passed into removeAll(where:) and removeAll will filter out 3 value from array. I was wrong. Code crashes in runtime because of not exclusive access to array. The error:

Simultaneous accesses to 0x107cf0090, but modification requires exclusive access.
Previous access (a modification) started at (0x107cec44c).
Current access (a read) started at:
...

So run removeAll starts modification. And then capturing of array.count attempt to run read when modification is running and fails. To make code work as I described earlier it’s sufficient to capture whole array in closure:

var array = [3,2,1]
array.removeAll(where: { [array] in $0 == array.count })
print(array) // prints [2, 1]

Or better capture explicitely only count:

var array = [3,2,1]
array.removeAll(where: { [count = array.count] in $0 == count })
print(array) // prints [2, 1]

While digging in stdlib jumped to read about underestimatedCount Inside the Standard Library: Sequence.map().

TIL where local config file for git is stored - it’s .git/config. I expected it be just .config because global config is ~/.gitconfig.



Tuesday, March 14, 23: TIL rethrows in Swift

Read again source of StringObject in Swift stdlib. No way I could use this anywhere soon.

Firstly came across rethrows in Swift in https://github.com/apple/swift/blob/main/stdlib/public/core/String.swift#L558.

Jumped to How to use the rethrows keyword in Hacking with Swift. I don’t know why I didn’t use it before.



Monday, March 13, 23: Read how to train YOLO5 in Google Colab

Bookmarking posts How I am making OCR (Russian) part 1, Part 2. Firstly, I like approach to building dataset. Second, post has steps how to train YOLO5 in Google Colab.



Saturday, March 11, 23: TIL modern iPhone still could be jailbroken

TIL modern iPhone still could be jailbroken: Jailbreak iOS 8 – iOS 16.4.



Friday, March 10, 23: Watched WWDC 2018 session video 237 Quick Look Previews from the Ground Up

Watched WWDC 2018 session video 237 Quick Look Previews from the Ground Up



Thursday, March 09, 23: TIL _Alignas in C and alignas in C++

TIL what is _Alignas in C and alignas in C++.



Sunday, March 05, 23: TIL cleanup attribute in GCC

TIL Using the __cleanup__ variable attribute in GCC. __cleanup__ allows you to define a function to be called when the variable goes out of scope (for example, before returning from a function).

Reread again Underscored Attributes Reference @_alwaysEmitIntoClient, while working on PR [stdlib] Add to Unsafe[Mutable]RawBufferPointer implementation of _custom[Last]IndexOfEquatableElement.

TIL how to change message in one of old commits: git rebase -i <commit_sha> , <commit_sha> is the sha of one commit before the commit to be changed. Then pick should be changed to reword for commit where message hould be changed. After save new dialog for editing commit message will be open.

Holy shit! Xcode shows column number of cursor in editor. I used to Xcode not showing column. Taday I googled for it to learn that it shows:

Xcode screenshot



Friday, March 03, 23: Overflow arithmetic vs saturating arithmetic vs regular arithmetic

Working on optimizing search for a byte in a buffer for [stdlib] Add to Unsafe[Mutable]RawBufferPointer implementation of _custom[Last]IndexOfEquatableElement return to blog post Finding Bytes in Arrays. Now I bookmark it here to save search time when I will need it next time.

Working on above mentioned PR I came across &+ and alike operations. I wrongly call these operations saturating operations (saturating arithmetic). Wiki: Saturation arithmetic. Saturation arithmetic clamps result to minimum and maximum values.

Typically, general-purpose microprocessors do not implement integer arithmetic operations using saturation arithmetic; instead, they use the easier-to-implement modular arithmetic, in which values exceeding the maximum value “wrap around” to the minimum value, like the hours on a clock passing from 12 to 1.

This is exactly what Swift implements - Overflow Operators.



Tuesday, February 28, 23: Watched WWDC 2014 video about Accelerate, read about Factory pattern in Swift

Read slides of WWDC 2014 session video703 Whats new in the Accelerate framework. There’s good example there how to copy string with simd.h.

Read 30,000 lines of SwiftUI in production later: We love it but you know there was going to be a “but”.

Read I am a bad software developer and this is my life.

Read Make it for me: Factory pattern and Swift. The post is intended to be used as a complete reference.



Saturday, February 25, 23: TIL Voxel, Polyhedron, 2.5D maps

TIL that Voxel is the same as Pixel, but for 3D. Voxel stands for volume element. Pixel - picture element.

TIL what is 2.5D maps - it’s 2D map where objects have hight.

TIL what is Polyhedron (plural polyhedra).



Friday, February 24, 23: TIL @_disfavoredOverload in Swift

What is @_disfavoredOverload in Swift?



Wednesday, February 22, 23: TIL copyleft-next

In news about next Linux release read Linux started to accept code licensed under copyleft-next license. Never heard of it before.

This comment in PR raised question if global variables in Swift are initialized lazily. Indeed. Googled for it: Swift global variables and static members are atomic and lazily computed.

Bookmaking How I have started conducting technical interviews in 30 minutes (Russian). Very good post about organizing technical interviews.



Tuesday, February 21, 23: Tinkered with SIMD operations in Swift

Working on PRs [string] SIMD-izes internal func in StringCreate.swift and on SIMD variant of PR [stdlib] Add to Unsafe[Mutable]RawBufferPointer implementation of _custom[Last]IndexOfEquatableElement explained in post I have found that Swift’s implementation of SIMD misses operations for checking if SIMD vector includes particular scalar. At the same time, simd implementation in Objective-C has simd_any and simd_all. These is poor documented in Apple documentation. These operations allow check not only presence of some scalar but allow use conditions like

if (simd_any(x < 0)) {
    // executed if any lane of x
    // contains a negative value.
}

if (simd_all(x == 0)) {
    // executed if every lane of x
    // contains zero.
 }

Implementing these operations in Swift would become reasonable Swift proposal extending proposal SIMD Vectors which introduced SIMD.

Proposal makes possible above mentioned operations only on two steps:

if (SIMD4<Int>(1,2,-3,4) .< 0) != SIMDMask<SIMD4<Int>>(repeating: false) {
    // executed if any lane of vector
    // contains a negative value.
    print("There's a lane with negative value.")
} else {
    print("All lanes have non-negative values.")
}

if (SIMD4<Int>(-1,-2,-3,-4) .< 0) == SIMDMask<SIMD4<Int>>(repeating: true) {
    // executed if every lane of vector
    // contains a negative value.
    print("All lanes have negative values.")
} else {
    print("There's a lane with non-negative value.")
}

May be it does make sense defining operations like ∀< for all and ∃< for any. Math symbol ∀ means ‘all’, and ∃ - ‘there exists’. These operations could be defined like:

infix operator <: ComparisonPrecedence // all
infix operator <: ComparisonPrecedence // any

extension SIMD where Scalar: Comparable {
    /// Returns a boolean if all lane contains value less then provided scalar.
    public static func <(vector: Self, scalar: Scalar) -> Bool {
        for index in vector.indices where !(vector[index] < scalar) {
            return false
        }
        return true

        /// Alternative implementation in terms of vector operations
        return (vector .< scalar) == SIMDMask(repeating: true)
    }

    /// Returns a boolean if any lane contains value less then provided scalar.
    public static func <(vector: Self, scalar: Scalar) -> Bool {
        for index in vector.indices where vector[index] < scalar {
            return true
        }
        return false

        /// Alternative implementation in terms of vector operations
        return (vector .< scalar) != SIMDMask(repeating: false)
    }
}

With such operations comparisons from snippets above become one step and much more readable:

if SIMD4<Int>(1,2,-3,4) < 0 {
    // executed if any lane of vector
    // contains a negative value.
    print("There's a lane with negative value.")
} else {
    print("All lanes have non-negative values.")
}

if SIMD4<Int>(-1,-2,-3,-4) < 0 {
    // executed if every lane of vector
    // contains a negative value.
    print("All lanes have negative values.")
} else {
    print("There's a lane with non-negative value.")
}

Fuuuuuuuuuck. SIMDVector.swift defines global functions any and all on SIMDMask argument which make possible what is needed. Why SIMD neither SIMD proposal nor any post/article I have read mentions these important functions!?

if all(SIMD4<Int>(-1,-2,-3,-4) .< 0) {
    // executed if any lane of vector
    // contains a negative value.
    print("There's a lane with negative value.")
}

if any(SIMD4<Int>(1,2,-3,4) .< 0) {
    // executed if any lane of vector
    // contains a negative value.
    print("There's a lane with negative value.")
}


Monday, February 20, 23: TIL CRDT

TIL about Conflict-free replicated data type. There’s Swift implementation CRDT.

Read how to add tag-based navigation to site on Jekyll: Adding and Displaying Tags on Jekyll Posts.

TIL difference between categories and tags in Jekyll.

Read Adding post tagging to jekyll’s Minima theme. Ended up copying a lot from this Jekyll install. But not yet tagging. Will finish tagging soon.

Since working on PR [stdlib] Add to Unsafe[Mutable]RawBufferPointer implementation of _custom[Last]IndexOfEquatableElement I am thinking that fix width integer types in Swift miss initializer repeating byte. It’s quite common operation in bit twiddling. And one has to write something like

let mask = UInt64(0x7f7f_7f7f_7f7f_7f7f)

or

var mask = UInt64(0)
withUnsafeMutableBytes(of: &mask) {
    _ = $0.initializeMemory(as: UInt8.self, repeating: 0x7f)
}

Both compile into one or two assembly instructions when optimization is tirned on. Latter is more condenced but likely to make mistake at quite long literal. Former is longer to write. Former works for any fixed width integer type and the only way to write generic code.

Would be so nice to have initiliser like let mask = UInt64(repeatingByte byte: 0x7f7f) for byte both UInt8 and Int8. This could be nice short Swift evolution proposal.



Saturday, February 18, 23: TIL Complementary Filter

TIL about dead reackoning and Complementary Filter from video Drone Control and the Complementary Filter.



Friday, February 17, 23: TIL Bitonic sorter

TIL Bitonic sorter. Came accross interesting implementation of bitonic sorting for Intel, offical from Intel and ARM A fast vectorized sorting implementation based on the ARM scalable vector extension (SVE), (A fast vectorized sorting implementation based on the ARM scalable vector extension (SVE))[https://arxiv.org/abs/2105.07782] (SVE is not supported by Apple silicon), Basic principles and bitonic sorting in official ARM’s Neon programmers’ guide. One time I will add these implementations to Swift.



Thursday, February 16, 23: Watched a bunch of lectures about Crazyflie

Watched Crazyflie AI-deck Workshop 1. For me worth watching since 28:00. Or better even since 40:00. Has interesting stuff like streaming images from AI-deck over WiFi. Repo for workshop - AI deck workshop.

As I get from the workshop, Crazyflie’s AI-deck is kind of clone of what is called PULP (Parallel Ultra Low Power). PULP datasheet.

Watched lecture Bitcraze - Crazyflie 101 EPFL-LIS lecture - part 1 (2020).



Wednesday, February 15, 23: TIL Crazyflie’s Stabilizer Module

Read Overview of Stabilizer Module of Crazyflie. Then State estimation.



Tuesday, February 14, 23: TIL GitHub Copilot

TIL JetBrains Sunsetting AppCode.

Today I have subscribed for GitHub Copilot. Installed CopilotForXcode plugin. Activated Copilot also for NVIM and Visual Studio Code. Latter looks quite nice. I will try to use it some time. As for NVIM, I worked with it’s maintainer, Justin some years ago. Since then I have NVIM installed but never really used it for something bigger then editing tiny config files.

Bookmarking Parsing responses on BLE-commands in Swift on example of GoPro(Russian).



Monday, February 13, 23: TIL SLAM

TIL SLAM - Simultaneous localization and mapping.



Friday, February 10, 23: TIL how to save money when using GitHub Actions for iOS CI/CD

Read Save money when using GitHub Actions for iOS CI/CD.



Thursday, February 09, 23: TIL Crazyflie 2.0: System Architecture

Read Crazyflie 2.0: System Architecture.

Watched Guest Lecture at EPFL Aerial Robotics Course 2021 (YouTube). Extreemly interesting!



Wednesday, February 08, 23: TIL Fletcher checksum, UART

TIL Fletcher checksum: rfc1146.

TIL what UART is Universal asynchronous receiver-transmitter:

A universal asynchronous receiver-transmitter is a computer hardware device for asynchronous serial communication in which the data format and transmission speeds are configurable. It sends data bits one by one, from the least significant to the most significant, framed by start and stop bits so that precise timing is handled by the communication channel. The electric signaling levels are handled by a driver circuit external to the UART. Two common signal levels are RS-232, a 12-volt system, and RS-485, a 5-volt system. Early teletypewriters used current loops.



Tuesday, February 07, 23: TIL git has global .gitignore file

TIL git could have global .gitignore file Setting up a global .gitignore` file



Monday, February 06, 23: TIL FreeRTOS

TIL FreeRTOS.



Saturday, February 04, 23: TIL Git scrapping

TIL about git scrapping: Git scraping: free hosting technic for not really static web sites.

TIL that [ETL means extract, transform, load (https://en.wikipedia.org/wiki/Extract,_transform,_load).



Friday, February 03, 23: Watched the first lecture of Princeton: Introduction to Robotics

Read Introduction to Embedding, Clustering, and Similarity. A close look at key elements of ML and Latent Spaces.

From How the AI industry profits from catastrophe learned about https://appen.com, huge company in data labelling business, they even have aticle in wiki.

Bookmarking Train YOLOv8 on Custom Dataset – A Complete Tutorial. Has link on quite interesting pothole dataset.

Bookmarking Introduction to Robotics course of Princeton University using Bitcaze’s Crazyflie. Watched the first lecture Lecture 1: Princeton: Introduction to Robotics.



Sunday, January 29, 23: TIL alloca

TIL alloca function in C to dynamically allocate memory on stack. Also learned it’s extremely unsafe and is discouraged to use.

alloca() is machine and compiler dependent; its use is discouraged.

alloca() is slightly unsafe because it cannot ensure that the pointer returned points to a valid and usable block of memory. The allocation made may exceed the bounds of the stack, or even go further into other objects in memory, and alloca() cannot determine such an error. Avoid alloca() with large unbounded allocations.

The use of C99 variable-length arrays and alloca() in the same function will cause the lifetime of alloca’s storage to be limited to the block containing the alloca().



Friday, January 27, 23: TIL lazygit

TIL lazygit. May be I will use it.



Wednesday, January 25, 23: TIL NULL is disfavored in C++ in sake of nullptr

TIL NULL is disfavored in C++ in sake of nullptr.



Tuesday, January 24, 23: TIL Stable Diffusion could be selfhosted

Bookmarking Short manual on Stable Diffusion (Russian).



Monday, January 23, 23: TIL why to use make with Swift package, how to gather code coverage without Xcode, new useful CLI tools

TIL how ease usage of swift package with make: Utilizing Makefiles for Swift projects.

TIL how to gather and display code coverage reports for Swift packages both for macOS and Linux without using Xcode at all: Code coverage for Swift Package Manager based apps. Didn’t know about swift test --enable-code-coverage.

CLI tools you won’t be able to live without. fuck looks at least funny. Will see if it’s useful.



Friday, January 20, 23: TIL Xcode configuration files

Read How to manage build settings using Xcode configuration files.



Wednesday, January 18, 23: TIL how transparently compress individual files/folders in macOS (afsctool)

TIL how transparently compress individual files/folders in macOS. It’s about cli afsctool.



Tuesday, January 17, 23: TIL rm -rf $(brew --cache) could free up 7GB om my machine

TIL how could I free up 7GB of memory from caches of Homebrew. It’s rm -rf $(brew --cache). It’s from man brew.



Monday, January 16, 23: TIL how to use ManagedBuffer in Swift

SimpleArray in SwiftBanchmark could be good example/benchmark for better (meaning faster) implementation of Matrix, Bitmap.



Friday, January 13, 23: TIL nothing new(

In Swift there’s a note in UnsafeRawPointer.swift

/// - Note: A trivial type can be copied bit for bit with no indirection or
///   reference-counting operations. Generally, native Swift types that do not
///   contain strong or weak references or other forms of indirection are
///   trivial, as are imported C structs and enumerations.

and in Unsafe[Mutable]RawBufferPointer.swift

/// - Note: A *trivial type* can be copied bit for bit with no indirection
///   or reference-counting operations. Generally, native Swift types that do
///   not contain strong or weak references or other forms of indirection are
///   trivial, as are imported C structs and enums. Copying memory that
///   contains values of nontrivial types can only be done safely with a typed
///   pointer. Copying bytes directly from nontrivial, in-memory values does
///   not produce valid copies and can only be done by calling a C API, such as
///   `memmove()`.

Should this note be unified?



Thursday, January 12, 23: TIL Data labelling is big business

Read interesting post data labelling becoming big business Data Annotation: The Billion Dollar Business Behind AI Breakthroughs.

From Document withUnsafeBytes behaviour when size != stride issue in Swift learned that layout could be checked not only on type like MemoryLayout<Int>.size but on any value with MemoryLayout.size(ofValue: t).



Wednesday, January 11, 23: TIL Voronoi diagrams, Medial axis

From Flying Car and Autonomous Flight Engineer course learned what Voronoi graph and Medial axis (Ukr Серединні вісі) are.

TIL how easy to crash app with dictionary literal in Swift. let dict = [1:"1", 1:"2"] results in fatal error Fatal error: Dictionary literal contains duplicate keys.



Tuesday, January 10, 23: TIL Matrix determinats is polygon area

From Flying Car and Autonomous Flight Engineer course learned that matrix determinant is area of polygon. This is nice explanation Using Determinants to Calculate Areas. If calculated area of triangle is zero that means vectors forming triangle are colliniar. So determinat is nice test of vectors colliniarity (in 2D, in 3D it’s not sufficiant condition of linearity).

Read about eco system of the crazyflie.



Monday, January 09, 23: TIL Swift Expression Macros

TIL Swift is going to introduce macro: Expression Macros Swift proposal. This introduces @expression attribute.



Friday, January 06, 23: TIL gimbal lock

TIL what gimbal lock means.



Thursday, January 05, 23: TIL @ attributes in Swift

Read chapter Attributes of Swift Reference. Good reference. Among others has useful example of using @dynamicMemberLookup for implementing PassthroughWrapper:

struct Point { var x, y: Int }

@dynamicMemberLookup
struct PassthroughWrapper<Value> {
    var value: Value
    subscript<T>(dynamicMember member: KeyPath<Value, T>) -> T {
        get { return value[keyPath: member] }
    }
}

let point = Point(x: 381, y: 431)
let wrapper = PassthroughWrapper(value: point)
print(wrapper.x)


Wednesday, January 04, 23: TIL C++ enum class

TIL what is enum class in C++ aka scoped enumerations.

TIL git diff --staged shows changes for staged files.



Tuesday, January 03, 23: TIL how to work with Swift in Visual Studio on Windows

TIL Visual Studio can work with Swift Packages, so could be used on Windows. Unfortunately I failed to make it work.

TIL there are a lot of starter issues in Swift. Bookmarkign here ones I could fix/implement:

TIL about Policy.swift which declares a lot of interesting stuff, like AnyObject, AnyClass, operator ~= as well as what type of element of literal like [1, 2, 3] or [1.0, 2.0, 3.0] will be and some other stuff.

From Flying Car and Autonomous Flight Engineer nano degree learned A* algorithm.

Side learning from above: refreshed knowledge about heap data structure.



Friday, December 30, 22: TIL oneway keyword on Objective-C

Browsing NSSlowTaggedLocalizedString in Swift stdlib, have found oneway keyword in - (oneway void) release {}. Have never seen this. How? Use-case of oneway void in Objective-C? in Stackoverflow is exactly about this method.



Sunday, December 25, 22: Flying Car and Autonomous Flight Engineer

Have started Udacity’s Flying Car and Autonomous Flight Engineer course.

First things learned, about Drone code foundation. Hm, Linux foundation support them. Dronecode supports open sourced projects. But ardupilot is not among them.



Friday, December 23, 22: Aliases in bash

After more then 20 years on macOS started to use aliases in command line. First alias is alias sub="open -a Sublime\ Text".



Wednesday, December 21, 22: Remove unavailable simulators; SWIFT_DEFER

Bookmarking how to remove unavailable simulators xcrun simctl delete unavailable

TIL about SWIFT_DEFER.



Saturday, December 17, 22: TIL C++ allow declaring variable inside condition in if statement

TIL that in C++ it’s possible to declare variable inside of condition in if:

// Try the platform-specific fast path that avoids heap (re)allocation. Not
// all platforms implement this function.
if (auto argv = swift::getUnsafeArgvArgc(outArgLen)) {
  return argv;
}

The first fixes 1, 2, 3 in Swift thanks to PVS-Studio.



Friday, December 16, 22: restrict keyword in C

Forgot what restrict in C means so had to google. Worth using as it could speed up generated code up to the level generated by FORTRAN.



Thursday, December 15, 22: PVS-Studio

Requested trial license for PVS-Studio. Will try to check C++ code in Swift. Here’s how to generate compile_commands.json needed to run PVS-studio:

swift/utils/build-script <other options> --extra-cmake-options='-DCMAKE_EXPORT_COMPILATION_COMMANDS=ON'

Run PVS-studio analyzer (current directory is swift). Analyzes took 34 hours on my M1 MacBook Pro.

pvs-studio-analyzer analyze -f ../build/Ninja-ReleaseAssert/swift-macosx-arm64/compile_commands.json  -l ~/.config/PVS-Studio/PVS-Studio.lic -o pvs.log

Convert PVS-studio’s log into human readable format:

plog-converter -a GA:1,2 -t tasklist -o project.tasks pvs.log

Experimented with implementing firstIndex(of:) of UnsafeBufferPointer with SIMD. Have to benchmark it to see if it’s better/faster then code generated by library implementation.

extension UnsafeBufferPointer<Int8> {
    func firstIndex(of element: Self.Element) -> Self.Index? {
        //print("count=\(count)")

        guard let pointer = baseAddress else { return nil }
        let address = Int(bitPattern: pointer) // Any guarantee Int is same wide as pointer

        var i = 0
        let stride = MemoryLayout<Int8>.stride // or alignment? jump to Int(bitPattern:) in headers
        let simd4Int8Stride = MemoryLayout<SIMD4<Int8>>.stride
        assert(simd4Int8Stride == stride * SIMD4<Int8>.scalarCount) // Memory layout of SIMD4<Int8> should match one of 4 Int words
        let simd4Int8Sample = SIMD4<Int8>(repeating: element)
        let simd4Int8MaskAllFalse = SIMDMask<SIMD4<Int8>>(arrayLiteral: false, false, false, false) // Why SIMDMask needs SignedInteger?

        // Bytes up to beginning of a SIMD4
        while (address &+ i) % simd4Int8Stride != 0 && i < count {
            guard self[i] != element else { return i }
            i &+= 1
        }

        // Full SIMD4
        // print("Full SIMD4")
        while (i &+ simd4Int8Stride) < count {
            let simd4: SIMD4<Int8> = UnsafePointer(
                bitPattern: address &+ i
            )!/*._unsafelyUnwrappedUnchecked*/.pointee
            //let simd4 = SIMD4<Int8>(array[address+i..<address+i+4])
            // Where is functionality to search for Scalar in SIMD?
            // We have sum(), min(), max() but don't have firstIndex(of: Scalar)
            guard (simd4 .== simd4Int8Sample) == simd4Int8MaskAllFalse else {
                var offset = 0
                while offset < simd4.scalarCount && simd4[offset] != element {
                    offset += 1
                }
                if offset < simd4.scalarCount {
                    return i + offset
                } else {
                    fatalError()
                }
            }
            i &+= simd4Int8Stride
        }

        // Rest bytes up to end
        //print("Rest bytes up to end i=\(i)")
        while i < count {
            guard self[i] != element else { return i }
            i &+= 1
        }

        return nil
    }
}


Wednesday, December 14, 22: (opinionated) iOS Interview Questions

Read how to embed Python interpreter in iOS or macOS app and successfully publish it to the AppStore. Don’t know why I need this.

Read My personal (opinionated) iOS Interview Questions in interviewing iOS Engineers. Some questions are quite interesting.

Read Finding Memory Leaks in Mobile Apps (Part 1: Visualization).



Tuesday, December 13, 22: Ask Apple a question; swift-tagged package

Should ask Apple a question about returning from Objective-C function autoreleased Core Graphics object.

Came accross swift-tagged package. Simple thing like typealias Id = Tagged<User, Int> makes types unique.



Saturday, December 10, 22: TIL swift-system package; yield keyword in Swift

GitHub recommended swift-system package. Interesting stuff. Browsing came across yeild keyword in FilePathComponentView source.

Jumped to The yield keyword post.



Friday, December 09, 22: SwiftPM package to WebAssembly

TIL how compile Swift package to WebAssembly: swift build --triple wasm32-unknown-wasi.



Tuesday, December 06, 22: Swift package manifest cheatsheet; Swift Package Manager Usage

From Swift package manifest cheatsheet how to set difines directly in Package.swift:

swiftSettings: [
    .define("DEBUG"),
    .define("DEBUG", .when(platforms: [.iOS, .macOS, .tvOS, .watchOS], configuration: .debug)),
    .unsafeFlags(["-D EXAMPLE"]),
    .unsafeFlags(["-D EXAMPLE"], .when(platforms: [.iOS], configuration: .debug)),
]

Immediately used in in swift-png to pass NO_INTRINSICS on Windows.

Cool that swift package could depend on libraries which could be installed with brew or apt.

Read All about the Swift Package Manager and the Swift toolchain. Mess. But there’re interesting finding:

swift lol
error: unable to invoke subcommand:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-lol
(No such file or directory)

swift build, run, test subcommands are just another Swift binary executables placed inside the toolchain’s binary path. (Named like: swift-package, swift-build, swift-run, swift-test).

People do things like swift-ci, CI written in Swift.

Read Deep dive into Swift frameworks: Learn everything about Swift modules, libraries, packages, closed source frameworks, command line tools and more..

Browsed Swift Package Manager Usage. I did missed that such documentation exists. Why there’s no direct link to it from README.md? Learned about swift package resolve.



Monday, December 05, 22: TIL @_implementationOnly; GitHub actions

From swift-package-manager sources learned @_implementationOnly exists. No idea what exactly it is for.

Read documentation about GitHub actions.



Saturday, December 03, 22: Low-level Swift optimization tips; Stable Diffusion to Core ML; Debugging Tips

TIL new things about performance in Swift Low-level Swift optimization tips by the author of swift-png and swift-jpeg. Well, this quote I will point to to anyone saying Swift is faster then C:

Reasonably well-written Swift code without any detailed optimization can easily achieve run time performance within 200 to 250 percent of a bare-metal C implementation. (Lower is better.) Busts popular myths like wrapping arithmetic like &+ is faster then regular arithmetic, and @inline(__always) as a magical make this faster.

New for me is suggestion to favour us of ManagedBuffer instead of UnsafeMutableBufferPointer in attempt making arays faster.

Interesting note about poor performance if Dictionary(grouping:by):

[Dictionary.init(grouping:by:)](https://developer.apple.com/documentation/swift/dictionary/init(grouping:by:)/) seems to exhibit exceptionally poor performance, compared to a naive two-pass bucketing algorithm. (One pass to determine the sub-array counts, and one pass to populate the sub-arrays.) Only use Dictionary(grouping:by:) if you have a single-pass Sequence and absolutely need the Dictionary output format.

There’re benchmarks in stdlib for this. Would be interesting to try rewrite.

TIL Apple ported Stable Diffusion to Core ML.

Read Debugging Tips by Krzysztof Zabłocki. Should create .lldbinit file in home directory. Should return to this later on.



Friday, December 02, 22: TIL the less dependencies the better

Read Chris’ Eidhof post Dependencies. Why we got rid of most dependencies. By the way, the site itself is generated with StaticSite, here is the source of the site. As long as objc.io.

Tried chat.openai.com. No luck. Not available in your country. Should try launch VPN



Thursday, December 01, 22: TIL how good Swift runtime detecting non-exclusive access; about DigitalOcean Functions

TIL how good Swift runtime detecting non-exclusive access:

swift run -c release integration-test --compact
Building for production...
Build complete! (0.08s)
Simultaneous accesses to 0x102540640, but modification requires exclusive access.
Previous access (a modification) started at integration-test`PNGIntegrationTests_main + 96 (0x102512684).
Current access (a read) started at:
0    libswiftCore.dylib                 0x000000019a4f806c swift::runtime::AccessSet::insert(swift::runtime::Access*, void*, void*, swift::ExclusivityFlags) + 432
1    libswiftCore.dylib                 0x000000019a4f8294 swift_beginAccess + 84
2    integration-test                   0x0000000102513944 static Test.decode(path:premultiplied:) + 320
3    integration-test                   0x0000000102513430 static Test.decode(_:subdirectory:) + 384
4    integration-test                   0x0000000102513408 closure #1 in closure #1 in static Test.cases.getter + 28
5    integration-test                   0x000000010251dc88 test(_:cases:name:) + 468
6    integration-test                   0x000000010251a0f4 commonMain(commandLineArguments:options:filters:testCases:) + 608
7    integration-test                   0x0000000102512624 PNGIntegrationTests_main + 144
8    dyld                               0x000000018c10b460 start + 2544
Fatal access conflict detected.
zsh: abort      swift run -c release integration-test --compact

TIL about github codespaces. Interesting stuff. Unfortunately, I am not web-developer. May be, occasionally I could use it for Jupyter notebooks.

TIL about Manim, animation engine for explanatory math videos, like 3Blue1Brown.

TIL about shields.io github for whatever could be shown on shields.

TIL that Digital Ocean this year introduced DigitalOcean Functions, analogue of AWS lambdas: DigitalOcean Enters the Serverless Arena with DigitalOcean Functions. DigitalOcean Functions documentation. Unfortunately, no Swift support so far. List of supported runtimes could be checked anytime with doctl serverless status --languages.



Wednesday, November 30, 22: TIL more about cross-platform Swift

TIL more about running Swift cross-platform. Read Automatic test discovery in Swift on Linux.

Read LinuxMain.swift and Custom Target Layouts.

From Generating LinuxMain breaks when renaming a test learned that LinuxMain.swift could be generated.



Monday, November 28, 22: TIL How to share code between targets in Swift package; Codable vs NSCoding

From swift-numerics package learned how to organize package with internal dependencies Package.swift. I am going to follow this pattern to get rid of symlinks in swift-png package.

Read Swift Forum thread Should I stick with Codable or switch back to NSCoding?.



Sunday, November 27, 22: TIL how to build customized dmg in command line

TIL about dmgbuild. It’s one of dependencies of qFlipper macOS app. dmgbuild is a command line tool to create macOS disk images (aka .dmg files). While it is possible to create disk images easily enough from the command line using the hdiutil program that ships with macOS, there is no easy way to configure the appearance of the resulting disk image when the user opens it. dmgbuild allows for full customization of the resulting disk image, without relying on Finder, and without using deprecated APIs (like the Alias Manager functions).



Saturday, November 26, 22: TIL how to use symlinks in git repo in Windows

TIL how to use symlinks in git repo in Windows. Made PR trying using swift-png on Windows.



Friday, November 25, 22: TIL how to pass defines with -Xswiftc option to all swift compiler invocations

TIL how to pass define to Swift compiler invocations when building Swift package from command line: swift build -Xswiftc -DNO_INTRINSICS - passes define NO_INTRINSICS.

TIL about flag WARN_COPY_ON_WRITE. Should experiment with swift-geometrize with it.



Thursday, November 24, 22: TIL subst Windows command; Managed to make Swift on Windows working

TIL subst Windows command for creating virtual drive from a folder.

TIL than uninstalling and re-installing still works on Windows. Finally, managed to make Swift on Windows working by uninstalling and re-installing Visual Studio and Swift.

Bookmarking how to launch ssh-agent on Windows: Starting ssh-agent on Windows 10 fails: “unable to start ssh-agent service, error :1058”.

Bookmarking how to launch ssh-agent on Windows with GUI. Failed to do this with command line.



Tuesday, November 22, 22: TIL that Swift on Windows 10 isn’t working

Failed to make Swift work on Windows 10. Swift Forums: Having error compiling a simple hello.swift on Windows 10.

What I have learned that to compile Swift source on Windows I should run swiftc -emit-executable -o hello.exe hello.swift.

swift hello.swift is not compiling. What’s it doing then?



Wednesday, November 09, 22: TIL Compiler Explorer. Again

Played with Compiler Explorer while thinking of adding some SIMD optimizations to Swift. Read How it works: Compiler Explorer. Really cool stuff. Surprizing it works on single Amazon EC2 instance most of the time.



Wednesday, November 02, 22: TIL APPLE DEVELOPER RESOURCES for Swift; Swift Driver

Read Swift documentation The Swift Driver, Compilation Model, and Command-Line Experience.

From running man swift came accross APPLE DEVELOPER RESOURCES for Swift. A lot of interesting stuff.



Tuesday, November 01, 22: TIL how to train YOLO and a lot about Swift generics and how they are compiled

Bookmarking YOLOv4 Training Tutorial (Training YOLOv4 в Google Colab (Russian translation)). It’s very good step by step guide with example on recognizing car licenze plate.

Bookmarking Learning from the task “Recognizing traffic sings in frames from dashboard cam” (Russian). It’s about training YOLO, especially YOLO5 with resolution 1280 pixel which better suits to the task of recognizing relatively small images of traffic signs. Post is very usefull step-by-step trainign YOLO guide. I should follow this guide. All code is available on GitHub. Post refers Russian traffic sign images dataset. It’s 18GB of data. I have downloaded it for further use.

Continue reading Compiling Swift Generics. Surprize. Optional var in Swift is being initialized only if it’s declared with sugar syntax T?:

var x: Int?
print(x)  // prints ‘nil’
var y: Optional<Int>
print(y)  // error: use of uninitialized variable ‘y’

This is also curious to know:

The standard library declares a type alias Void whose underlying type is ().

This as well:

An unlabeled one-element tuple type cannot be formed at all; (T) resolves to the same type as T in the language.

Interesting, that beside of inout parameter could have attribute __owned or __shared. What these are for?

Fuck, finally I got what is metatype and what misterious .Type is:

Types are values in Swift, and a metatype is the type of a type used as a value. The metatype of a type T is written as T.Type. The type T is the instance type of the metatype. The type T is the instance type of the metatype. For example (() -> ()).Type is the metatype type with the instance type () -> (). This metatype has one value, the function type () -> ().

Whaaaaaaaat?

let (x: Int, y: String) = (x: 123, y: "hello")
print(Int)  // huh? prints 123
print(String)  // weird! prints "hello"


Friday, October 28, 22: TIL how Swift generics are compiled and usefull compiler flags

Read Swift documentation Compiling Swift Generics. Useful reading.

The -### driver flag performs a “dry run” which prints all commands to run without actually doing anything.

Interestings compiler flags like -debug-cycles and -stats-output-dir for debugging compiler speed.



Monday, October 24, 22: Bookmarking post Why I am sceptical selfdiving cars will boom in next 5 years

Bookmarkinng post Why I am sceptical selfdiving cars will boom in next 5 years (Russian) which I will share with overoptimistic pals.



Sunday, September 18, 22: TIL math behind different blend modes

Read about math behind different blend modes. Then I attempted to implement snapshotting strategy on Bitmap in swift-geometrize library which I port to Swift.



Saturday, September 17, 22: TIL about snapshot testing implementation

Watched A Tour of Snapshot Testing in attempt to extend Bitmap to make it smapshot testible. Challenge here is doing it without UIImage and NSImage.



Wednesday, September 07, 22: Bookmarking good implementaion of RandomNumberGenerator with seed

Bookmarking good example of RandomNumberGenerator with seed from Swift package swift-argument-parser.



Saturday, September 03, 22: Bookmarking essay Why operators are useful by Guido van Rossum

To those who will continue saynig (0..20).contains(index) is better than 0..20 ~= index which I fond to use I will point Why operators are useful essay of Guido van Rossum.



Monday, August 15, 22: TIL image dithering

Read interesting article about dithering Ditherpunk — The article I wish I had about monochrome image dithering. Screenshow as example of image dithering.

Bookmarking swift packages JPEG is a cross-platform pure Swift framework for decoding, inspecting, editing, and encoding JPEG images and PNG is a pure, cross-platform Swift framework for decoding, inspecting, editing, and encoding PNG images. Hope to use these when I complete porting geometrize C++ library to Swift (EDIT: this is done) and implement demo like geometrize haxe web demo but in Swift for Web.



Friday, August 12, 22: Bookmarking article Slow Swift Compiler Performance

Read Slow Swift Compiler Performance. Bookmarking for Xcode options -Xfrontend -warn-long-function-bodies=<limit> and -Xfrontend -warn-long-expression-type-checking=<limit>.



Tuesday, August 09, 22: Bookmarking article about remote sensors monitoring

Bookmarking article Remote sensors monitoring (Russian).



Monday, July 25, 22: Read post Why IT-man cannot pass interview with HR; Read post about data labelling

Bookmarking very interesting tips for HR interview Why IT-man cannot pass interview with HR (Russian).

Read very interesting post Data Labeling in Machine Learning: Process, Types, and Best Practices.



Tuesday, July 05, 22: Watched some session videos from WWDC 2022

Watched WWDC 2022 session Create parametric 3D room scans with RoomPlan video.

Watched WWDC 2022 session Design App Shortcuts video.

Watched WWDC 2022 session Discover advancements in iOS camera capture: Depth, focus, and multitasking video.

Watched WWDC 2022 session video Adopt Variable color in SF Symbols.



Friday, June 24, 22: TIL built-in sound classification in SoundAnalysis framework

Watched WWDC 2021 session video Discover built-in sound classification in SoundAnalysis.



[Thursday, June 23, 22: TIL ShazamKit; Swift allows now writing extension Array { /* ... */ }](/2022/06/23/TIL.html)

Read Swift proposal Extensions on bound generic types. Implemented in Swift 5.7. It’s about writing

extension Array<String> { /* ... */ } 

instead of

extension Array where Element == String { /* ... */ }

Watched WWDC 22 session video Explore ShazamKit. This definately could be used in eNote app I have worked seveal years ago.



Wednesday, June 22, 22: TIL idea recognizing images with KAZE, SIFT, ORB algorithms

From Recognizing paintings wthout recognition (Russian) got idea about recognizing objects without neural networks but with OpenCV’s algorithms KAZE, SIFT, ORB. This might work at least for detecting road signs. But could work for recognizing as well.



Wednesday, May 11, 22: TIL Actor model and Actors in Swift

Read Antoine van der Lee’s blog post Actors in Swift: how to use and prevent data races and by link from there read WiKi article Actor model.



Tuesday, May 10, 22: TIL Compiler explorer to research compiler output

Found good service Compiler explorer to research compiler output.



Saturday, May 07, 22: TIL about distributed systems built with Swift

Watched Scale By The Bay 2021: Konrad Malawski, Distributed Systems with Swift.



Monday, April 25, 22: TIL result builders (@resultBuilder) in Swift

Come accross @ViewBuilder in View SwiftUI protocol. Jumped to reading post A deep dive into Swift’s result builders. @ViewBuilder is @resultBuilder.



Friday, April 22, 22: Watched video Simple AWS Lambda website

Watched Build a Simple AWS Lambda website.

TIL mkfile 10m test.pdf creates pdf file with size 10MB. Convinient for testing. Unfortunately, files are filled in with zeros.



Thursday, April 07, 22: TIL Embedded development in Swift; Swift Numerics introducing Real and Complex; μSwift; C Isn’t A Programming Language Anymore; ThreadX running Raspberry Pi; Websites using Swift and AWS Lambda

Learned how to install/use Sublime Text on Windows. Forgotten experience for me. Most of time nowdays I have access only to Windows computer. But it doesn’t stop me from learning.

Read Swift forum thread Introduce embedded development using Swift. Very interesting reading.

Read On the road to Swift 6.

Read Swift Numerics which introduces Real and Complex. And in future it’s supposed to add ShapedArray - equivalent of numpy’s ndarray, Fixed-size integers larger than Int64 (some time ago I wanted to use Int128 and was surprised there’s no such type in Swift).

From one of above leared about μSwift.

Read C Isn’t A Programming Language Anymore. “C is an inscrutable implementation-defined mess”. “C is the lingua franca of programming.” Target triples, like aarch64-apple-ios-sim.

Side-reading What’s wrong with Raspberry Pi (in Russian) about (Microsoft own closed sourced) ThreadX real-time OS which runs Raspberri Pi under the hood.

Starting experimenting with Websites using Swift and AWS Lambda.



Thursday, February 24, 22: Help Ukraine Now!

SWUbanner



Sunday, September 19, 21: TIL about __auto_type in Objective-C

__auto_type layersOnlySet = [NSSet setWithArray:layersOnly];

What is __auto_type? How could it be I have never heard of it and never used it?



Wednesday, August 18, 21: TIL NSTextAlignment lesson: same enum could have different raw values on different platforms

It’s never safe to persist raw values of enums. The not only can change in time, raw values for same cases might be different on different platforms, like with NSTextAlignment. Addressing Architectural Differences in Your macOS Code.



Thursday, August 12, 21: TIL about Swift type placeholders and the trick of using tuples for complex sorting operations

Read accepted Swift evolution proposal Type placeholders (formerly, “Placeholder types”).

Read post Using tuples to Complex Sorting Operations in Swift. The idea is brilliant.



Sunday, July 11, 21: TIL about memory usage performance

Read Memory Usage Performance Guidelines. I have already forgotten about NSDiscardableContent protocol and NSPurgeableData class.



Saturday, July 10, 21: TIL how to extract data from documents using Vision framework

Watched WWDC 21 session video Extract document data using Vision.



Wednesday, June 30, 21: TIL how tagged pointers are working in Objective-C

Watched WWDC 2020 session video Advancements in the Objective-C runtime. Part about tagged pointers is interesting.



Saturday, June 26, 21: TIL/refreshed memory about NSOperations

Watched WWDC 2015 session 226 video Advanced NSOperation’s.



Saturday, May 15, 21: TIL Bradly algorythm for binaryzing images

Bookmarking interesting post about images binaryzation Binaryzation of images: Bradly algorythm (Russian).



Thursday, April 29, 21: TIL something new about iCloud sync

Read Apple documentation iCloud Design Guide.



Saturday, April 24, 21: TIL how to migrate your project with Carthage to Xcode 12

Bookmarking good how to How to migrate your project with Carthage to Xcode 12.



Sunday, April 18, 21: TIL XCFramework format in Xcode 11 (Binary Frameworks in Swift)

Watched WWDC 2019 Session 416 video Binary Frameworks in Swift about new XCFramework format in Xcode 11.



Monday, April 12, 21: TIL how to detect taps in SwiftUI

Watched objc.io Swift Talk SwiftUI Path Builder: Detecting Taps.



Saturday, April 10, 21: TIL xargs

TIL about xargs.



Tuesday, April 06, 21: TIL about GitHub easter eggs

Read in a post Six secret Easter Eggs in GitHub about a trick of adding repo with name matching the user name.



Sunday, March 07, 21: TIL what exactly are meant by frameworks

TIL what exactly are meant by frameworks talking about Apple platforms: Framework Programming Guide: What are Frameworks?



Wednesday, March 03, 21: TIL how to print git remote branches sorted by last commit date

One-liner for listing remote git branches sorted by the last commit date for each branch (gist with source):

for branch in `git branch -r | grep -v HEAD`;do echo -e `git show --format="%ci %cr" $branch | head -n 1` \\t$branch; done | sort -r


Saturday, February 27, 21: TIL how to Set PTR Records and Reverse DNS in DigitalOcean

Read How to set up your own email server (russian).

Learned How to Set PTR Records and Reverse DNS in DigitalOcean - it’s just about renaming a droplet to a fully qualified domain name.



Thursday, February 25, 21: TIL in Swift cast from ‘Any’ to ‘AnyObject’ always succeeds

TIL that in Swift cast from ‘Any’ to ‘AnyObject’ always succeeds: Any as AnyObject:

When trying to bridge an incompatible thing to Obj-C (such as the structure value or function value in your example), Swift will wrap the value in an opaque Obj-C compatible box that can be round tripped across the bridge.



Tuesday, February 23, 21: TIL a bit about Quick Look

Watched Quick Look Previews from the Ground Up. It’s about iOS. But actually, same approach should work for macOS as well. QuickLook works on both, iOS and macOS. Previews or Thumbnail Images for macOS 10.14 or Earlier.

What’s New in File Management and Quick Look.

Here’s correct way of creating temporary file for atomic document creation which will speed up following moving file to final location or deletion in multivolume environment:

do {
	let tempURL = try FileManager.default.url(for: .itemReplacementDirectory, in: [.userDomainMask], appropriateFor: url, create: true) 
} catch { // Handle error }



Monday, February 15, 21: TIL a lot about CRC32

Trying to use ZIPFoundation Swift package, I came across this:

Note: There is a large performance discrepancy between Debug and Release builds of ZIP Foundation. The main performance bottleneck is the code that calculates CRC32 checksums. This codepath executes slowly when Swift optimizations are turned off (-Onone). To avoid long wait times when debugging code that extracts archives, the skipCRC32 flag can be set. To learn more about the skipCRC32 parameter, please refer to the documentation strings of the Archive.extract and FileManager.unzipItem methods. Skipping CRC32 checks should only be enabled during debugging.

I look crc32(checksum:) implementation to figure out what’s wrong with it.

Firstly, I proposed PR: Speed up crc32 calculation in performance test ~4 times.

I started to think about a way to speed up crc32 calculation even further, possibly used SIMD extensions.

Have found swift-crc32c swift package which uses SSE 4.2 instruction set if running on an Intel CPU that supports it.

Failed to find something similar for ARM. But I have found this in linux crc32-ce-glue.c: Accelerated CRC32(C) using ARM CRC, NEON and Crypto Extensions instructions and crc32c-intel_glue.c: Using hardware provided CRC32 instruction to accelerate the CRC32 disposal.

So there’s some opensourced foundation for Swift package for hardware accelerated CRC32 for both Intel and ARM.

This worth bookmarking Ethernet CRC32 calculations. Includes brief CRC tutorial.

This from Android worth bookmarking crc32-arm64.c - CRC32 and CRC32C using optional ARMv8 instructions.

Zlib in Chromium include both ARMv8 and Intel crc32_simd.c.

This is interesting Stackoverflow question: How to detect crc32 on aarch64.

Interesting repo validating Chromium’s SIMD CRC.

And finally, this is pure gold A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS which might be useful in attempt to implement crc32 from scratch or in attempt understand and/or improve implementation from others.

The best option would be implementing CRC32 package with Swift SIMD Vector Types.

Today’s finding: ZIPFoundation’s CRC32 is exactly what happening in crc32.c. Precalculated table matches first part from crc32.h (precalculated with crc32.c file).



Tuesday, February 09, 21: TIL spellchecking is available in Xcode since version 11

How I didn’t know earlier that spellchecking is available in Xcode since version 11.



Monday, February 01, 21: TIL about CPU 6502 emulator

Accidentally came across video Emulating a CPU in C++ (6502) and couldn’t stop watching it. 6502 CPU reminds me myself in my 20.



Friday, January 29, 21: TIL how to catch exact exception in Swift

From Handling Cocoa Errors in Swift TIL, finally, how to catch only specific errors when making file operations, e.g. not throw if file doesn’t exist when deleting file:

do {
    try fileManager.moveItem(at: fromURL, to: toURL)
} catch CocoaError.fileNoSuchFile {
    print("Error: no such file exists")
} catch CocoaError.fileReadUnsupportedScheme {
    print("Error: unsupported scheme (should be 'file://')")
}


Friday, January 22, 21: TIL UTF-8 encoding used by Mac for filenames is insane

TIL that UTF-8 encoding for filenames for mac is insane and incompatible with other systems. It uses different form of normalization. convmv should be used to fix filenames.



Monday, January 18, 21: TIL how to setup Brother printer on Raspberry Pi

Notes for future self how to setup Brother HL-L2300D on Raspberry pi:



Monday, January 04, 21: TIL how to decode a JSON Field that Could Be String or Double with Swift

Read Decoding a JSON Field that Could Be String or Double with Swift of my colleague Luca Angeletti.



Thursday, December 31, 20: TIL details about inlining in Swift

Read Understanding @inlinable in Swift. Then read two years older of the same author The Forbidden @inline Attribute in Swift. Read Cross-module inlining and specialization. Read When should both @inlinable and @inline(__always) be used?. The last is extremely interesting.



Monday, December 28, 20: TIL about ARUCO markers; how to launch built in Python IDE named IDLE

Watched video PRECISION LANDING | with OPENCV and ARUCO Markers | Part 1 and https://www.youtube.com/watch?v=iezU2PR0hBk.

Learned that Python has its own built in IDE named IDLE. To launch it, first, python interpreter sholuld be launched, then in it import idlelib.idle triggers IDLE launching.



Saturday, December 26, 20: TIL more about Property Wrappers in Swift

Watched Anatomy of a Property Wrapper. The best explanation of property wrapper I’ve seen so far.



Tuesday, December 22, 20: Read GitHub Actions for iOS projects

Read GitHub Actions for iOS projects.



Monday, December 21, 20: TIL Image segmentation with deep learning

Attended meetup Image segmentation with deep learning. Learned difference between semantic segmentation vs instance segmentation. withoutbg.com and segmentive.ai - very good examples of what could be done.



Sunday, December 20, 20: Watched WWDC 2019 session 413 video Testing in Xcode

Watched WWDC 2019 session 413 video Testing in Xcode. Learned about xctestplan. XCTUnwrap! XCAssertEqual has parameter accuracy! XCTAssertThrowsError!



Friday, December 18, 20: Read Organizing Your Code with Local Packages

Read Organizing Your Code with Local Packages.



Thursday, December 17, 20: TIL a lot about Swift Packages and Binary Frameworks

Read Migrate Your iOS Project From CocoaPods To Swift Package Manager presents a process to migrate iOS projects to Swift Package Manager fully.

Read Binary Frameworks as Swift Packages

in this article, we’ll cover both how to integrate a binary Swift package into your project and how we created a binary Swift package using Xcode 12. We’ll also discuss how Swift Package Manager compares to the other dependency managers for iOS like CocoaPods and Carthage.

Read Supporting XCFrameworks

Watched WWDC 2019 session video Binary Frameworks in Swift introducing XCFramework.



Tuesday, December 15, 20: After several years I have again project with git submodules

After several years I have again project with git submodules.



Friday, December 11, 20: TIL about Swift Struct Storage

Read Mike Ash’s Friday Q&A 2016-01-29: Swift Struct Storage.



Friday, November 27, 20: Read Swift on Raspberry Pi Workshop

Read Swift on Raspberry Pi Workshop: Part 1, from which I learned about Swish, script for remote building your Swift projects on a Linux machine. Unfortunately, is not updated since 2016. Anyway, I didn’t get how to use it without Xcode, only with Swift package manager. Probably, I need this tool Builder.

Swift on Raspberry Pi Workshop: Part 2.



Monday, November 23, 20: TIL what’s new in Swift 5.4

Googled what’s new in Swift 5.4. Not too much.

Whatched Swift 5.4, Subscription Codes, Big Sur Icons, SF Symbols 2.1. Subscription offers for me are new.



Sunday, November 22, 20: TIL how to restore deleted branch in git and some comprehenses of git stash

Learned how to restore deleted branch in git:

  1. Find the SHA1 for the commit at the tip of deleted branch running git reflog --no-abbrev;

  2. Recreate branch running git checkout -b <branch> <sha>.

Learned some comprehenses of git stash:

  • git stash save “Your stash message” allow give message to your stash

  • git stash save -u or git stash save --include-untracked stashes untracked files

  • git stash apply stash@{1} applies specific stash

  • git stash pop applies the most recent stash and removes it. Could also be run with specific stash git stash pop stash@{1}

  • git stash show shows summary of stash diffs. git stash show -p shows full diff. Could be run with specific stash git stash show stash@{1}.

  • git stash branch <name> stash@{1} creates a new branch with the latest stash, and then deletes the latest stash (like stash pop).

  • git stash clear removes all sashes in repo.

  • git stash drop removes most top stash without applying it. git stash drop stash@{1} removes specific stash.



Saturday, November 14, 20: Read Create a React- and SwiftUI-Inspired Web App With Swift for WebAssembly on MacOS With SwiftWasm

Working on simulator for SenseHat I have read Create a React- and SwiftUI-Inspired Web App With Swift for WebAssembly on MacOS With SwiftWasm.

SwiftWasm Documentation is available. Open sourced.



Saturday, November 07, 20: TIL FileManager.default.displayName(atPath: url.path) for displaying name of file/folder to the user

From NSHipster learned:

Long story short, when displaying the name of a file or directory to the user, don’t simply take the last path component. Instead, call the method displayName(atPath:):

// Bad
let filename = directoryURL.pathComponents.last

// Good
let filename = FileManager.default.displayName(atPath: url.path)


Thursday, November 05, 20: Read Modern Dependency Injection in Swift

Read Modern Dependency Injection in Swift.



Tuesday, November 03, 20: TIL how to rotate images and matrices

Today I have been scratching my head with rotating image on arbitrary angle. Something which looked easy from first look isn’t that easy at all. Here’s good explanation about how artifacts appear during rotation and how to avoid them Rotating Images. Nice wiki article gives introduction to rotation matrix Rotation matrix. This oldfashioned site Leptonica has nice section Rotation which explains Rotation by Area Mapping.



Monday, November 02, 20: Read My Swift Package Manager Release Workflow

Bookmarking My Swift Package Manager Release Workflow. It’s about workflows for GitHub actions: one is the tests workflow which runs on every commit and another is the release workflow which is triggered by the creation of a git tag that starts with a v.



Sunday, November 01, 20: TIL how to make C library available in Swift using the Swift Package Manager

Learned Making a C library available in Swift using the Swift Package Manager.

Read Modules in llvm.

Read SwiftPM’s Usage which us surprisingly detailed. Creating C Language Targets section helped me.



Monday, October 26, 20: Read Interviewing for an iOS Design System Engineer role at Spotify

Read Interviewing for an iOS Design System Engineer role at Spotify.



Sunday, October 25, 20: Read Writing High-Performance Swift Code from Swift compiler

Read Writing High-Performance Swift Code from Swift compiler.

Hm, final could by applied not only for classes but for methods and properties as well. Also private and fileprivate allow compiler infer final.

Interesting (despite ineffective for copying) way representing trees:

protocol P {}
struct Node: P {
  var left, right: P?
}

struct Tree {
  var node: P?
  init() { ... }
}

Brilliant idea to use Array as box just to benefit copy-on-write:

struct Tree: P {
  var node: [P?]
  init() {
    node = [thing]
  }
}

And this Box can replace the array in the code sample above:

final class Ref<T> {
  var val: T
  init(_ v: T) {val = v}
}

struct Box<T> {
    var ref: Ref<T>
    init(_ x: T) { ref = Ref(x) }

    var value: T {
        get { return ref.val }
        set {
          if !isKnownUniquelyReferenced(&ref) {
            ref = Ref(newValue)
            return
          }
          ref.val = newValue
        }
    }
}


Saturday, October 24, 20: TIL dynamic in Swift; what Thunk means in computer programming

Read What Does the Dynamic Keyword Mean in Swift 3 about static, virtual and dynamic dispatch in Swift. Still, I don’t get difference between @objc and dynamic. I know that dynamic implies @objc. And I don’t know what’s the difference between the two.

Ok. Above post was a little outdated. From newer one @objc and dynamic dynamic iplied @objc pre Swift 4.

Here’s the least you need to remember:

  • @objc makes things visible to Objective-C code. You might need this for setting up target/action on buttons and gesture recognizers.

dynamic opts into dynamic dispatch. You might need this for KVO support or if you‘re doing method swizzling. The only way to do dynamic dispatch currently is through the Objective-C runtime, so you must add @objc if you use dynamic.

Learnt what Thunk is:

In computer programming, a thunk is a subroutine used to inject an additional calculation into another subroutine.



Monday, October 19, 20: Watched Mike Ash’es talk Exploring Swift Memory Layout

Watched (quite old) Mike Ash’es talk Exploring Swift Memory Layout. Interesting points:

  • mach_vm_read_overwrite
  • malloc_size
  • dladdr
  • 44:00 swizzling possible


Friday, October 16, 20: Read Benchmarking Xcode Performance on a large Swift Project

Read Benchmarking Xcode Performance on a large Swift Project. iMac, MacBook, iMac Pro compared. Comparison is curious. Conclusion that size of memory, 16Gb, 32Gb or 64Gb isn’t that important also curious.



Thursday, October 15, 20: Read Readdle’s Swift for Android

Read Readdle’s Swift for Android: Our Experience and Tools. Apple’s post Introducing Swift on Windows refers Readdle as early adopters.



Tuesday, October 06, 20: Read Compile Swift for Raspberry Pi by Xcode

Bookmarking Compile Swift for Raspberry Pi by Xcode.



Sunday, October 04, 20: TIL ThreadX proprietary realtime OS launches on Raspberry Pi before Linux

Read What’s wrong with Raspberry Pi. Learned that on Raspberry Pi firstly proprietary realtime OS ThreadX loads on GPU (!) which then loads Linux on CPU. And Linux is the second class citizen on the platform. Throttling, power management is controlled by ThreadX, not Linux. That was eyeopener. Also eyeopener is fact that ThreadX belongs to Microsoft now according to Wikipedia.



Friday, October 02, 20: TIL about different ways of reading/writing GPIO on Linux

Read about different ways of reading/writing GPIO on Linux.

As I get now SwiftyGPIO.swift is this code ported to Swift.



Tuesday, September 29, 20: TIL about Swift for Tensorflow

Watched Webinar A deeper dive into Swift for Tensorflow.



Monday, September 28, 20: TIL storing loaded images with NSCache and NSURLCache in Swift; Network Link Conditioner on macOS; how to print all characters from CharacterSet

Watched Swift: Loading Images Asynchronously and storing with NSCache and NSURLCache. I didn’t know Link Conditioner exists for macOS. I always used one in OS. Also I have never used NSURLCache. I only used NSCache previously.

Read NSHipster’s Network Link Conditioner.

Read NSHipster’s As We May Code. Understood nothing. Then read Cross-Pollination where also understood very little.

Read Understanding Swift’s CharacterSet. It’s brilliant! Has a code to print all characters from any character set. It’s eye opener to print out CharacterSet.decimalDigits. That’s what I always wanted to point my colleagues.



Sunday, September 27, 20: TIL Robot pattern; swift-system package

Read about Robot pattern UI Testing in iOS - Robot Pattern.

Read Swift System is Now Open Source.



Friday, September 25, 20: TIL state of Swift for WebAssembly; Generators in Swift

Read Max Desiatov post The state of Swift for WebAssembly in 2020 (and earlier). Learned that asm.js was superseeded by WebAssembly (often shortened to Wasm).

TODO: Xcode sucks to fix this:

CGSize size = [self.valueLabel.text sizeWithFont:self.valueLabel.font
                               constrainedToSize:CGSizeMake(self.valueLabel.frame.size.width, MAXFLOAT)
                                   lineBreakMode:NSLineBreakByWordWrapping];

 

Read How do closures and callbacks work? It’s turtles all the way down, Event loops, building smooth UIs and handling high server load, , What are generators and why Swift needs them?. The idea of Generator is brilliant. I remember being confused seeing yeild in Python code. Read Coroutines and “yield” expressions in Swift.



Thursday, September 24, 20: TIL C++ isn’t fast

Bookmarking blogpost Is C++ fast? to show to thous who claims C++ is as fast as C.



Tuesday, September 22, 20: TIL how use pointers in Swift; use Swift on AWS Lambda with Xcode

Surprisingly, Apple has good enough information about use cases of pointers in Swift UnsafeRawPointer Migration.

Watched WWDC 2020 session video Use Swift on AWS Lambda with Xcode.



Monday, September 21, 20: Watched cocoacast episode Mastering MVVM With Swift

Watched several episodes of Mastering MVVM With Swift.



Sunday, September 20, 20: TIL Optional argument chaining in Swift

Watched What’s new in Swift. TODO: write simple app(s) in Swift and Objective-C to compare code size and heap usage.

Learned what is Optional Argument Chaining. I have known what it is, but did not know the name.

// Reading contents of URL might look like this:
let contents: String?
if let url = URL(string: "/url/to/image") {
	contents = try? String(contentsOf: url)
 } else {
 	contents = nil
 }

 // or like this with optional argument chaining:
 let contents1 = try? URL(string: "/url/to/image").flatMap(String.init(contentsOf:))

 

let image: UIImage?
if let url = URL(string: "https://apple.com/favicon.ico"),
   let data = try? Data(contentsOf: url)
{
    image = UIImage(data: data)
} else {
    image = nil
}

// alternative with optional chaining:
let image1 = URL(string: "https://apple.com/favicon.ico")
             .flatMap{ try? Data(contentsOf: $0) }
             .map(UIImage.init(data:))
// flatMap usage is like that because otherwise compiler is not smart enough to use `Data(contentsOf:options)`
// with default second parameter.

 

TODO: write to swift forums question if this could be emproved in Swift.



Saturday, September 19, 20: TIL what’s new in Swift 5.3; Better Git Workflow with Rebase

Read release notes Swift 5.3 released!.

Watched A Better Git Workflow with Rebase and Git MERGE vs REBASE.



Friday, September 18, 20: TIL abount Danger for Swift

Learned about Danger which could automatically improve PR reviews.

Read Getting started with GitHub Sponsors. Applied from here Fund your work. Build what matters.. Now my profiles waits for approval. Applying took less then an hour.

Bookmarking The Complete Guide to iOS and Swift Job Interviews.



Tuesday, September 15, 20: Read Apple’s recent blog post Managing Model Data in Your App

Read Apple’s recent blog post Managing Model Data in Your App.



Monday, September 14, 20: TIL difference between class and static members in Swift; what is redacted view

Watched Point Free episode #115 █████ed SwiftUI: The Problem. Very interesting. Now I know what is redacted view.

Today I was asked about class and static members in Swift and the difference. I didn’t know about the difference. That why I checked that after interview. What’s the difference between a static variable and a class variable?:

Where static and class differ is how they support inheritance: When you make a static property it becomes owned by the class and cannot be changed by subclasses, whereas when you use class it may be overridden if needed.



Saturday, September 12, 20: Watched a bunch of Tips and Tricks in Cocoacast

Watched Building Reactive Applications With Combine What Is Reactive Programming, then Combine First-Class Functions and Function Types and Pure Functions and Higher-Order Functions. Nothing new in either.

Watched Tips and Tricks: Removing String Literals, then Using a Branching Strategy That Works. Nothing new in both.

Watched Tips and Tricks: Using didSet Property Observers to Configure Outlets. Completely makes sense!

Watched Why You Should Default to Private Outlets. Obvious.

Watched Five Simple Tips to Improve the Code You Write. The first tip suggesting using switch instead of if statement with boolean condition I find stupid. The rest tips make sense.

Watched Ten Xcode Tricks Every Developer Should Know. Tip of showing callers in assistant editor is useful.

Watched Managing Build Configurations in Xcode. This is extremely useful!



Friday, September 11, 20: TIL unsafelyUnwrapped in Swift

Watched WWDC 2020 session video Unsafe Swift. Learned:

  • unsafelyUnwrapped exists and could be used like: print(optionalInt.unsafelyUnwrapped). In optimised builds it doesn’t check optional for being not nil like force unwrap is doing. In debug builds it behaves like force unwrap.

  • in most cases withUnsafeMutablePointer and alike are not needed when interoperating with C APIs. Swift arrays and strings could be used directly, - compiler generates necessary code. I havn’t known that.

Watched WWDC 2020 session video Safely manage pointers in Swift.

Read Guarantee (in-memory) tuple layout…or don’t.

Read What’s new in CryptoKit.

Watched Apple’s employee talk at dotSwift 2020 Cryptography in Swift. TL;DR: it’s about Swift Crypto which is opensource implementation of closedsource CryptoKit.

Read Peter Steinberger’s blog post Logging in Swift. Mostly about accessing log from device programmatically on iOS 14.

Browsed Introducing Swift Cluster Membership. Great that Swift is get widely used on server side!



Thursday, September 10, 20: TIL how Swift imports C APIs

Read Swift’s How Swift imports C APIs. This is new for me:

C (and C++) permit non-ASCII Unicode code points in identifiers.

In C, every type has a size (computed with the sizeof operator), and an alignment (computed with alignof).

I missed existence of alignof. Curious since when it exists.

Swift tracks the exact size of the data stored in a type so that it can pack additional data into bytes that otherwise would be wasted as padding. Swift also tracks possible and impossible bit patterns for each type, and reuses impossible bit patterns to encode more information.

This example is interesting:

// This enum takes 1 byte in memory, which has 256 possible bit patterns.
// However, only 2 bit patterns are used.
enum Foo {
  case A
  case B
}

print(MemoryLayout<Foo>.size) // 1
print(MemoryLayout<Foo?>.size) // also 1: `nil` is represented as one of the 254 bit patterns that are not used by `Foo.A` or `Foo.B`.

 

Swift’s integer and floating point types have fixed size, alignment and stride across platforms, with two exceptions: Int and UInt.

This 👆🏻 is not new, but for the fist time I see this so clearly and briefly formulated.

Hm, from table of matching C/C++ and Swift types I see possible problem. E.g. C’s short, signed short match to Swift’s typealias CShort = Int16. That might be problematic as C guarantees only that size of int is greater or equal to the size of short. So might be cases when C’s short values doesn’t fit into Swift’s matching CShort. So might exist valid portable C code which can’t work properly with Swift. TODO: check if Swift has diagnostic about this.

It has so good explanation matching C and Swift pointer types!!! The best I have seen so far! I will refer and use it!

It’s completely new for me how plain C enum’s are imported into Swift - as struct’s! And only if C’s enum’s are annotated with Clang’s __attribute__((enum_extensibility(closed))) or __attribute__((enum_extensibility(open))) they are imported into Swift as enum’s. Objective-C enums declared with NS_ENUM were assumed to have “enum nature” and were imported as Swift enum’s.



Monday, September 07, 20: Watched Mastering MVVM With Swift, What Are Self-Executing Closures Tips and Tricks

Watched Mastering MVVM With Swift: How Does the Model-View-ViewModel Pattern Work.

Learned what is called self executing closure Tips and Tricks: What Are Self-Executing Closures. Sure, concept isn’t new. I just haven’t known how it’s called. But some ideas of how it could be used are new.

Came across Writing A Generic Stable Sort. I feel I was already there.

Digging in Swift stdlib sources have found how UTF8 is accessible despite it’s declared in Unicode:

public typealias UTF8 = Unicode.UTF8
public typealias UTF16 = Unicode.UTF16
public typealias UTF32 = Unicode.UTF32


Saturday, September 05, 20: Read Learning Dependency Injection using Swift

Read Learning Dependency Injection using Swift.



Wednesday, August 26, 20: TIL how to Spot Toxic Software Jobs From Their Descriptions

Bookmarking that ArraySlice implementation in Swift has performance TODO which I could probably fix.

Read extremely interesting and relevant post How to Spot Toxic Software Jobs From Their Descriptions.



Sunday, June 21, 20: TIL about enhancements to Quick Look on iOS and macOS

Watched WWDC 2019 Session.



Tuesday, February 18, 20: TIL Snoop CLI for OSINT

Recent finding - cli snoop Snoop project - incredible tool for OSIMT (Open-source intelligence) (russian).



Monday, February 17, 20: TIL Speech Framework

Read Recognizing Speech Locally on an iOS Device Using the Speech Framework.

Found with sad that video WWDC 2014 Session 235: Advanced Scrollviews and Touch Handling Techniques isn’t available anymore.



Saturday, February 15, 20: TIL NSDoubleLocalizedStrings

Googled for NSDoubleLocalizedStrings and have found on stackoverflow.



Friday, February 14, 20: TIL CIContext is heavy and should be reused

Learned from Core Image Programming Guide that CIContext is heavy and should be reused.

Read again Podfile Syntax Reference. How I hate Cocoapods documentation!

I should definately turn this my Swift script into such app AssetsGenerator for Xcode.

Read Signal Processing and Dynamic Time Warping. It has a lot of interesting material, far more then DTW.



Wednesday, February 12, 20: TIL how to bypass numerical noised captcha with neural net on tensorflow, keras and python

Bookmarked How to bypass captcha: neural net on tensorflow, keras, python vs numerical noised captcha (russian). And follow up by another author Captcha, special case: tear apart neural net with 30 lines of code (russian).



Tuesday, February 11, 20: TIL how to build a Synthesizer in Swift; how to detect beats with AudioKit

Bookmarking Building a Synthesizer in Swift which is a follow up of WWDC 2019 session video 510 What’s New in AVAudioEngine. Post is focusing on how the newly announced AVAudioSourceNode can be used to build a musical synthesizer for iOS. Post references complete git repo and Apple sample Building a Signal Generator.

Shortly looked into git repo of Audio Kit Synth One available in the App Store. Here’s more info about the app.

Googling about beat detection with AudioKit came across post Exploring music basics with AudioKit.

How does Shazam work? Music Recognition Algorithms, Fingerprinting, and Processing.

Interesting post from author of Core ML Survival Guide book Upsampling in Core ML.

Tip: At the end of this post there is a handy cheatsheet that lets you look up which Core ML layer to use with your TensorFlow / Keras / PyTorch models.



Monday, February 10, 20: TIL dynamic time warping algorithm

Learning dynamic time warping algorythm. In Ukrainian it is called Алгоритм динамічної трансформації шкали часу.

Watched 5 times How DTW (Dynamic Time Warping) algorithm works, than three times Dynamic Time Warping. The last is much better and explains how to handle signals of different lengths.

Read Dynamic Time Warping with Time Series.

Googling for Dynamic Time Warping accidentally have found Speech recognition for dummies (russian). Post of noob for noobs. But I find it interesting. It has:

  • explanation of .wav file format;
  • how detect periods of silence in sound calculating signal entropy;
  • what Mel-frequency cepstral coefficients are and how to calculate them.

Read interesting post Video with cloud based object detection of Raspberry Pi (russian).



Friday, February 07, 20: TIL Xcode source editor extensions

Special class of apps, Xcode source editor extensions, exist in the mac app store. There’re even paid ones like pretty json formatter. Good to know that!

Here’s tutorial how to create them: Xcode Source Editor Extension Tutorial: Getting Started.

Read NSHipster post on topic XcodeKit and Xcode Source Editor Extensions. It also describes the process of creation of extension.

TODO: watch WWDC 2016 session 414 video Using and Extending the Xcode Source Editor.

Read another NSHipster post RawRepresentable. WTF? enum in Swift can have both raw value and associated value???

Read Objective-C Direct Methods. And linked documentation Using Imported Lightweight Generics in Swift.

Read what is database sharding. Mostly accidentally, not because I needed that.

Learned how to use repo on local machine for CocoaPod. Related post Development Pods. And another similar one Working with CocoaPods Lib Locally. And related CocoaPods documentation .

Read The Illustrated Transformer russian translation. very interesting reading. A lot of illustrations.



Thursday, February 06, 20: TIL binary or octal literal in Swift; rounding in Swift; shell script to run some cli on every file matching pattern

Spend more than an hour for writing simple shell script to run some cli on every file matching pattern:

for file in *.pcm; do
   fromescaped=$(printf '%q' "$file")
   to="$(basename "$file" .pcm).wav"
   toescaped=$(printf '%q' "$to")
   #echo $cmd
   cmd="ffmpeg -f f32le -ar 16000 -ac 1 -y -i $fromescaped $toescaped"
   eval $cmd
done

Had to google how to write binary or octal literal in Swift:

let decimalInteger = 17         // 17 in decimal notation
let binaryInteger = 0b10001     // 17 in binary notation
let octalInteger = 0o21         // 17 in octal notation
let hexadecimalInteger = 0x11   // 17 in hexadecimal notation

Learned about rounding in Swift:

let f: Float = ...
_ = f.rounded() // rounds to closest integral value, same as 'rounded(.toNearestOrAwayFromZero)''
_ = f.rounded(.toNearestOrAwayFromZero) // equivalent to the C 'round' function
_ = f.rounded(.towardZero) // equivalent to the C 'trunc' function
_ = f.rounded(.up) // equivalent to the C 'ceil' function
_ = f.rounded(.down) // equivalent to the C 'floor' function


Wednesday, February 05, 20: TIL how to persist business logic with Swift Combine

Read From ground to FPV drone: introduction (russian). Will return to it later.

Todo: I should definitely create playground for various pointers:

Swift                               C
UnsafePointer<T>              const T&ast;

UnsafeRawPointer              const void&ast;

UnsafeMutablePointer<T>          T&ast;

UnsafeMutableRawPointer          void&ast;

UnsafeMutableBufferPointer

Read Control UI with gestures (Keras + CoreML)(russian). Simple guide. I should follow it.

Bookmarking Persist Business Logic With Swift Combine.



Tuesday, February 04, 20: TIL how to list branches in git ordered by date of the last commit; saturation arithmetic

Learned how to list branches in git ordered by date of the last commit git branch --sort=-committerdate.

Reading Adieu, Quake! (russian translation Porting Quake on iPod Classic) have firstly met term saturation arithmetic. Now it look strange for but I have never ever used or even heard of saturation arithmetic. Here I had no other choice as googling and here some results: wiki: Saturation arithmetic (curious - neither Russian nor Ukrainian version), Stackoverflow: How to do unsigned saturating addition in C?.



Wednesday, January 29, 20: TIL how to call C functions from Python and how to pass pointers

Learned how to call C functions from Python. This simple example worked well for me as starter. More trickier was to guess how to pass pointers to C functions from Python. This documentation was handy A foreign function library for Python.



Tuesday, January 28, 20: TIL that Apple’s documentation for BLAS has bugs

Today I faced a problem of making portable C code using matrices multiplication. Target - use same C code on preprocessing before Neural net on iOS and on training in Python on Ubuntu. On iOS vDSP was used for matrices multiplication which is not available on Ubuntu. But iOS have BLAS port where matrix operations also available. BLAS exists nearly on every platform. Here I faced a problem with making cblas_dgemm working properly. Assert inside fired saying that parameter 9 was incorrect on entry to cblas_dgemm. But call was so simple and documentation so straightforward… An hour of googling have shown that Apple documentation was wrong. Apple documentation clearly says:

ldb The size of the first dimension of matrix B; if you are passing a matrix B[m][n], the value should be m.

So it looks like ldb should match with the first dimension of matrix B. No.

Example Multiplying Matrices Using dgemm from documentation on Intel’s port of BLAS is much clear in this regard:

Leading dimension of array B, or the number of elements between successive rows (for row major storage) in memory. In the case of this exercise the leading dimension is the same as the number of columns.

Because I use C-arrays where rows go first ldb parameter should be second dimension of matrix B, not this first! And this worked for me. Shame on Apple!

Filed a bug for this on 13 of April 2023. Feedback id for this bugreport is FB12116665.

TODO: give answers on stackoverflow.



Friday, January 24, 20: TIL in Swift unsafeBitCast(_:to:), type(of:), withoutActuallyEscaping(_:do:), ‘OpaquePointer’, MemoryLayout, offset(of:), AutoreleasingUnsafeMutablePointer

While exploring pointer stuff in Swift read about unsafeBitCast(_:to:) but acually I read declarations inside Xcode. As always it’s extremely interesting to read in Swift source code in Xcode because there you always see real declarations along with related stuff.

Then jumped to type(of:) where I barely understood second part about generic context.

Then jumped to withoutActuallyEscaping(_:do:).

Then jumped to ‘OpaquePointer’. That’s simple:

Opaque pointers are used to represent C pointers to types that cannot be represented in Swift, such as incomplete struct types.

Then jumpled to MemoryLayout. Everything is clear but this is a little obscure:

Always use a multiple of a type’s stride instead of its size when allocating memory or accounting for the distance between instances in memory.

Hm, I didn’t know that type’s alignment should be used when allocating memory using an unsafe pointer. But when accessing memory stride should be used.

And offset(of:) is something I don’t fully understand.

Found out strange thing which I have never met in wild AutoreleasingUnsafeMutablePointer:

This type has implicit conversions to allow passing any of the following to a C or ObjC API:

  • nil, which gets passed as a null pointer,

  • an inout argument of the referenced type, which gets passed as a pointer to a writeback temporary with autoreleasing ownership semantics,

  • an UnsafeMutablePointer<Pointee>, which is passed as-is.



Thursday, January 23, 20: TIL memory command of lldb, UnsafeMutablePointer initialization in Swift

Stack overflow question How to compare two UIImage objects might be very good example when wrong question is highly voted up. Would be great if I find time and write longread answer to question.

Example snippet in vdsp_vsadd is not consistent as it doesn’t declare variable stride. Filed a bug with feedback id FB12116721 on 13 of April 2023. Full fixed snippet should look like:

let a: [Float] = [1, 2, 4, 5]
let stride = 1
var b: Float = 2

let n = vDSP_Length(a.count)

var c = [Float](repeating: 0,
                count: a.count)

vDSP_vsadd(a, stride,
           &b,
           &c, stride,
           n)

// Prints "[3.0, 4.0, 6.0, 7.0]"
print(c)

SWIFT MEETUP QUESTION: Several questions to above snippet:

  • why can’t b be declared as let if appropriate parameter of vDSP_vsadd is declared as UnsafePointer<Float>? Xcode complains something stupid Cannot pass immutable value as inout argument: 'b' is a 'let' constant. Appropriate parameter of vDSP_vsadd isn’t inout:

func vDSP_vsadd(_ __A: UnsafePointer<Float>, _ __IA: vDSP_Stride, _ __B: UnsafePointer<Float>, _ __C: UnsafeMutablePointer<Float>, _ __IC: vDSP_Stride, _ __N: vDSP_Length)

  • what happens under the hood when a which is [Float] is passed to parameter of type UnsafePointer<Float>;

  • why in last case a might be let if here parameter also has type UnsafePointer<Float>.

This week every second day I look here for memory command in Xcode. Actually memory read -t float -c50 spectrogram is what I have looked for. I tried help memory read. Firstly, remembering help whateveryouhavetroublewith I don’t have remember exact syntax anymore. Second, I am shocked how powerful command memory is. It could even store output into a file!

It’s very useful to look into Swift declaration of UnsafeMutablePointer. It has a lot of information not available anywhere else.

You declare pointer. In Swift it can’t be uninitialised. How would you initialise it, let’s say, with NULL how C understands that.

// Compiler swallows this.
// But if you chech type of p1 it's UnsafeMutablePointer<Float>? which is not what we want.
var p1 = UnsafeMutablePointer<Float>(nil)

But if you stop and think for a moment you start to suppose that probably there’s no such thing as NULL pointer in Swift.



Wednesday, January 22, 20: TIL std::log2p1() calculates binary logarithm and adds 1 which is number of bit needed for storing argument

Post Naming Things: Implementer vs. User Names raises interesting question about choosing convinient name for functions.

E.g. std::log2p1() function calculates binary logarithm and adds 1, but for 0 returns zero. Is it useful? It is. It calculates number of bit needed for storing argument, but just looking at the name doesn’t really make it apparent.

Didn’t know there’s CPU instruction popcount doing exact that:

The population count (or popcount) of a specific value is the number of set bits in that value. For example, the population count of 0F0F₁₆, 111116₁₆, and 00₁₆ are 8₁₀, 4₁₀, and 0₁₀ respectively.

It’s interesting popcount is actually a Hamming weight of a word.

Learned that stride parameter in some vDSP functions might be strange, like in vDSP_polarD(_:_:_:_:_:) when stride parameneter must be even.



Saturday, January 18, 20: TIL a lot about unsafe Swift

Watched 4 Design Patterns for RESTless Mobile Integration.

Unsafe Swift: Using Pointers And Interacting With C.

Swift’s Pointy Bits: Unsafe Swift & Pointer Types by Nate Cook.

Unsafe in Swift.

Apple docs UnsafePointer.

Swift forums Unsafe Functions.

Swift forums Swift Pointer Syntatic Sugar.

Pointers in Swift.

Swift Tip: OpaquePointer vs. UnsafePointer.

Proposal UnsafeRawPointer API for In-Memory Layout.

How can I convert data into types like Doubles, Ints and Strings in Swift?.

Round trip Swift number types to/from Data.

Building smart Q&A app with CoreML, SwiftUI, and Combine.

Object Detection Guide

Advancements in Apple’s Vision Framework: 2019 Year-in-Review.



Friday, January 17, 20: TIL Swift is not faster than C++ as many think

Evidence Based Scheduling.

What are similarities and differences between C++ and Swift?.

Oh, I will show this to ones which tell Swift is faster then C++:

Like C++, Swift puts a high premium on performance. In practice, however, it’s not quite in the league of C++ or even Rust.

Vapor – Deep Dive Guide into Setup and Deployment for Heroku and Ubuntu.

TODO:



Wednesday, January 15, 20: TIL object initialization in Objective-C

Today I had to write convinience initializer for MLMultiArray. I thought that dealing with memory buffers and pointers will be in Objective-C. But I forgot how to do it. What signature should be? Should I annotate instancetype with __nullable for failing initializer? What about calling super? Do I have to call super if I assign new instance to self. So I googled for help. What does it mean when you assign [super init] to self? - ten years old post by Matt Gallagher. Interesting updated conclusion at the end:

Update: I have rewritten this conclusion to reflect the fact that I’m not actually suggesting you should stop using “assign [super init] to self” initializers. Thank you to everyone who invented creative ways to tell me I was wrong about this implication.

Read Object Initialization chapter in Apple’s Concepts in Objective-C Programming documentation.



Tuesday, January 14, 20: Read Five tips to write better todos in Xcode

Bookmarking iOS conference calendar 2020.

Interesting reading What I’ve learned after sending 147 proposals to 36 conferences in a year by Vadim Drobinin.

Five tips to write better todos in Xcode.



Saturday, January 11, 20: Read Round trip Swift number types to/from Data

Read New Diagnostic Architecture Overview. Understood very little. Got that soon to be released Swift 5.2 will have much better diagnostic.

I should play in playground on this stackoverflow answer Round trip Swift number types to/from Data. Very good and detailed answer!



Friday, January 10, 20: Read Advancements in Apple’s Vision Framework: 2019 Year-in-Review; Swift’s String Manifesto

Tried to play with Tutorial Create images from rectangular shapes in the user’s environment, and augment their appearance. referenced in Fritz AI mail list. But CoreML model is missing there.

Read Advancements in Apple’s Vision Framework: 2019 Year-in-Review.

Read String Manifesto. Despite it’s old, Swift 4, it’s interesting.

Despite its name, CharacterSet currently operates on the Swift UnicodeScalar type. This means it is usable on String, but only by going through the unicode scalar view. To deal with this clash in the short term, CharacterSet should be renamed to UnicodeScalarSet. In the longer term, it may be appropriate to introduce a CharacterSet that provides similar functionality for extended grapheme clusters.

Working on new release of Motivation, read NSHeapster’s DateComponents.



Thursday, January 09, 20: TIL how to convert images to MLMultiArray

Read Why do we use Story Points for Estimating?.

Read Number plates recognition. Practical manual. Part 1. (russian). Fuuuuck. Ukraine opened data of registered autos Register about vehicles and their owners. Comment to the post has a lot of useful links. Read Number plates recognition. How we achieved 97% accuracy for ukrainian number plates. Part 2. (russian).

Read Core ML and Combine by Matthijs Hollemans.

Read How to convert images to MLMultiArray by the same author. Unexpectedly interesting and might be useful soon.



Wednesday, January 08, 20: TIL something new in C++; how create a Command-Line Tool Using Swift Package Manager

Read Intriguing C++20 capabilities for embeded developers.

Read New operator spaceship in C++20 (Russian). Didn’t get it.

Read Comparisons in C++20. Didn’t get either. But I like used Carte Noire them for Jekyll.

Read Create a Command-Line Tool Using Swift Package Manager.

Today I asked on interview what protocol oriented programming is. Then I tried to google how other flormulate this. Here is Paul Hudson’s post What is protocol-oriented programming?. Nice header but post itself doesn’t have answer to questeion in header.

Played with number plates detection online Nomeroff Net Online Demo. Project’s home page which has full code, link to datasets.



Friday, January 03, 20: TIL how to copy a file from one place to another with showing progress

Learned how to copy a file from one place to another with showing progress: rsync --progress /copy/from /copy/to.

Read post How I have created my own deepfake in two weeks spending 552$ (russian).



Thursday, January 02, 20: TIL about implementing throwing protocol functions as non-throwing in Swift

Read John Sundell’s Implementing throwing protocol functions as non-throwing.

Read Initializers in Swift by the same author.



Wednesday, January 01, 20: TIL Publish - a static site generator built specifically for Swift developers

Read about Publish - a static site generator built specifically for Swift developers.



Monday, December 23, 19: TIL about faster Array operations with CollectionOfOne in Swift

Read Faster Array Operations With CollectionOfOne in Swift. Nothing new. Side learning: i..<i is valid range. Empty one.

Looking at implementation of insert(_:, at:) I am thinking if would it be more effective to add specialised version for replacing subrange with single element instead of creating CollectionOfOne:

public mutating func insert(_ newElement: __owned Element, at i: Int) {
    _checkIndex(i)
    self.replaceSubrange(i..<i, with: CollectionOfOne(newElement))
}

Passed the first week of Coursera’s Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning.



Saturday, December 21, 19: Read issue #150 of Swift Weekly Brief

Read issue #150 of Swift Weekly Brief.



Tuesday, December 17, 19: TIL Google Dataset Search; Registry of Open Data on AWS

Hanged a little on post 25 datasets for educational projects. Spent some time on Coco - it has very nice explore feature. The Chars74K dataset might be useful as well. Objects365 is promising: is has traffic signs category which I should try. Baidu Apolloscape Dataset has several datasets one of each has traffic signs.

Google has Google Dataset Search.

Amazon has Registry of Open Data on AWS which exists to help people discover and share datasets that are available via AWS resources.

There’s Russian Traffic Sign Dataset with dataset itself available by link. I have to explore this data set.

TODO: continue with repo RTSD because it has what I could reuse.



Sunday, December 15, 19: Read The Advanced Guide to UserDefaults in Swift

Read The Advanced Guide to UserDefaults in Swift. Side learning: I didn’t know __PRETTY_FUNCTION__ exists.



Tuesday, December 10, 19: Read Access Control and Inheritance from Swift documentation

10 Dec 2019 Tuesday

Started day with reading again chapter Access Control of The Swift programming language manual.

A module is a single unit of code distribution—a framework or application that is built and shipped as a single unit and that can be imported by another module with Swift’s import keyword.

Each build target (such as an app bundle or framework) in Xcode is treated as a separate module in Swift.

Read chapter Inheritance of The Swift programming language manual.



Monday, December 09, 19: Read about measuring code execution time on iOS; how KVO in Swift works

Read UITableView Swipe Actions in iOS 11. Somehow I did miss this. UITableView Leading & Trailing Swipe Actions in iOS 11 on the same topic mentions tableView(_:editActionsForRowAt:) existing since iOS 8.

Needed to measure execution time of some part of code googled for function CACurrentMediaTime() because I didn’t remember its name. But beware it doesn’t work when device sleeps! CFAbsoluteTimeGetCurrent() worth mentioning as well.

Read how to use KVO in Swift Observing properties with Key-Value Observing because my colleagues use it. But it’s time to start using Combine.

Read chapter Access Control of The Swift programming language guide.



Thursday, December 05, 19: Read about Iterator design pattern in Swift universe

Read Building a Face Detecting Robot with URLSessionWebSocketTask, CoreML, SwiftUI and an Arduino.

Read Iterator design pattern in Swift. I’ve never implemented this pattern directly.

Read Iterator design pattern in Swift universe.



Wednesday, December 04, 19: Read How OptionSet works inside the Swift Compiler; Useful obscure Foundation types in Swift

Read How OptionSet works inside the Swift Compiler.

Read Useful obscure Foundation types in Swift: Scanner, NSCountedSet (funny that example uses isAnagram which I use in interviews), CFTree, CFBinaryHeap, NSCache, NSOrderedSet, ByteCountFormatter, NSDataDetector. Nothing new.



Tuesday, December 03, 19: Read about serialization in Swift; State restoration in iOS 13; Type Casting in Swift; Checking for Protocol Conformance in Swift; Key words for use in RFCs to Indicate Requirement Levels; Thoughts on iOS Architecture

Read A first look Apple’s iPadOS multi-tasking improvements.

Read Object serialization in iOS - a systematisation of different formats and types of data serialization in iOS development. Learn then PropertyListEncoder exists along with JSONEncoder.

Read Serialization of enum with associated type. Nothing new. But should practice with it because each time I ran into this I have to google how to do this.

Bookmarking: Siri Shortcuts Practical Tips and Siri Intents.

Read about State restoration in iOS 13. Apple has good Sample Code Restoring Your App’s State.

Read The Swift programming language manual chapter Type Casting.

Side learning:

  • Any can represent an instance of any type at all, including function types.

  • AnyObject can represent an instance of any class type.

Read Checking for Protocol Conformance.

Read Key words for use in RFCs to Indicate Requirement Levels. SHOULD means RECOMMENDED. Good to know.

Read Thoughts on iOS Architecture



Monday, December 02, 19: TIL how to make xcode project file from cmake

Googled how to make xcode project file from cmake: CMake Tutorial – Chapter 2: IDE Integration. This should remember:

cmake -G "Xcode"

This lists all the targets and all the build configurations set up in the Xcode project:

xcodebuild -list

This runs building:

xcodebuild

Interesting to know Google maintains ios-cmake.

Interesting info on topic: How to include a CMake project in a Xcode project.



Friday, November 29, 19: TIL some new stuff on Swift Alps 2019 second day ⛷

Session 1 Swift for TensorFlow. By Paris Buttfield-Addison. Second workshop here.

Session 2 Audio Synthesis. By Adam Bell. Presentation is here. It was about AudioKit. Demo project is here, based, sure, on AudioKit. Nonetheless, interesting. Could I do same workshop. Sure I could! Firstly, more low-level with really generating sound, filling in buffer and playing it. Second, could do some Fast Fourier Transform staff. Could even combine this with Neural network stuff.

Session 3 SwiftUI. By Lea Marolt Sonnenschein. There’s repo, inside there’s file Instructions.



Thursday, November 28, 19: TIL some new stuff on Swift Alps 2019 first day ⛷

Session 1 Practical AI for iOS. By Mars Geldard. The first workshop mentioned here. Got a book Practical Artificial Intelligence with Swift. There is repo with all activities. iOS app which replaces faces in photos with emojis was interesting. All stuff was quite interesting and useful.

Session 2 Frameworks. By Cecilia Humlelu from Spotify. There’s kind of tutorial for workshop Building Hybrid Frameworks. I was skeptical about it because all workshop was just following this tutorial. But later I found out it is very practical. Sure I will return to this tutorial later and run it multiple times.

Session 3 Combine. By Florent Pillet. Here’s repo for workshop. Can’t say workshop was too much practical or useful. Hope it will work like kick-off.



Tuesday, November 26, 19: TIL isContinuous property of UISlider

Didn’t know method isContinuous exists in UISlider.



Monday, November 25, 19: TIL again Changes in the ViewController Presentation Style on iOS 13

Read View Controller Presentation Changes in iOS 13. Worth bookmarking.

Interesting pos of same author iPad Navigation Bar and Toolbar Height Changes in iOS 12.

iPad Navigation Bar height now 50…

Here is the app developer refers to in it’s posts. Great idea! And nice developer doesn’t shy to charge 3.99$ for it. Bought it. For 3.99£ in my case.

Short post Multi-window development in iPadOS.

Long read Inside Apple’s iPhone Software Shakeup After Buggy iOS 13 Debut.

Introducing the Apple Developer App:

Starting today, the WWDC app is now the Apple Developer app and delivers in-depth information from Apple experts all year round. Stay up to date with the latest developer news, informative videos, WWDC content, and more.

And this is thrilling:

Developers in the U.S. can also use the app to conveniently enroll in the Apple Developer Program on iPhone or iPad, with enrollment in additional countries and regions becoming available over time. And since membership is provided as an auto-renewable subscription, keeping your account active is easy.

Premium iOS App Templates is brilliant idea of making money!

Read Thread Sanitizer explained: Data Races in Swift. Nothing new.

Read How To Build UI and Transitions Programmatically Without SwiftUI. It’s not what title suggests. It’s just about how to make an app without storyboard.

Read What a Designer Needs to Know about iOS Dark Mode When Working with a Developer. According to Apple documentation:

developers or designers should use semantic colors whenever it is possible so that their app will be future-proof with any UI changes made by Apple.

To read more about how or when to use semantic colors, you can refer to the Apple documentation.

Side learning:

Prior to iOS 13, there is only 1 type of blur and vibrancy effect. In iOS 13, Apple introduced 4 types of blur effects and 8 types of vibrancy effects. As you might have guessed, all these visual effects will automatically adapt to iOS interface style.

Another reminder about SF:

SF Symbols are a collection of over 1500 symbols provided by Apple for designers and developers to use within their apps. As mentioned in iOS Human Interface Guidelines, SF Symbols automatically look great in Dark Mode and they are optimised for both light and dark appearances. Therefore, Apple highly recommend everyone to use SF Symbols whenever it is possible.

In conjunction with the release of iOS 13, Apple also released Xcode 11. By using the asset catalog in Xcode 11, developers can now create custom image and color group that specify what color and image to be shown in light and dark appearance.

But. How to that without Asset catalog in cases where you can’t use one, like when you build static library??? That might be Swift meetup question.

Apple has locked me out of my developer account. As story.

Side not from a sad story above. It’s an app from that developer ChibiStudio. I could easy do something like that with Kris making drawings.

Read Navigation Bar Customisation. Part 1 - The Basics. and Navigation Bar Customisation. Part 2 - UINavigationBarAppearance and proper view/model separation.. The first part is pure gold explaining in details how to customise different parts of navigation part. The second part mentions what iOS 13 brings us - new UINavigationBarAppearance for helping customise what was done poor in previous iOS versions. UINavigationBarAppearance is not the only one of its kind. It inherits all the general bar customisation functionality from its parent UIBarAppearance and shares it with the siblings: UIToolbarAppearance and UITabBarAppearance.

By the way, that blog is nice example of Jekyll with theme so-simple-theme.



Saturday, November 23, 19: TIL Changes in the ViewController Presentation Style on iOS 13

Read iOS 13: Changes in the ViewController Presentation Style. Condensed. Very short. But not full. What learned?

You must set the modalPresentationStyle property of the view controller that will be presented. If you want to present a navigation controller which contains a view controller, the navigation controller that will be presented must have set the property modalPresentationStyle, instead of the view controller that will be visible.

The code example below makes it clearer how to deal with the presentation style when presenting a navigation controller:

let detailVC = DetailViewController()
let navigationController = UINavigationController(rootViewController: detailVC)
navigationController.modalPresentationStyle = .fullScreen
present(navigationController, animated: true)

Watched Introducing Multiple Windows on iPad.

Watched WWDC 2019 Session 224 video Modernizing Your UI for iOS 13.

Watched WWDC 2019 Session 246 Window Management in Your Multitasking App.

Being iPad user I don’t use these features a lot. That why I had to re-watched Apple iPad Slideout Multitasking Demo at WWDC 2015. This video from Apple support is useful as well How to multitask with Split View on your iPad — Apple Support.

Watched old WWDC 2015 Session 205 Getting Started with Multitasking on iPad in iOS 9. New learned:

  • UIView.readableContentGuide;

  • Window of correct size used by app now could now be created with UIWindow() instead of UIWindow(frame: UIScreen.main.bounds).

Apple in the last video recommends to follow with Adopting Multitasking Enhancements on iPad chapter of iOS programming guide and with sample code AdaptivePhotos: Using UIKit Traits and Size Classes.

TODO: run this tutorial about building CCTV on raspberry Pi.



Friday, November 22, 19: TIL how to update Private CocoaPods

Learned how to update Private Pods and How to Update your CocoaPods Library Version.



Thursday, November 21, 19: Read Advanced Operators chapter of The Swift programming language

Read Advanced Operators chapter of The Swift programming language.

By link jumped to quite old NSHipster post Object Subscripting.

Reading about @objc and @objc(name) jumped to Attributes chapter of The Swift programming language.

It’s interesting that page by link above links to Programming with Objective-C.

Read Subscripts chapter of The Swift programming language.

Subscripts are not limited to a single dimension, and you can define subscripts with multiple input parameters to suit your custom type’s needs.



Wednesday, November 20, 19: Read about nested types in Swift

Read Section Nested Types of The Swift programming language. Nothing new.



Tuesday, November 19, 19: Read Properties chapter of The Swift programming language

Read Properties chapter of The Swift programming language. Easy? Even here I have found something new:

struct Point {
    var x = 0.0, y = 0.0
}
struct Size {
    var width = 0.0, height = 0.0
}
struct Rect {
    var origin = Point()
    var size = Size()
    var center: Point {
        get {
            let centerX = origin.x + (size.width / 2)
            let centerY = origin.y + (size.height / 2)
            return Point(x: centerX, y: centerY)
        }
        set(newCenter) { // <- dodn't know it's possible here
            origin.x = newCenter.x - (size.width / 2)
            origin.y = newCenter.y - (size.height / 2)
        }
    }
}

This is interesting note:

If you pass a property that has observers to a function as an in-out parameter, the willSet and didSet observers are always called. This is because of the copy-in copy-out memory model for in-out parameters: The value is always written back to the property at the end of the function. For a detailed discussion of the behavior of in-out parameters, see In-Out Parameters.

Section Property Wrappers is quite interesting as well. And this is new for me Projecting a Value From a Property Wrapper. Understood very little.

In section Global and Local Variables see clearly stated first time:

The capabilities described above for computing and observing properties are also available to global variables and local variables.

Subsection Type Property Syntax of section Type Properties is also bring something new:

You define type properties with the static keyword. For computed type properties for class types, you can use the class keyword instead to allow subclasses to override the superclass’s implementation.

Hm, from that could be good interview question.

Read Methods chapter of The Swift programming language.

Same finding with class and static keywords for type method like for type properties:

You indicate type methods by writing the static keyword before the method’s func keyword. Classes can use the class keyword instead, to allow subclasses to override the superclass’s implementation of that method.

Neither of chapters explains how to call type property or method having instance. It’s expecially interesting to know how it works in case of override (classes only). Are all ovverides in chain get called? What’s called if overritten property (or function) is called when instance is casted to base class? Which versions get called?



Saturday, November 16, 19: Watched again WWDC 2016 session video Unified Logging and Activity Tracing

Watched again WWDC 2016 session video Unified Logging and Activity Tracing.



Friday, November 15, 19: TIL URLSession in iOS 13 already supports WebSockets

From last Vapor Meetup in Berlin have learned that URLSession in iOS 13 already supports WebSockets. Here follow up reading WebSockets in iOS Using Swift, WebSockets in iOS 13 Using Swift and Xcode 11.



Thursday, November 14, 19: Read Memory Safety, Deinitialization, Strings and Characters chapters of The Swift programming language

Read again Memory Safety chapter of The Swift programming language, then chapter Deinitialization, then Strings and Characters. Some details of Multiline String Literals slippered from my mind:

// `multilineString` doesn't have line breaks
let multilineString = """
These are the same.
"""
// Multi line literal could have \ at end of each line meaning it will be no new line there 
let softWrappedQuotation = """
The White Rabbit put on his spectacles.  "Where shall I begin, \
please your Majesty?" he asked.

"Begin at the beginning," the King said gravely, "and go on \
till you come to the end; then stop."
"""

This shows strings are tricky collections:

// Concatenating two strings of length 1 creates a string of length 1
let combinedEAcuteS1: String = "\u{65}"         // e
print(combinedEAcuteS1, combinedEAcuteS1.count) // e 1
let combinedEAcuteS2: String = "\u{301}"        //  ́
print(combinedEAcuteS2, combinedEAcuteS1.count) //  ́ 1
let combinedEAcute2: String = combinedEAcuteS1 + combinedEAcuteS2
print(combinedEAcute2, combinedEAcute2.count)   // é 1


Wednesday, November 13, 19: TIL Flyweight pattern; Multiton pattern; what is String interning; refreshed how to make concurrent NSOperation

Read Swift Default Protocol Implementations. Obsoleted. But anyway, interesting.

Short strings in Objective-C are tagged pointers. What about Swift? Thread on Apple developers forum “Is String allocated on the Stack or on the Heap” slightly touches the topic.

By contrast, Swift Ints almost always have a value representation. But there are exceptions.

What are these exceptions?

Learned that storing single copy of string literal in a pool is called String interning.

Learned Flyweight pattern pattern. In computer programming, flyweight is a software design pattern. A flyweight is an object that minimizes memory usage by sharing as much data as possible with other similar objects. Wikipedia has very good Swift example of the pattern.

Learned Multiton pattern.

Curious thread on ycombinator about tagged pointers. And here is the answer for a question which annoyed me a lot:

It’s not NSString, but it’s interesting to note that Objective-C selectors are just interned strings. By interning them, they can be compared with a simple pointer comparison. Because they’re just C strings, you can print a selector by casting it to char &ast;.

Yesterday I was struggling to implement one of operations, concurrent one (nowadays it’s called asynchronous). It might look strange to hear about concurrent (asynchronous ) operations. Aren’t all NSOperations concurrent (asynchronous)? No, not all. I have implemented these many years ago and I remember it was tricky and has pitfalls so I wanted to read documentation first. And here again, nowadays documentation only describes properties and methods and doesn’t contain detailed guide. And here again, the only source of information how to implement it - old obsoleted Apple documentation. It’s a Concurrency Programming Guide.

To be true, here it is a documentation of asynchronous property of NSOperation which refers Asynchronous Versus Synchronous Operations which contain up to date information. But anyway, it’s far from be that descriptive and have all details in one place, like in old Concurrency Programming Guide referenced above.

Reviewing PR of one of mine colleges I see conformance to NSObjectProtocol in Swift protocol. What’s the point nowadays to conform to NSObjectProtocol? In such cases I conform to class or AnyObject.



Monday, November 11, 19: Read NSHipster’s Device Identifiers and Fingerprinting on iOS; TIL Apple provides Supported iPhone models

Read NSHipster’s Device Identifiers and Fingerprinting on iOS. Didn’t know that back in iOS 11 was introduced DeviceCheck.framework “which allows developers to assign two bits of information that are persisted by Apple until the developer manually removes them”. Didn’t know about these two bits! Chapter of this post about fingerprinting is interesting as well, especially about using locale information for fingerprinting.

But this drawn my attention the most: UserDefaults.standard.object(forKey: "AppleKeyboards"). Obvious thing have being slipping from my attention to the moment: System is writing to standard user defaults. Simple line dump(UserDefaults.standard.dictionaryRepresentation()) put into application(_:didFinishLaunchingWithOptions:) of freshly created up being run on iPhone 6S running iOS 13.2.2 shows there are 33 items (12 if run in simulator). Here are keys: ApplePasscodeKeyboards, com.apple.content-rating.ExplicitBooksAllowed, com.apple.Animoji.StickerRecents.SplashVersion, com.apple.content-rating.ExplicitMusicPodcastsAllowed, AKLastCheckInSuccessDate, INNextFreshmintRefreshDateKey, AKLastEmailListRequestDateKey, AppleLanguagesDidMigrate, CarCapabilities, com.apple.content-rating.AppRating, AppleKeyboardsExpanded, AppleICUForce24HourTime, PKContactlessInterfaceHomeButtonSourceHasOccuredKey, com.apple.content-rating.TVShowRating, AppleLocale, PKKeychainVersionKey, AppleLanguagesSchemaVersion, INNextHearbeatDate, NSInterfaceStyle, AddingEmojiKeybordHandled, AppleITunesStoreItemKinds, AppleTemperatureUnit, AppleKeyboards, AKLastIDMSEnvironment, MSVLoggingMasterSwitchEnabledKey, AKLastCheckInAttemptDate, AKDeviceUnlockState, NSLanguages, com.apple.content-rating.MovieRating, PKEnableStockholmSettings, AppleLanguages. What I have learned from that - use reverse domain name notation for user defaults keys.

Apple provides Supported iPhone models - a list of supported iOS devices. Remember iOS nowadays means iPhone.

Here is a reminder how units should be now formatted: Measurement<UnitInformationStorage>(value: Double(processInfo.physicalMemory), unit: .bytes).converted(to: .gigabytes) // 16GB

That post is a gold having pieces of info like following one for collecting information without permission if user is able to send emails and text message:

import MessageUI
MFMailComposeViewController.canSendMail()
MFMessageComposeViewController.canSendText()

Learned about git log -S <whatever> --source --all:

To find all commits that added or removed the fixed string whatever. The --all parameter means to start from every branch and --source means to show which of those branches led to finding that commit. It’s often useful to add -p to show the patches that each of those commits would introduce as well.



Sunday, November 10, 19: Read Closures chapter of The Swift Programming Language book

Read Closures of The Swift Programming Language book.

Where the term Closure comes from?

Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables

Closures take one of three forms:

  • Global functions are closures that have a name and do not capture any values.

  • Nested functions are closures that have a name and can capture values from their enclosing function.

  • Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context.

Functions and closures are reference types!



Friday, November 08, 19: TIL unowned(safe) and unowned(unsafe) exist in Swift

Read where clauses on contextually generic declarations.

Read Swift proposal Increase availability of implicit self in @escaping closures when reference cycles are unlikely to occur.

Side learning. In following snippet surprised to see just [self] in capture list. Usually you see there [weak self] or [unowned self]. But it’s logical to see there just [self] as well which means strong capturing.

class Test {
    var x = 0
    func execute(_ work: @escaping () -> Void) {
        work()
    }
    func method() {
        execute { [self] in
            x += 1
        }
    }
}

Fuck! From further reading of proposal found out that also unowned(safe) and unowned(unsafe) exist. Didn’t know that and don’t know what that does mean.

Actually The Swift programming language mentions unowned(unsafe) in Automatic Reference Counting chapter, but in a little bit different context. Book gives following snippet and then adds a note about unowned:

class Customer {
    let name: String
    var card: CreditCard?
    init(name: String) {
        self.name = name
    }
    deinit { print("\(name) is being deinitialized") }
}

class CreditCard {
    let number: UInt64
    unowned let customer: Customer
    init(number: UInt64, customer: Customer) {
        self.number = number
        self.customer = customer
    }
    deinit { print("Card #\(number) is being deinitialized") }
}

The examples above show how to use safe unowned references. Swift also provides unsafe unowned references for cases where you need to disable runtime safety checks—for example, for performance reasons. As with all unsafe operations, you take on the responsibility for checking that code for safety.

You indicate an unsafe unowned reference by writing unowned(unsafe). If you try to access an unsafe unowned reference after the instance that it refers to is deallocated, your program will try to access the memory location where the instance used to be, which is an unsafe operation.

This snippet opens my eyes that properties could not only be weak but unowned as well. It’s useful to read documentation.

From An Exhaustive Look At Memory Management in Swift learned that capture lists could rename captured variables:

class Example {
    var closure: () -> () = { }

    func captureSelf() {
        closure = { [weak weakSelf = self] in
            _ = weakSelf
        }
    }
}

One more eye opener example from post above.

In the example below, the reference cycle is not as apparent since a capture list exists that captures self as a weak reference. However, the capture list only exists on the inner closure. Without the capture list on the outerClosure, self is passed strongly within the block. By the time innerClosure captures self weakly, it is too late. The only way to break the reference cycle in this example is to rely on an external collaborator to nil out the outerClosure–which is not okay!

class Example {
    var outerClosure: (() -> ())?

    func testCycle() {
        var innerClosure: (() -> ())?
        outerClosure = {
            innerClosure = { [weak self] in
                _ = self
            }
        }
    }
}

let example = Example()
example.testCycle() // Leak!

Let’s modify the example to pass self in weakly to the outer closure, preventing the strong reference cycle.

class Example {
    var outerClosure: (() -> ())?

    func testCycle() {
        var innerClosure: (() -> ())?
        outerClosure = { [weak self] in
            innerClosure = {
                self?.callAFunction()
            }
        }
    }
}

let example = Example()
example.testCycle() // All good!

At least one of examples from post were not working as it was described. Anyway, this is highly useful and post. Sure I will return to it many times to refresh my knowledge. May be I will include some snippets from this post to interview questions.

Above post also refers to Closures Capture Semantics, Part 1: Catch them all! which is interesting. Despite name there’s no Part 2.

From Hover at GitHub jumped by link to WWDC 2018 session #803 video Designing Fluid Interfaces. That is where I am complete noob in iOS. Here nice GitHub repo fluid-interfaces in the topic with accompanying blog post.

Read post NSCopying uses in Swift.

Side learning. I was intrigued with following. What’s Unmanaged.passUnretained there?

// Getting memory addresses
print(Unmanaged.passUnretained(stringBox).toOpaque()) // 0x0000600003620da0
print(Unmanaged.passUnretained(stringBoxCopy).toOpaque()) // 0x0000600003620e20


Thursday, November 07, 19: Read Differentiable Programming documentation in Swift

Run through Differentiable Programming documentation.

Side note: it’s smart how illustration images are embed in this markdown file.

Passed over Generic Math(s) Functions Swift proposal introducing to the standard library two new protocols ElementaryFunctions and Real to provide “basic math functions” in generic contexts for floating-point and SIMD types, and provide a path to extend that functionality to planned complex types in the future. The third piece of the proposal is the Math module. Unlike the previous two additions, the availability of these functions is gated on Swift 5.1.

Passed over Make Numeric Refine a new AdditiveArithmetic Protocol proposal. Already in Swift 5.

Passed over SIMD additions and SIMD Vectors Swift proposals. Already in Swift 5.1.

Today I was reviewing coding test of job candidate where I found developer was casting Swift String into NSString just to call enumerateSubstrings(in:,options:,using:). The problem is that this function is available on String as well. If you know it exists, just start typing its name and Xcode will help you with code completion. But what if you don’t know about this function or you forgot its name, what can you do? You can’t find this function in help, it’s not listed in String documentation. In Objective-C time I in such case I would just jump into String Programming Guide where all information about strings processing in Objective-C is available. Apple used to have such programming guides on all important topics, let it be Cryptographic Services Guide or Local and Remote Notification Programming Guide.

TODO: Consider completing PR for this FIXME.



Friday, November 01, 19: Read Crash course in Swift’s ‘function builders’ with SwiftUI

Again read about function builders Crash course in Swift’s ‘function builders’ with SwiftUI.



Wednesday, October 30, 19: TIL about comparing floats in Swift

Fun with comparing floats again: Floating-point Swift, ulp, and epsilon, talk on the topic from iOS Conf SG 2017.

Based on what’s discussed in video above it’s interesting to refactor following two extensions with code duplication into one:

extension Array where Element == Double {
    public init(txtFileURL: URL) throws {
        self =
            try String(contentsOf: txtFileURL)
            .trimmingCharacters(in: .whitespacesAndNewlines)
            .components(separatedBy: .whitespacesAndNewlines)
            .map { Double($0)! } // force unwrap intentionally!
    }
}

extension Array where Element == Float {
    public init(txtFileURL: URL) throws {
        self =
            try String(contentsOf: txtFileURL)
            .trimmingCharacters(in: .whitespacesAndNewlines)
            .components(separatedBy: .whitespacesAndNewlines)
            .map { Float($0)! } // force unwrap intentionally!
    }
}

Browsed Swift proposal Approximate Equality for Floating Point because it’s connected to the topic.

Passed over Float by Example - Swift Programming Language and Double by Example - Swift Programming Language to check if I familiar with everything.

Interesting finding Create Object Detection and Segmentation Neural Networks without Code.

Here post by Alexey Korotkov, creator of MakeML.app MakeML’s Automated Video Annotation Tool for Object Detection on iOS. Has great hint for speeding app creation of dataset for object detection.

Crosslink the post above worth reading Object Detection Guide. Almost everything you need to know about how object detection works..

Learned about baseline for Xcode performance tests. Here’s explained where baselines are stored inside project.

Read about office access system in mail.ru office developed with OpenCV and Vision, their cloud computer vision service.



Tuesday, October 29, 19: TIL git reflog

Here git reflog would help with restoring previous states of HEAD in git as it described here.

Tried to check if pugixml parser is streamable or not with searching for “stream” in Safari. Surprise: Not found. But for “iostream” - 2 matches. Safari by default searches by words, not by substrings. But this could be changed as it explained here. Changing defaults don’t work in macOS 10.15 (Safari 3.0.2). But dropdown from changing from “Starts With” to “Contains” is still there. Strange I’ve never spotted this dropdown. How many searches might I have missed with such inconsistent defaults!



Monday, October 28, 19: TIL stride(from:, to:, by:) function returns StrideTo<Element>

For the first time looked into type returned by function stride(from:, to:, by:). It returns a struct StrideTo<Element> which conforms to Sequence protocol. Here how declaration begins:

/// A sequence of values formed by striding over a half-open interval.
///
/// Use the `stride(from:to:by:)` function to create `StrideTo` instances.
public struct StrideTo<Element> where Element : Strideable {

Curious why function is used and not regular constructor?

Another finding that there’s first property. This wasn’t a surprise - I expected to have it. Surprise is that it is not optional. And it is logical for a sequence. Failed to find where this exact first is declared. Xcode is shitty bad in that. And navigating in code manually given nothing. Another surprise - there’s no last. And that’s also logical.

Meetup question: where first accessible from StrideTo is actually declared. Failed to find it in StrideTo itself as well as in Sequence.



Wednesday, October 23, 19: Read about Sequence and Collection in Swift; about type erase

Hang some time on wikipedia Apple designed processors trying to guess how many cores modern iPads and iPhones have. Short answer is: 6 or 8.

Watched Everything You Ever Wanted to Know on Sequence & Collection by Soroush Khanlou. Soroush says that extending sequence one should remember that sequence might be consumable (means it could be iterated only once) but gives as example implementation of eachPair which internally consumes sequence twice.

Watched Keep Calm and Type Erase On. I have already watched this some time ago. Nothing new.



Tuesday, October 22, 19: Read Sequence Hacking In Swift series; Iterator design pattern in Swift

Being hooked with sequence yesterday, today jumped to Sequence Hacking In Swift (I): Extending Sequences. Nothing new from this part. But this diagram worth keeping it:

Sequence Hacking In Swift (II): Extending Sequences. Nothing new as well. Good to feel I could write example better.

Sequence Hacking in Swift (III): Building Custom Sequences for Fun and Profit. Nothing new. But I feel I should practice implementing different kinds of sequences with AnyIterator and without it.

Comparing How to make a custom sequence with three part post above - a sequence could be also an iterator, It this case only next() method has to be implemented.

Another post on the topic: Iterator design pattern in Swift. It’s interesting because it refers to example from the gang of four book.

Didn’t know it’s possible to declare notmutating setter for property in Swift. Sometime it’s useful to dig into Swift sources.

Refreshed memory about NSOperation reading NSHipster’s NSOperation and post NSOperation and NSOperationQueue To Improve Concurrency in iOS.



Monday, October 21, 19: TIL how to iterate pairs if Sequence in Swift

Have been looking for iterator of pairs of sequence elements which I have used several years ago. Failed to find implementation. I found out I have a gap in knowledge and fail to write iterator on my own. I should fill in this gap. But by now here is implementation of pairs iterator borrowed from here:

extension Collection {
    func pairs() -> AnySequence<(Element, Element)> {
        return AnySequence(zip(self, self.dropFirst()))
    }
}

As it fairly stated

this approach is not safe when applied to a Sequence, because it is not guaranteed that a sequence can be traversed multiple times non-destructively.

Implementation with a custom iterator type which works on sequences as well

struct PairSequence<S: Sequence>: IteratorProtocol, Sequence {
    var iterator: S.Iterator
    var last: S.Element?

    init(seq: S) {
        iterator = seq.makeIterator()
        last = iterator.next()
    }

    mutating func next() -> (S.Element, S.Element)? {
        guard let a = last, let b = iterator.next() else { return nil }
        last = b
        return (a, b)
    }
}

extension Sequence {
    func pairs() -> PairSequence<Self> {
        return PairSequence(seq: self)
    }
}

Reading … forgot exactly what … found out how interesting reversed() over Sequence is implemented in Swift. And it seems like I could really optimize it for performance as per FIXME. Sequence itself has also interesting FIXME which I could address.

Read Swift Tip: Lazy Infinite Sequences. Nice to clarify that sequence doesn’t produce element until it is requested. In following example nothing is computed until we turn results into into an Array:

let results = (1...)
   .lazy
   .map { $0 * $0 }
   .filter { $0 > 100 }
Array(results.prefix(10))

Exercise: improve code from this post.



Thursday, October 17, 19: TIL Intersection over Union (IoU) for object detection; read Swift Property Wrappers

Read Intersection over Union (IoU) for object detection.

Reread Swift Property Wrappers.



Wednesday, October 16, 19: TIL how Range is implemented in Swift

Read Range implementation in Swift.



Tuesday, October 15, 19: Read Identifiable and Hashable / Hasher chapters at NSHipster; TIL Apple is using version 4 of UUID

Read Identifiable at NSHipster. Not as useless reading as one might think. Post discusses topics like Identifiable vs. Equatable, Identifiable vs. Hashable.

  • Unlike identifiers, hash values are typically state-dependent, changing when an object is mutated.

  • Identifiers are stable across launches, whereas hash values are calculated by randomly generated hash seeds, making them unstable between launches.

Identifiers are unique, whereas hash values may collide, requiring additional equality checks when fetched from a collection.

Identifiers can be meaningful, whereas hash values are chaotic by virtue of their hashing functions.

NSHipster’s posts are always gold!

Jumped to Versions of Universally unique identifier in WiKi. Apple uses Version 4 for UUID. Did know that all UUIDs have version number in them.

As in other UUIDs, 4 bits are used to indicate version 4.

Jumped to Hashable / Hasher.

Exercise: Use sequence function to walk tree.

Sidenote: About here in LinkedIn is really good! I should learn from this.



Monday, October 14, 19: TIL cp -a /source/. /target` copies all files from source to target not using wildcards

Why description of CGSize in Swift is so stupid? TODO: fix it. But before try to understand if there is any reason output of description of CGSize is so stupid.

From cp command: right copying of folders with files in Linux (russian) cp -a /source/. /target for copying all files from source to target not using wildcards. Not that easy topic as one could think.



Sunday, October 13, 19: TIL googleimagesdownload CLI for downloading images from Google in command line

Worth keeping bookmark How to create your own dataset with Kirkorov and Face on Yandex.Toloka (russian), at least for referencing CLI googleimagesdownload for downloading images from Google images in command line. Economics is impressive: 1.3$ for classifying 1150 photos. Another similar post Creating dataset for recognizing meters on Yandex.Toloka (russian) describing case which is much closer do my needed for creating data set for ukrainian traffic signs. Author promises follow-up for task for image segmentation for computer vision tasks.

Read post Specialist for labeling data (russian) which browses tools for labeling data. Nothing new.



Saturday, October 12, 19: TIL objc_msgSend’s new prototype; usign ffmpeg to convert audio in video

Read objc_msgSend’s New Prototype.

Learn to use ffmpeg to convert audio: ffmpeg -f f32le -ar 44100 -ac 1 -i output.pcm output.wav

  • -ar 44100 sets sample rate

  • -ac 1 number of channels. should match number of channels in source audio otherwise output is fast or slow.



Friday, October 11, 19: TIL MemoryLayout<Float>.stride in Swift as equivalent of sizeof(float) in C; CFBitVector for bit arrays; no UInt128 in Swift

Learned sizeof(float) in C equals to MemoryLayout<Float>.stride in Swift.

Trying decode data coming from python server come to this Don’t Pickle Your Data:

For most common tasks, just use JSON for serializing your data. It’s fast enough, human readable, doesn’t cause security issues, and can be parsed in all programming languages that are worth knowing.

TIL Swift doesn’t have UInt128. What the fuck!?

TIL bit arrays are available in Objective-C CFBitVector. May be I should use them.



Thursday, October 10, 19: Read interesting Swift evolution proposal Offset-Based Access to Indices, Elements, and Slices

Read interesting proposal Offset-Based Access to Indices, Elements, and Slices for adding:

let str = "abcdefghijklmnopqrstuvwxyz"
print(str[.first + 3 ..< .first + 6]) // "def"


Wednesday, October 09, 19: Found out that DispatchSourceTimer set to fire every 500ms with leeway 10ms fires first three times with half of that interval

Found out that DispatchSourceTimer set to fire every 500ms with leeway 10ms fires first three times with half of that interval:

203.233003616333
362.44702339172363
512.6810073852539
512.36891746521
511.1290216445923
533.6190462112427
512.20703125
511.90900802612305
511.6978883743286
533.7280035018921
511.7610692977905
511.9049549102783
533.6589813232422
511.79707050323486
512.0589733123779
512.2179985046387
511.40296459198
512.173056602478
511.78693771362305
533.6840152740479

Investigating why dispatch timer fires first three times with interval twice shorter then needed, jumped to Minimize Timer Use and Defer Networking. Then to How to synchronize code to drawing using CADisplayLink and CADisplayLink and its applications.

Side note: interesting case for using CADisplayLink Animated UILabel with CADisplayLink.



Tuesday, October 08, 19: Read Popovers, UINavigationController, and preferredContentSize and a lot of other interesting stuff

Switched to use Catalina and after first minutes found out bash got retired and I have to learn to use zsh. Note to future self: just remember to set the shebang in your scripts to #!/bin/zsh - taken from Moving to zsh.

Read The MAESTRO Dataset and Wave2Midi2Wave.

Read Popovers, UINavigationController, and preferredContentSize.

Passed over Trouble with form fields in iOS apps which has short overview of libraries to build forms. Then passed over follow-up Modeling form field.

Passed over All you need to know about UICollectionViewCompositionalLayout.

Passed over Less… Is More? Apple’s Inconsistent Ellipsis Icons Inspire User Confusion.

Read Caching in Swift by John Sundell.

Bookmarking Puma - a set of build utilities to automate mobile application development and deployment.

Browsed The Comprehensive Guide to iOS Context Menus - in iOS 13, context menus replace 3D Touch peek & pop. And it’s really comprehensive with many examples.

Bookmarking SwiftErrorHandler which might get useful soon. SwiftErrorHandler enables expressing complex error handling logic with a few lines of code using a memorable fluent API.

Passed over Writing an Elegant and Extensible Network Stack in Swift.



Monday, October 07, 19: How to properly mention method in Swift similar to Objective-C -[Class method:parameter]?

Swift meetup question: if would like to mention a method of a class in Objective-C in text I do it so -[Class method:parameter] or +[Class method:parameter] if it’s about a class method. How should I do this in case of Swift? If I write Class.method(_parameter:) it is not clear is it about method of a class or an instance.



Saturday, October 05, 19: TIL how to write parser using SIMD operations

Watched Swift Talk # 171 A Parser Using SIMD and Bitwise Operations (Part 1). It’s so interesting how bit twiddling is used to find control characters in a string. It’s even more interesting that I have met similar trick last week in Python code which I am porting to iOS and couldn’t get how it works.

Tricks reminded me Bit Twiddling Hacks but applied to strings.

Code in Swift Talk # 171 above uses Swift function padding(toLength:withPad:startingAt:) which I have never used. Googling for it found that method description has what Apple calls a documentation bug: String padding method is broken?. Still not fixed. To be short, method is applied to code points, not characters. Which means this method could break strings with some emoji, e.g. Good to know and remember this.

From Supporting Low Data Mode in your app TIL that iOS 13 introduced Low Data Mode.

Read Fast app prototyping with SwiftUI.

Read Announcing Our iOS Fall Sale!.

Read Auditing Your Mac for 32-bit applications and go 64.



Friday, October 04, 19: Read An in-depth look at CoreML 3

Read An in-depth look at Core ML 3:

We’re mostly going to look at the mlmodel format here, not the API from CoreML.framework (which, except for adding training functionality, didn’t really change much).

Do you need to know this stuff if you’re just looking to convert an existing model and use it in your app? Probably not. But it’s definitely good to have as a reference for when you’re designing your own machine learning models that you intend to use with Core ML 3, or when you’re not sure an existing model can be converted.

Learned keystroke for force quit on macOS. Hard to believe that after 15 years on Mac I still can’t remember it.



Thursday, October 03, 19: Read Build iOS-ready machine learning models using Create ML and Machine Learning on iOS: Computer Vision

While procrastinating read Why should you use language Ada to program your system (russian). Curious to know that int and float in Ada has no range specifiers. Programmer has to define that.

Read Build iOS-ready machine learning models using Create ML.

Read Machine Learning on iOS: Computer Vision, A catalogue of Heartbeat posts covering the use of computer vision-based machine learning tasks on iOS. Quite good selection! I should try some.



Wednesday, October 02, 19: Read chapter Error Handling of The Swift programming language guide

Read chapter Error Handling of The Swift programming language guide. catch is VendingMachineError - is what I have missed before.

Read Popovers, UINavigationController, and preferredContentSize. Relevant topic for current task.



Tuesday, October 01, 19: TIL Apple’s port of BLAS (Basic Linear Algebra Subprograms) and Compression as part of Accelerate framework

Read post Struct References by Chris Aidhof.

Read review by Chris Eidhof Swift Analytics about building analytics system in Swift with enums, structs, protocols and subclasses.

Browsed post by Cris Eidhof Swift Mirrors and JSON about using reflection to build JSON codable. Post mentions library doing exactly this .

And finally with Cris, read Undo History in Swift.

Jumped to BLAS (Basic Linear Algebra Subprograms) which is part of Accelerate framework. Jumped because we have been discussing if BLAS could help me with my current task of interpreting CoreML model output. The answer is “No”.

Read about Compression, part of Accelerate framework.



Monday, September 30, 19: TIL AltStore

Read bout AltStore Introducing AltStore. Curious. But I hope Apple will hut it down soon with all its tricks with background silent audio playing, background refresh, weekly resigning. And whole idea installing apps doing whatever they like is suspicious.



Thursday, September 26, 19: TIL how semantics of &signalFloats[offset] is different in Objective-C and Swift

In Objective-C or C when you need to process buffer from somewhere in its middle, you do something like &signalFloats[offset] or signalFloats + offset. When you do &signalFloats[offset] in Swift, compiler is happy because types match, but you get something completely different by meaning. signalFloats[offset] returns a copy of a value from an array because it’s value type and & takes address of this value.



Wednesday, September 25, 19: TIL Modality changes in iOS13

Read Supporting iOS Billing Grace Period.

Read Atomic property wrapper in Swift.

Read Modality changes in iOS13.



Tuesday, September 24, 19: TIL I don’t (always) need [weak self]

Delayed deallocation - what I have always missed - You don’t (always) need [weak self]. Except of this, post has a lot of interesting examples of creating / not creating retain cycles.



Monday, September 23, 19: TIL Unmanaged in Swift

Firstly, came across Unmanaged in Swift. Which exists since 2015. Completely missed this along with CF_IMPLICIT_BRIDGING_ENABLED, CF_IMPLICIT_BRIDGING_DISABLED, CF_RETURNS_RETAINED, CF_RETURNS_NOT_RETAINED. Therefor I jumped to NSHipster’s Unmanaged and Mike Ash’s Friday Q&A 2017-08-11: Swift.Unmanaged and Erica Sadun’s Swift: Working with Unmanaged Objects.



Saturday, September 21, 19: Watched video But what is the Fourier Transform? A visual introduction.

Watched very interesting video But what is the Fourier Transform? A visual introduction..



Friday, September 20, 19: Watched Paul Hudson’s video The Evolution of Swift: Are we there yet?

Watched Paul Hudson’s The Evolution of Swift: Are we there yet?.



Thursday, September 19, 19: Completely forgot dispatch_once was removed

As follow up after discussion about way of tolling payment for subscription for iOS app explored way how and why Netflix doesn’t give way to pay trough iTunes for new users. Billing FAQs:

iTunes billing for Netflix is not available to new or rejoining Netflix customers. If you are currently billed by iTunes, you can continue to use iTunes billing until your account is cancelled.

Read Netflix permanently pulls iTunes billing for new users.

Apple and Google charge 15 percent on each in-app subscription on their platforms. The two used to take a 30 percent cut, but in the past two years have slashed their ask.

Read Netflix ditching iTunes billing for new customers:

Currently, Apple takes a 30% cut from all purchases made through the App Store. Recurring subscriptions that are longer than a year will see a smaller 15% cut from Apple.

Netflix: ‘We No Longer Support iTunes as a Method of Payment for New Members’:

Apple recoups 15% - 30% of all subscription revenue, current and moving forward, when a user signs up for a service through its iTunes App Store and uses its billing system.

Completely forgot dispatch_once was removed. It seems to have in Swift 3, so 2 years ago.



Wednesday, September 18, 19: Firstly used Swift’s Array Initializer with Access to Uninitialized Storage; Read about Curry Function in Swift

First time used Swift 5.1. feature Array Initializer with Access to Uninitialized Storage refactoring this:

extension Data {
    var sha1: [UInt8] {
        var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
        withUnsafeBytes { unsafeBytes in
            _ = CC_SHA1(unsafeBytes.baseAddress, CC_LONG(count), &digest)
        }
        return digest
    }
}

into this:

extension Data {
    var sha1: [UInt8] {
        let dLength = Int(CC_SHA1_DIGEST_LENGTH)
        return withUnsafeBytes { bytes in
            return [UInt8](unsafeUninitializedCapacity: dLength) { buf, initedCount in
                _ = CC_SHA1(bytes.baseAddress, CC_LONG(count), buf.baseAddress)
                initedCount = dLength
            }
        }
    }
}

Functional Swift: Curry Function. First time I got which this feature called this way. Oh, no! This feature was called after Haskel Curry.

Why I started to read about curried functions? I have this:

sha1.map { String(format: "%02hhx", $0) }.joined()

The idea is to get rid of String(format: "%02hhx", $0) inside map and to get something similar to:

let hexformat: (CVarArg...) -> String = format("%02hhx")
sha1.map(hexformat).joined()
// or even shorter - that's idea!
sha1.map(format("%02hhx")).joined()

Implementation of curried format function is very short:

func format(_ fmt: String) -> (CVarArg...) -> String {
    return { String(format: fmt, arguments: $0) } // (1)
}

let s1 = format("%02hhx")(255)
let s2 = format("%02hhx-%02hhx")(255, 255)
let s3 = format("%02hhx-%02hhx-%@")(255, 255, "string")

Unfortunately it doesn’t compile with error at (1):

Cannot convert return expression of type '([CVarArg]) -> String' to return type '(CVarArg...) -> String'

The problem is because parameter CVarArg... is visible inside function having type [CVarArg]. But closure has to be converted back to CVarArg.... Or I can’t find how to do this conversion. Or this doesn’t exist.

It works like charm for single value formatting:

func singleValueFormat(_ fmt: String) -> (CVarArg) -> String {
    return { String(format: fmt, arguments: [$0]) }
}
[1,2,3,4,5].map(singleValueFormat("%02hhx")).joined() // "0102030405"

Swift meetup question: how to cast [CVarArg] to CVarArg...?



Saturday, September 14, 19: Read Dynamic Features in Swift

Read Dynamic Features in Swift.



[Friday, September 13, 19: Read What is NSUserDefaults?]; What’s new in Swift 5.1](/2019/09/13/TIL.html)

Read What is NSUserDefaults?.

If you find yourself needing to do anything else to read a preference, you should take a step back and reconsider: caching values from NSUserDefaults is usually unnecessary, since it’s extremely fast to read from. Calling -synchronize before reading a value is always unnecessary. Responding when the value changes is almost always unnecessary, since the nature of “settings” is that they control what a program does when it does it, rather than actually causing it to do something. Having an alternate code path for “no value set” is also generally unnecessary, as you can provide a default value instead (see Providing Default Values below).

This is also a good reminder:

[[NSUserDefaults standardUserDefaults] registerDefaults:@{
    @"Something" : initialValue
}];

Prior to iOS 12/macOS Mojave, if you set a default, and then immediately call exit() or abort() (but not -terminate, or the like), the value you set may be lost. You can use CFPreferencesAppSynchronize() to wait until it’s safe to exit.

The first time you read a default, it will load all the defaults for that suite into memory. This can take a meaningful amount of time on slower systems. One implication of this is to not store huge amounts of data in defaults, since it’ll all be loaded at once. Another is to not have tons and tons of defaults suites, since each one will require its own initial load.

Read Dos and Don’ts for creating an onboarding journey on iOS.

Posted these quotes to our team Slack channel:

Don’t assume your users is already converted. I’ve discovered many apps asking for email and personal informations in onboarding to finish on a pay subscription page. As a mobile user, I still haven’t the value of the app and won’t pay for it.

Do work on the right timing to onboard. You might want to leave the user to go through the onboarding process only once he discovered a bit about the app. It can be a second launch, or maybe after launching a search request. It’s can be nice to let it accessible through an help page if user want to replay it.

Read What’s new in Swift 5.1 this seem to be it’s russian translation Swift 5.1 — что нового?, What’s New in Swift 5.1?:

  • synthesized memberwise initializers with defaults;

  • implicit returns from single-expression functions;

  • universal Self;

  • opaque return types;

  • static and class subscripts;

  • warnings for ambiguous none cases;

  • matching optional enums against non-optionals;

  • ordered collection diffing;

  • creating uninitialized arrays;

  • function builders @functionBuilder;

  • property wrappers @propertyWrapper;

  • dynamic member lookup (@dynamicMemberLookup) for keypaths;

  • keypaths for tuples;

  • Equatable and Hashable conformance for weak and unowned properties;

  • new features for Strings, base at Substring worth mentioning;

  • contiguous strings;

  • converting tuple types;

  • fix of a bug of allowing duplicate labels in tuples;

  • fix overloading functions with any parameters;

  • allow type aliases for @autoclosure parameters;

  • fix for methods returning Self from Objective-C;

  • stable ABI libraries (@frozen);

CHANGELOG

This is interesting link to documentation on Swift.



Tuesday, September 10, 19: Read Swift Generics Evolution

Looked into this xcode-dev-cleaner to fix md calculation.

Read Building an iOS camera calculator with Core ML’s Vision and Tesseract OCR.

Read Swift Generics Evolution: value-level abstraction, existential types, reverse generics.



Monday, September 09, 19: Read Secrets of “printf`

Today while reviewing code of my colleague I came across of this:

private func signedValueText(_ value: Int) -> String {
    let sign = value > 0 ? "+" : ""
    return sign + String(value)
}

Read Secrets of printf:

In the most simple case, printf takes one argument: a string of characters to be printed. This string is composed of characters, each of which is printed exactly as it appears. So printf("xyz"); would simply print an “x”, then a “y”, and finally a “z”. This is not exactly “formatted” printing, but it is still the basis of what printf does.

WRONG!



Saturday, September 07, 19: Watched Swift Talk #167 Building a Collection View

Watched Swift Talk #167 Building a Collection View (Part 1). Understood very-very little.



Thursday, September 05, 19: Read Timsort and Introsort: Swift’s Sorting Algorithms

Have found that CGRect isn’t hashable in Swift. Why is that?

Read Timsort and Introsort: Swift’s Sorting Algorithms.



Monday, September 02, 19: Watched Paul Hudson’s How to use the Coordinator pattern in iOS

This CLI to eliminate unused Swift code might be useful.

Watched How to use the Coordinator pattern in iOS and Advanced Coordinators in iOS by Paul Hudson.



Sunday, September 01, 19: TIL JSONDecoder, JJLISO8601DateFormatter; Read Caching in Swift

TIL ZippyJSON:

When should you use this library?

At first, default to using JSONDecoder. It’s very battle-tested, and for plenty of use cases is just fine. Then, once you start looking for new things to optimize, take a look at how long your JSON parsing is taking. After all, JSON parsing can be a bottleneck for getting data to the user. As a rule of thumb, divide its current time taken by 4 to approximate the time taken with ZippyJSON. If that difference is significant to you (and even milliseconds can impact a user experience!), then consider using ZippyJSON.

TIL JJLISO8601DateFormatter - a 10x+ faster drop-in replacement for NSISO8601DateFormatter:

Why is it so much faster?

There’s nothing special about the library. It is written in straight-forward C and tries to avoid unnecessary allocations, locking, etc. It uses versions of mktime and localtime from tzdb. A better question is, why is Apple’s so much slower? Apple’s date formatting classes are built on top of ICU, which although reliable, is a fairly slow library. It’s hard from a glance to say exactly why, but it seems to have a lot of extra abstraction, needless copying, etc., and in general doesn’t prioritize performance as much.

May be useful Caching in Swift.

Interesting case The Curious Case of the Core Data Crash how not proper finishing background execution could crash app.



Saturday, August 31, 19: Read first chapters of App Architecture. iOS Application Design Patterns in Swift

Read first chapters of App Architecture. iOS Application Design Patterns in Swift.



Tuesday, August 27, 19: TIL two instances of UIColor can’t be directly compared

I spent half a day explaining to a colleague why callbacks aren’t always better than delegates. To clarify the concept, I created this gist to summarize the discussion and key differences.

Another interesting discovery: two instances of UIColor can’t be directly compared. This is because color space needs to be considered.

CGColorEqualToColor clearly says:

Two colors are equal if they share the same color space and numerically equal color components.

let blackColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
blackColor.isEqual(UIColor.black) // false

This behavior highlights that simple equality checks don’t work as expected.

Another thing I have learned that func getRed(_ red:, green:, blue:, alpha:) -> Bool may not return color components if color isn’t compatible with RGB.

It might be a good time to revise the assumption that color components are always in the 0…1 range:

On applications linked for iOS 10 or later, the red/green/blue component is specified in an extended range sRGB color space and can have any value. Values between 0.0 and 1.0 are inside the sRGB color gamut. On earlier versions of iOS, the specified value is always between 0.0 and 1.0.



Monday, August 26, 19: TIL expandingTildeInPath exists for NSString but not for String

Learned how to turn on Gather coverage in Xcode. I always forget where this should be turned on.

Do you know expandingTildeInPath exists for NSString but not for String. URL has standardizedFileURL but it isn’t doing what you would expect. The easiest way fill gap - bridge to NSString:

let expandedPath = (CommandLine.arguments[1] as NSString).expandingTildeInPath
let url = URL(fileURLWithPath: expandedPath)

TODO: add here explanation of what is standardizedFileURL really doing. And use NSString initializer instead of cast.



Saturday, August 24, 19: Found good mini-reference and mini-manual on Scrum

Good mini-reference and mini-manual on Scrum.



Friday, August 23, 19: Interesting Swift interview question

Today I hang at this snippet:

let numbers: [String?] = ["1", "two", nil]
let mapped: [Int?] = numbers.compactMap { Int($0 ?? "0") }
mapped.count
// What's the value of mapped.count?

Correct answer is 3.

Reason is not in source array at all and not in coalescing inside of transform in compactMap as it might seem after first look.

It’s because of type annotation of mapped variable. [Int?] for result of compactMap which is returning non-nil results. Here what documentation says:

/// Returns an array containing the non-nil results of calling the given /// transformation with each element of this sequence. /// /// Use this method to receive an array of non-optional values when your /// transformation produces an optional value.

Ok, [Int?] for result of compactMap looks strange. But how is that influencing result? Here how compactMap is declared:

func compactMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]

And its implementation is dead simple:

return self.map(transform).filter { $0 != nil }.map { $0! }

Attention to function declaration. compactMap is generic on type of element of returning array. compactMap returning [ElementOfResult] and its transform parameter is (Element) throws -> ElementOfResult?.

But what if we enforce ElementOfResult to be optional providing type annotation for mapped variable? Not a problem. Then transform will wrap all transformation results in optinal giving double optional. Then compactMap will get rid of wrapper optional because none of elemens could be nil. And now elements of array returned from compactMap is optional some of which might be nil. That what we have in our case. That why count of mapped is 3 but not 2. But if you make type annotation of mapped [Int] or get rid of it completely we get count 2 as expected.

Interesting example when explicite type annotation might play bad. If they are wrong.



Thursday, August 22, 19: TIL what is frequency response

Preparing requirements for this screen learned what frequency response (russian амплитудно-частотная характеристика) is. I havn’t literally meant “learned”. I have learned that when I was in school 40 yeas ago. And yes, this screen isn’t connected directly with notion of frequency response.

Tuning and pitch

Learned difference between accessibility identifiers and accessibility labels.



Wednesday, August 21, 19: TIL Robot pattern; Costs of sharing code between iOS and Android

There’re not obvious costs of sharing code between iOS and Android, means Dropbox: The (not so) hidden cost of sharing code between iOS and Android.

Thanks to Cocoaheads Berlin August meetup learned what robot pattern is.



Tuesday, August 20, 19: TIL Presenting Coordinators; reduce in Swift along with reduce(_:_:) has version reduce(into:_:)

Watched talk from NSSpain Presenting Coordinators by Soroush Khanlou.

Reviewing code of my colleague learned that Swift provides two reduce functions on Sequence:

Use the reduce(_:_:) method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of numbers to find their sum or product.

Use the reduce(into:_:) method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of integers to filter adjacent equal entries or count frequencies.

Swift meetup question: trivial task for testing string if it contains only characters from valid character set. I know only one easy way to do this test - using inverted character set (below). But creating inverted character set seems to be not that cheap. Strange that String in Swift doesn’t provide such basic primitive operation.

let sample = "123"
let validCharacterSet = CharacterSet.decimalDigits
let notValidCharacterSet = validCharacterSet.inverted
let valid = sample.rangeOfCharacter(from: notValidCharacterSet) == nil


Monday, August 19, 19: TIL how to make private gist public

Learned how to make private gist public and that there’s no need for that any more! Made public Obj-C gist created many years ago. TODO: made AWS Swift lambda for this coordinates transforms. Just for practicing with AWS lambdas.

Read Binary Frameworks in Swift by Peter Steinberger:

TL;WR: ABI stability won’t change much for you, and it’s not enough to ship binary Swift frameworks.

Jumped (indirectly) to (quite old) Are the Top Apps Using Swift?.

I once again downloaded the top 100 free apps and wrote some scripts to analyze the .ipa files.

Swift meetup question: how people now download apps from the AppStore. Manually one by one? Hard to believe!

Read again The Coordinator by Soroush Khanlou.

Then jumped to post of the Martin Fowler Application Controller.



Saturday, August 17, 19: TIL Xcode project vs Xcode workspace

Watched WWDC 2017 session #305 video Advanced StoreKit.

What is Xcode project vs Xcode workspace? The best answer is in Stackoverflow. Read A dive into Xcode projects and workspaces. Ooooo, project.pbxproj actually isn’t XML! Why merging it hundreds times I haven’t look into it closely.



Thursday, August 15, 19: WWDC 2018 session #705 video Engineering Subscriptions

Watched WWDC 2018 session #705 video Engineering Subscriptions - it’s my time came for mastering subscriptions on iOS.



Wednesday, August 14, 19: TIL didSet doesn’t fire for wiped out weak optional

This is my finding today that didSet doesn’t fire for wiped out weak optional. Could be interview question.

func f() {
    let n = NSNumber(value: 1)
    weak var weakOptional: NSNumber! = n {
        didSet {
            print("didSet")
        }
    }
}
f()


Tuesday, August 13, 19: TIL details about protocol extensions in Swift

Have been exploring this quiz:

var quiz = ("iOS", "Quiz") {
    didSet {
        quiz.1 = "Swift"
    }
}
quiz.0 = "Advanced"
// What's the value of quiz?

Answer is obvious. Value of quiz variable is ("Advanced", "Swift").

Solution: ("Advanced", "Swift")

But what the hell are they talking about “observer will only avoid being recursively called” and “property is set on self”:

In Swift 5, when setting a property from within its own didSet or willSet observer, the observer will only avoid being recursively called if the property is set on self (either implicitly or explicitly)

First, 1 isn’t a property but element of tuple, at least Swift reference manual calls it so. Second, it isn’t accessed with self, but with the name of the variable. Actually it isn’t possible to use self.1 in context of didSet here, compiler complains Use of unresolved identifier 'self'. I find it weird as you have to remember to change name of observed variable in didSet when you change name of variable quiz. Third, despite element 1 is accessed not with self, observer avoids running recursively.

What I have learned here, is that any variable could be observed, not only property. So this is valid:

var a = 10 {
    didSet {
        print(a)
    }
}

Again, a in snipped above could be accessed with variable name, not with self. I find it to ba a flow of the language.

Another quiz. I find this quiz question really useful for understanding protocol extensions:

protocol Drawing {
    func render()
}

extension Drawing {
    func circle() { print("protocol") }
    func render() { circle() }
}

class SVG: Drawing {
    func circle() { print("class") }
}

SVG().render()

// What's the output?

TODO: I am feeling like I have to reread about protocol extensions in Swift.

Exploring apple docs about protocol extensions found out that the first snippet in chapter Protocols of Swift language guide doesn’t compile. Asked Swift forums if I should report this.

Finally, I got quiz question with Drawing above. Extension of Drawing adds func circle() and this isn’t additional requirement! This is just part of implementation of protocol extensions. Protocol extension can’t extend protocols with new requirements! This means that func circle() from SVG conforming to protocol Drawing is just different function, it doesn’t implements protocol requirement or override something!

Accidentally found Appetize which allows to run demo of iOS apps in web. I should use it!



Monday, August 12, 19: TIL details about RawRepresentable in Swift

This quiz about enums with raw values moved me to read about RawRepresentable. Swift language guide says:

Raw values can be strings, characters, or any of the integer or floating-point number types.

Which isn’t true. To be continued.



Friday, August 09, 19: Read Useful obscure Foundation types in Swift

Passed over Useful obscure Foundation types in Swift. Well. I have used ‘NSScanner’ 10 years ago or so for this. TODO: rewrite that in Swift. CFBinaryHeap and CFTree are new for me. Have heard but never used NSCache, NSOrderedSet, NSByteCountFormatter, NSDataDetector.



Thursday, August 08, 19: Read Opaque Types chapter in Swift manual

Transformation while vectorizing code I have been tinkering with:

Read Opaque Types chapter in Swift manual.

Read Swift evolution proposal Add a String Initializer with Access to Uninitialized Storage.



Wednesday, August 07, 19: Came across interesting repo Lickability Swift Best Practices Guide

Read interesting repo Lickability Swift Best Practices Guide. “Read repo” sounds funny, I know. Lickability is small app agency from NY.

It describes app architecture. Especially interesting Common Controller Types. It contain a lot of interesting and important things even about Project Groups in Xcode project. So it could be good reference point.



Tuesday, August 06, 19: Looked in one FFT implementation

While procrastinating had a look at FFT implementation of Surge. I doubt anyone will use this implementation:

  • It’s doing real-to-complex Fourier transform but uses complex-to-complex implementation vDSP_fft_zip and to use this function it builds complex array with zero imaginary parts. It just waists memory allocated in line 27 for array imaginary. There’s real-to-complex implementation of 1D FFT vDSP_fft_zrip which might be used to avoid allocation of array of zeros for imaginary part. TODO: check if complex implementation takes more time fo running on same buffer length.

  • Usually FFT is run multiple times for several chunks of data of same length. For that usage of FFT in vDSP (and all other effective libraries for same purpose, e.g. fftw) split on two parts: setup of FFT which has to be done once and consecutive run of FFT for chunks of data of same length. But here setup is calculated inside of a function and isn’t reused.

  • vDSP isn’t able to run FFT on a buffer of arbitrary length as it uses FFT algorithm operating only on buffer of length of pow of 2. Here the length of the buffer is calculated as let length = vDSP_Length(floor(log2(Float(input.count)))) (line 30). Which means FFT will run on whole buffer only if its length is pow of 2, otherwise FFT will be run on part of the buffer. Let’s say FFT function was called with array of 1000 floats. This means FFT will be run only for 512 items of it, leaving rest 488 items as they are.

  • line 40 calculates squares of magnitudes, but runs it on whole input.count items of splitComplex. In our example 512 items contain calculated FFT and the rest - raw signal. After this calculation 512 items will contain squares of magnitude of FFT and 488 squares of raw signal.

  • line 46 calculates square first going from squares of magnitudes to just magnitudes. Than multiplies magnitudes by 2.0 divided by length of input signal. Whatever the last means, again, result of calculation is mixed with input signal.



Monday, August 05, 19: Read Create and Distribute Private Libraries with CocoaPods

Read Create and Distribute Private Libraries with CocoaPods before creating my first private pod. Have been maintaining for years pod created by others. But first time have created one.



Friday, August 02, 19: Browsed A Fast and Simple Algorithm for the Money Changing Problem

Browsed A Fast and Simple Algorithm for the Money Changing Problem.



Thursday, August 01, 19: Read Swift 5.1 Collection Diffing

Read post about musical app idea Can you sing well?, source is available. It’s interesting to write it without AiduoKit but with raw iOS stuff available.

Read Swift 5.1 Collection Diffing.

After publishing gist with my solution read Vending machine change problem.



Wednesday, July 31, 19: TIL git clean; Fortran is still in use on macOS

Don’t laugh. TIL git clean.

Found out Fortran 77 still exists, Fortran compiler is installed on OSX by default and there’s something which still using it.

Curious if it is possible to write generic function in Swift which uses vDSP_mtrans or vDSP_mtransD. I need versions for Float and Double but don’t like to have two implementations.



Tuesday, July 30, 19: Read swifting.io issue #53 First steps with NFC on iOS 13

After reading Unused images and resources clean up in Xcode started to use new tools including bonus DevCleaner for cleaning up Xcode developer files. Tools for cleaning up Xcode from unused localized string are waiting: Unused localized strings clean up from a Strings file.

Read swifting.io issue #53 First steps with NFC on iOS 13

In iOS 13 Apple expanded possibilities of Core NFC. Now iOS is able to read more complex NFC tags, including those that meet ISO 7816 and ISO 15693 standards. Now is enabled to read the data stored on tags associated with passports, driving licenses, and other forms of official identification.

The second important thing is that now iPhone apps will be able to write directly to blank tags.

iPhone XS, XS Max and XR (with the new A12 Bionic chip) posses a background feature that allows them to scan NFC tags without the need to open an app.



Monday, July 29, 19: Read On Code Review about prioritizing code review above other work

Read Swift Weekly Brief. Particularly got interested with SR-10855: Added non-ASCII characters to String benchmarking. Now I know what Bicameral scripts are as well as unicameral scripts or unicase. Read also proposal SE-0261: Identifiable Protocol.

Read post Continuous Integration. It brings interesting topic:

You need to build a feature that takes 1,000 lines of code, but you’d like to merge it in in smaller chunks. How can you merge the code in if it’s not finished?

Ultimately, continuous integration isn’t a build server, it’s a mindset. Keep your outstanding branches small and get code into the mainline branch steadily and frequently, and your team will see appreciable yields.

Will point this post when next time I will face review of big PR.

Above post refers this On Code Review. It’s about prioritizing code review above other work. Unexpectedly good post with advice for good review practices, goof review requests and good reviews.

Browsed The Great AVAudioUnitSampler workout. Tomorrow I will be using it to load sound fonts into sampler of audio engine.



Sunday, July 28, 19: Read chapter 4 of Machine Learning with CoreML book

Read chapter 4 of Machine Learning with CoreML book.

Read chapter about MLMultiArray in CoreML survival guide. Found out many things which I have already solved during last two weeks.

Have never thought that Swift misses multidimensional arrays. Arrays of arrays are different.

In Core ML, all tensors are represented as 5-dimensional multi-arrays with the shape: (sequence length, batch size, channels, height, width). If a dimension isn’t used, it is set to 1. So if the (200, 50, 75) array is really (1, 1, 200, 50, 75), then it is interpreted by Core ML as having 200 channels, a height of 50, and a width of 75. Note: The height comes before the width!

It’s a pity I haven’t get section about subscripting two weeks ago.

Example with use of withExtendedLifetime worth mentioning.

Examples with fast transposing MLMultiArray might come useful soon.

Examples with converting MLMultiArray into image with help of functions like UIImage.fromByteArrayRGBA() and other from vImage framework are also brilliant.



Saturday, July 27, 19: Read Core Audio Introduction

Read Core Audio Introduction, Core Audio: don’t forget the headphones, Core Audio: Sampling.

Read Improve your iOS team’s productivity by building features as frameworks. Probably it’s the path we will follow nearest weeks.

Read Why you should stop using Git rebase.

Accidentally came across Audio Classification using FastAI and On-the-Fly Frequency Transforms. It’s about Short-time Fourier Transform (STFT) and melspectrograms with which I struggled several weeks ago in iOS.



Friday, July 26, 19: Read Assert, Precondition and Fatal Error in Swift - Five Ways to Fail; Reducing Memory Footprint and OOM Terminations in iOS; Played with generating MIDI in iOS

Read Assert, Precondition and Fatal Error in Swift - Five Ways to Fail.

Read Reducing Memory Footprint and OOM Terminations in iOS. One more reminder to use UIGraphicsRenderer instead of UIImage(named:). Quite detailed post with references to some example projects on GitHub and to appropriate WWDC sessions.

Read Why iOS developers should pay attention to Flutter in 2019. Not convincing.

Run through Building a MIDI Sequence in Swift accustoming myself to AudioKit and Midi. Too much over-complicate for simple task of playing generated on a fly MIDI.

Passed over Building a MIDI Music App for iOS in Swift. It is better because it doesn’t depend on third party frameworks. Unfortunately it depends on deprecated APIs.

What is MIDI? Finally I came to this question. Answer is concise.

Watched WWDC 2019 Session 509 video What’s New in AVAudioEngine. Nothing relevant for me at the moment.



Thursday, July 25, 19: Read Reducing Memory Footprint and OOM Terminations in iOS

Read Reducing Memory Footprint and OOM Terminations in iOS. OOM stands for Out Of memory.

Bookmarking github repo Awesome-Swift-Playgrounds. May be I should create playground for Fast Fourier Transform and Short Time Fourier Transform.



Wednesday, July 24, 19: Came across very strange runtime error instantiating CoreML model - solution was unexpected

Today came across very strange runtime error instantiating CoreML model:

2019-07-24 10:57:07.346799+0300 amt-model-sandbox[16309:2126534] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'
*** First throw call stack:
(
	0   CoreFoundation                      0x0000000106eb26fb __exceptionPreprocess + 331
	1   libobjc.A.dylib                     0x000000010601bac5 objc_exception_throw + 48
	2   CoreFoundation                      0x0000000106eb2555 +[NSException raise:format:] + 197
	3   Foundation                          0x0000000105b22cf3 -[NSURL(NSURL) initFileURLWithPath:] + 127
	4   Foundation                          0x0000000105b2355f +[NSURL(NSURL) fileURLWithPath:] + 45
	5   amt-model-sandbox                   0x0000000104e9a3c9 +[onset_frames urlOfModelInThisBundle] + 169
	6   amt-model-sandbox                   0x0000000104e9a43c -[onset_frames init] + 60
	7   amt-model-sandbox                   0x0000000104ea1133 $sSo12onset_framesCABSgycfcTO + 19
	8   amt-model-sandbox                   0x0000000104e9dc4f $sSo12onset_framesCABSgycfC + 31
	9   amt-model-sandbox                   0x0000000104e9b554 $s17amt_model_sandbox14ViewControllerC11viewDidLoadyyF + 580
	10  amt-model-sandbox                   0x0000000104e9e6b4 $s17amt_model_sandbox14ViewControllerC11viewDidLoadyyFTo + 36
	11  UIKitCore                           0x00000001119bc43b -[UIViewController loadViewIfRequired] + 1183
	12  UIKitCore                           0x00000001119bc868 -[UIViewController view] + 27
	13  UIKitCore                           0x0000000111ff4c33 -[UIWindow addRootViewControllerViewIfPossible] + 122
	14  UIKitCore                           0x0000000111ff5327 -[UIWindow _setHidden:forced:] + 289
	15  UIKitCore                           0x0000000112007f86 -[UIWindow makeKeyAndVisible] + 42
	16  UIKitCore                           0x0000000111fb7f1c -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4555
	17  UIKitCore                           0x0000000111fbd0c6 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1617
	18  UIKitCore                           0x00000001118026d6 __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke + 904
	19  UIKitCore                           0x000000011180afce +[_UICanvas _enqueuePostSettingUpdateTransactionBlock:] + 153
	20  UIKitCore                           0x00000001118022ec -[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:] + 236
	21  UIKitCore                           0x0000000111802c48 -[__UICanvasLifecycleMonitor_Compatability activateEventsOnly:withContext:completion:] + 1091
	22  UIKitCore                           0x0000000111800fba __82-[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]_block_invoke + 782
	23  UIKitCore                           0x0000000111800c71 -[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:] + 433
	24  UIKitCore                           0x00000001118059b6 __125-[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]_block_invoke + 576
	25  UIKitCore                           0x0000000111806610 _performActionsWithDelayForTransitionContext + 100
	26  UIKitCore                           0x000000011180571d -[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:] + 223
	27  UIKitCore                           0x000000011180a6d0 -[_UICanvas scene:didUpdateWithDiff:transitionContext:completion:] + 392
	28  UIKitCore                           0x0000000111fbb9a8 -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 514
	29  UIKitCore                           0x0000000111b72dfa -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 361
	30  FrontBoardServices                  0x00000001109da125 -[FBSSceneImpl _didCreateWithTransitionContext:completion:] + 448
	31  FrontBoardServices                  0x00000001109e3ed6 __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2 + 283
	32  FrontBoardServices                  0x00000001109e3700 __40-[FBSWorkspace _performDelegateCallOut:]_block_invoke + 53
	33  libdispatch.dylib                   0x0000000107f78db5 _dispatch_client_callout + 8
	34  libdispatch.dylib                   0x0000000107f7c2ba _dispatch_block_invoke_direct + 300
	35  FrontBoardServices                  0x0000000110a15146 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 30
	36  FrontBoardServices                  0x0000000110a14dfe -[FBSSerialQueue _performNext] + 451
	37  FrontBoardServices                  0x0000000110a15393 -[FBSSerialQueue _performNextFromRunLoopSource] + 42
	38  CoreFoundation                      0x0000000106e19be1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
	39  CoreFoundation                      0x0000000106e19463 __CFRunLoopDoSources0 + 243
	40  CoreFoundation                      0x0000000106e13b1f __CFRunLoopRun + 1231
	41  CoreFoundation                      0x0000000106e13302 CFRunLoopRunSpecific + 626
	42  GraphicsServices                    0x000000010b7822fe GSEventRunModal + 65
	43  UIKitCore                           0x0000000111fbeba2 UIApplicationMain + 140
	44  amt-model-sandbox                   0x0000000104ea1e9b main + 75
	45  libdyld.dylib                       0x0000000107fed541 start + 1
	46  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

Solution was unexpected. Changing CoreML Model Class Generation Language parameter from Automatic to Swift, firstly, solved this runtime bug. Second, Xcode started generate Swift but not Objective-C class for CoreML model. Don’t know why in case of Automatic parameter it generated Objective-C code.



Tuesday, July 23, 19: Open question: how to assign reference type to self in initializer

Swift meetup question. Got stumbled with this Swift extension (below) where convenience failable initializer is implemented. At the very bottom there’s image which is what is needed. How to use this image to init self. Assignment to self in initializers only allowed for value types. To complete initialization here some self.init should be called (for not convenience initializers it will be super.init). But there’s no initializer for UIImage with UIImage parameter. As a workaround I use one with CGImage parameter. But it isn’t good solution as cgImage getter is failable. Nicer solution should exist!

extension UIImage {

    public convenience init?(from buffer: UnsafeMutablePointer<Double>, rows: Int, cols: Int, toRange0_1: Bool) {
        if toRange0_1 {
            let size: vDSP_Length = vDSP_Length(rows * cols)
            var min: Double = 0.0
            vDSP_minvD(buffer, 1, &min, size)
            min *= -1.0
            vDSP_vsaddD(buffer, 1, &min, buffer, 1, size)
            var max: Double = 0.0
            vDSP_maxvD(buffer, 1, &max, size)
            if max != 0 {
                vDSP_vsdivD(buffer, 1, &max, buffer, 1, size)
            } else {
                print("🔥 can't proceed with division by 0")
                return nil
            }
        }
        // TODO: do it with data provider!
        let size = CGSize(width: rows, height: cols)
        UIGraphicsBeginImageContextWithOptions(size, true, 1.0 /* we need just single resolution */)
        defer { UIGraphicsEndImageContext() }
        for r in 0..<rows {
            for c in 0..<cols {
                let pixelValue = buffer[r * cols + c]
                UIColor(red: CGFloat(pixelValue), green: 0.0, blue: 0.0, alpha: 1.0).setFill()
                UIRectFill(CGRect(x: CGFloat(r), y: CGFloat(c), width: CGFloat(1.0), height: CGFloat(1.0))) // Draw just one pixel in r,c
            }
        }
        guard let image = UIGraphicsGetImageFromCurrentImageContext(),
              let cgImage = image.cgImage
        else {
            return nil
        }
        // TODO: What a way to do this without cgImage?
        // cgImage is workaround here to build UIImage with existing initializer.
        self.init(cgImage: cgImage)
    }

}


Monday, July 22, 19: Read Utilizing value semantics in Swift; Cracking my windshield and earning $10,000 on the Tesla Bug Bounty Program

Read post Utilizing value semantics in Swift in Swift by Sundell.

Read interesting post about vulnerability in Tesla Cracking my windshield and earning $10,000 on the Tesla Bug Bounty Program. It doesn’t relate what I am doing. But. Learned about format string attacks - sometime enter %x.%x.%x.%x into text fields could be fun. As well as giving devices/users name like ><sctript src=//somesite.com></sctript>.



Sunday, July 21, 19: Read Distributing Custom B2B iOS Apps privately

Recently my friend asked me about way to distribute custom B2B apps beyond the App Store. This post comes handy Distributing Custom B2B iOS Apps privately.



Saturday, July 20, 19: TIL about SimulatorStatusMagic and simctl status_bar

From issue 413 of iosdevweekly learned about existence of SimulatorStatusMagic and then learned that Xcode 11 beta 4 supports same feature now: simctl status_bar.



Friday, July 19, 19: Watched WWDC 2011 session video #209 Inside the Accelerate Framework for iOS

Finding that Stephen Canon from Apple and Point Free answering my comments on stackoverflow question is Accelerate framework team member jumped to watch WWDC 2011 session Inside the Accelerate Framework for iOS.



Wednesday, July 17, 19: TIL details about vDSP from Accelerate Framework

In vDSP_mtrans parameters follow in order I wasn’t expecting. It’s cols * rows! While I expected rows * cols!!! That’s my learning of the day for which I paid with half of the day.



Tuesday, July 16, 19: Read Implementing Hash Table Algorithms in Swift; Source code of Dictionary.swift

Browsed post Implementing Hash Table Algorithms in Swift by Wayne Bishop, author of Swift Algorithms & Data Structures book.

Browsed Dictionary.swift from Swift stdlib. I understand this now “Native storage is a hash table with open addressing and linear probing”. But don’t understand this: “Dictionary does not use tombstones”. What is tombstone in this context? Probably the answer could be found in Knuth’s.

Following yesterday’s note jumped to source of KeyValuePairs in Swift. Interesting data structure I didn’t know about.



Monday, July 15, 19: Read Exploring Swift Dictionary’s Implementation

Passed Dictionary and Set Improvements in Swift 4.0 as refreshment because encountered it in one of my searches googling for posts about implementation of dictionaries in Swift.

Read Exploring Swift Dictionary’s Implementation to which I came googling “open addressing with linear probing”.

Side learning: UnsafeMutablePointer actually is much closer to pointer arithmetic in C then I thought:

var values: UnsafeMutablePointer<Value>
///
(values + i).initialize(v) // here values + i resembles C's pointer arithmetic


Saturday, July 13, 19: Watched Swift Talk episode #160 Lazy Data Loading; Point Free episode #64 Parser Combinators; Read Problem Solving with Combine Swift

Watched Swift Talk episode #160 Lazy Data Loading.

Watched Point Free episode #64 Parser Combinators: Part 3.

Brilliant idea - store where developer could buy template for app for quick start of development iOS App Templates.

Nice introduction to Combine Problem Solving with Combine Swift with marble diagrams.



Friday, July 12, 19: Read Fast.ai’s Deep Learning from the Foundations with Swift for TensorFlow; Read about swiftbrew CLI

Read Fast.ai’s Deep Learning from the Foundations with Swift for TensorFlow. fast.ai is updated for Swift for TensorFlow. Time to start it. And one more reminder tat there’s browser playground for S4TF.

Read about swiftbrew a tool for installing command line Swift packages.



Thursday, July 11, 19: Read NSHipster’s UIStackView and CAEmitterLayer

Was caught with this quiz answering it wrong. And most developers answer it wrong. Appearance of default case should have made this suspicious! Nice interview question.

objc.io Swift Quiz

Read NSHipster’s UIStackView post. Quite good explanation. Despite I use UIStackView in nearly every app I develop, I have found something new in the post. I have missed this:

To remove an arranged subview that you no longer want around, you need to call removeFromSuperview() on it. The stack view will automatically remove it from the arranged subview list. In contrast, calling removeArrangedSubview(_ view: UIView) on the stack view will only remove the view passed as a parameter from the arranged subview list, without removing it from the subview hierarchy. Keep this distinction in mind if you are modifying the stack view content during runtime.

Nice post CAEmitterLayer about confetti effect. Would wait promised full code to give it a try.

Passed over TensorFlow and CoreML – inference on iOS.

Passed over post Hotswapping Core ML models on the iPhone which describes quite sophisticated techniques of deploying CoreML models.



Wednesday, July 10, 19: Read again What Every Programmer Should Know About Floating-Point Arithmetic; Watched IEEE-754 Analysis; Example code for FFT

Again returned back to What Every Programmer Should Know About Floating-Point Arithmetic. “LANGUAGE CHEAT SHEETS” section misses C/C++/Swift. Probably I should fix this. At least memset with 0 for floating point buffer bug should be reflected here. Nice that even [Apple employees make this errors(https://forums.developer.apple.com/thread/24124).

Bookmarking IEEE-754 Analysis - nice tool for converting binaries/decimals/hex to 754 float/double.

I have to write my own example code like here about FFT. But without common errors initializing statically allocated buffers with memset (it’s actually double bug - not effective and memset of float buffer is not correct). Binary logarithm called natural. I have feelings that freq_bins is calculated incorrectly for common case. But I like approach, plots for every step, even hamming window, signal before/after window.



Tuesday, July 09, 19: TIL wtfautolayout.com; Read The missing ☑️: SwiftWebUI; Read How I set up a Jenkins node for iOS jobs

Watched Auto Layout: WTF to FTW.

  • Fuck! Accessibility identifiers for views are get printed to console by autolayout diagnostics! Which immediately shows views involved with problematic constraints.

  • Just copy autolayout diagnostics from console to wtfautolayout.com and get visual explanation what’s going on.

  • a script as action for symbolic brakepoint could open wtfautolayout page automatically! Nice!

The missing ☑️: SwiftWebUI. Nice! tonight I will give it a try.

LinkPresentation is forgotten hero of WWDC 2019.

Read post about JenkinsHow I set up a Jenkins node for iOS jobs:

Sure it is a pain in the ass to set up and can be annoying to maintain, but it is worth it to have total control of your continuous integration environment. Some cloud solutions are constrained or become difficult if not impossible to customize whereas with Jenkins the only limitation is how much time you have.



Monday, July 08, 19: Read An in-depth look at Core ML 3; Custom Layers in Core ML; MobileNetV2 + SSDLite with Core ML

Read An in-depth look at Core ML 3 and accidentally found that Core ML 3 brought SoundAnalysisPreprocessing layer — this is for Create ML’s new sound classification model. It takes audio samples and converts them to mel spectrograms. This can be used in a Pipeline as the input to an audio feature extraction model (typically a neural network). I have been working the last month exactly on this. Unfortunately sizes are fixed and limited for task I am working on.

Jumped to post Custom Layers in Core ML which explains in details how to build custom layer implementation for CPU (plain Swift implementation with loops and vectorized 150 times faster one with Accelerate framework) and for GPU (with metal shader).

Browsed MobileNetV2 + SSDLite with Core ML. Interesting reading. A lot of comparisons SSD vs. YOLO. I should repeat all this steps myself.

Browsed A peek inside Core ML. If whenever I would need to examine Core ML file I would go to this post.

First time tried to compile CoreML model on device. Interesting that console output matches one of xcode.

Read Building a Neural Style Transfer app on iOS with PyTorch and CoreML. People don’t shy to wrap ready style transfer neural nets into paid apps.

Re-watched videos of week 2 of course Audio Signal Processing for Music Applications, accomplished quiz and assignment.



Friday, July 05, 19: TIL good real-life examples in Accelerate framework documentation

Read docs simd library which is part of Accelerate framework. Working with Vectors gives interesting real life examples for color-to-grayscale conversion, calculate length and distance (Pythagorean theorem) and compare distances, calculate reflection and refraction vectors, calculate the normal of a triangle, interpolate between values. Working with Matrices gives examples for solving simultaneous equations, transforming (translating, rotating, and scaling) vectors with matrix multiplication. Working with Quaternions gives examples for rotating a point around a sphere, interpolating between two and multiple points on a sphere. Example code explains how to work with quaternions. vForce transcendental and trigonometric functions on vectors of any length, vectorised inside for current architecture, including exotics like copysign. I guess any vector imaging function one could imagine exists there.



Thursday, July 04, 19: TIL about market for software for audio units

Read Diatonic Shifter 2 User Manual. Such Audio Units could be used in host apps Apple’s like Logic (Pro), Garageband and AU Lab. This unit costs 29.99$. Interesting to learn that market for such type of software exists. Probably I could try to make something similar. E.g. this developer as a bunch of similar stuff in the Mac App Store including tuning app which I definitely could make.

Audio Unit manual by link above has quite a lot of very useful links. Some I would like to bookmark here. Pitch Shifting Using The Fourier Transform has detailed explanation of Short Time Fourier transform with implementation of which I am struggling at the moment including question of choosing of stride.

Site of company standing behind audiowish stuff mentioned above has not bad post about accelerate framework Vectorizing with vDSP and vecLib. Unfortunately it doesn’t mention question which bothers me a lot: can vDSP and veclib use as output vector one of its input vectors and how this use case influence performance.



Wednesday, July 03, 19: Read NSHipster’s Swift Property Wrappers; Exhaustive rundown of the many faces of @; Attributes chapter of Swift language reference

Read NSHipster’s Swift Property Wrappers. Despite useful info on topic this post has chart showing connection between protocols and structs conforming to them which define number types in Swift. Same about String and Substring. This information is difficult to find anywhere else. I like this conclusion in post because I find myself feeling the same:

Swift is a much, much more complex language than Objective-C. That’s been true since Swift 1.0 and has only become more so over time.

Read with joy NSHipster’s Exhaustive rundown of the many faces of @.

Jumped to Attributes of Swift language reference.



Tuesday, July 02, 19: TIL about Audio Signal Processing for Music Applications

Watched videos of week 2 of course Audio Signal Processing for Music Applications.

Read post Fourier Transform in action: detecting note frequency and recognizing separate notes (Russian).



Monday, July 01, 19: TIL different array ordering naming row-major (aka C order) and column-major (aka Fortran order)

Continuing fucking with FFTWcame across this gist which worked for me. Learned that importing ‘complex.h’ one could use expressions like double complex z1 = 1.0 + 3.0 * I; in plain C (taken from this stackoverflow answer). It’s C99. Same works in C++. Finally found out that failure last Friday was not because of complex.h being to included but because of my buffer overflow bug.

Examining fftw documentation found a term I havn’t heard before - row-major order for multidimensional array (sometimes called “C order”). Also exists a column-major order (sometimes called “Fortran order”).

TODO: check is it really that despite row-major or column-major order both can be accessed just by changing order of dimensions.



Friday, June 28, 19: Tried FFTW library for calculating discrete Fourier transform

Read new fast.ai course outline Deep Learning from the Foundations. Sounds interesting. But it’s considered second part. Probably I should start with it.

Tried FFTW library C subroutine library for computing the discrete Fourier transform (DFT). Succeeded to build it for iOS with this bash script with minor changes. But failed to successfully run fftw and get out verifiable output.



Thursday, June 27, 19: Watched Week 2 of Coursera course Audio Signal Processing for Music Applications

Watched Week 2 of Coursera course Audio Signal Processing for Music Applications.



Wednesday, June 26, 19: Read What Every Programmer Should Know About Floating-Point Arithmetic; TIL how to show in Xcode memory area formatted to some basic types like float

Read What Every Programmer Should Know About Floating-Point Arithmetic and this is especially curious Comparison. I used to think that abs(a-b) < 0.00001 is good enough way to compare floats.

It bugs me a lot that in Xcode there’s no way to show memory area formatted to some basic types like float. E.g. I have dynamic array of floats on Objective-C float *file_contents. What I can do is examine contents of pointer and contents of pointee:

Context menu of pointer variable has item ‘View Memory of “*ppointer_variable”’:

.

But it shows only raw bytes along with textual representation:

Which helps very little in case of array of floats. The only way is to use lldb command like memory read -t float -c50 \file_contents` where -t specifies type and -c count of values to show. memory read -ff -c10 `file_contents` produces same results, where -f specifies format. And there's even shortcut x/10f file_contents! Good to remember that help memory read` and help ‘help x’ work in debugger console in Xcode.

And actually there’s one more way of doing the same - casting the pointer to a pointer-to-array and use p lldb command. p *(float(*)[30])file_contents in our case:

One more way - use parray lldb command, parray 50 file_contents will print 50 elements. And if count of elements is variable it could be parray file_size file_contents.



Tuesday, June 25, 19: TIL swift-sh - a tool which allows to write CLI in Swift with dependencies; Watched Swift Talk #157 Asynchronous Networking with SwiftUI

Jumped to swift-sh a tool which allows to write CLI in Swift with dependencies.

#!/usr/bin/swift sh

import Foundation
import PromiseKit  // @mxcl ~> 6.5
print("That is how it works 👆🏿")

Nice gists of all sessions in WWDC 2019 Session Notes.

Great idea to store app container and use in tests one small change for Xcode, one giant leap for productivity.

Xcode 11 Previews could be used without SwiftUI and while developing for iOS versions prior to 13: Using Xcode Previews with existing views without using SwiftUI.

Watched Point-Free episode #62 Parser Combinators: Part 1.

Flashback:

Watched Swift Talk #157 Asynchronous Networking with SwiftUI.



Monday, June 24, 19: TIL why growth factor 2 for array is rigorously the worst possible

Browsed ARM64 Function Calling Conventions.

Read why growth factor 2 for array is rigorously the worst possible.

Read Are pointers and arrays equivalent in C?.

Results of two weeks fucking with vDSP are these spectrograms of 1000Hz sine and piano phrase:



Friday, June 21, 19: Read Read Exposing NSMutableArray

Read Swift forum post Function builders to proposal Function builders (draft proposal).

Read Exposing NSMutableArray.

Once we’re through the low level details, I present the non obvious characteristics of the class.



Thursday, June 20, 19: TIL new stuff about music notation

TIL new stuff about music notation:



Wednesday, June 19, 19: TIL Cauli - network debugging framework

Watched WWDC 2019 session #420 video Drawing Classification and One-Shot Object Detection in Turi Create.

Bookmarking Cauli - network debugging framework about which was one of talks at today’s Cocoa Heads Berlin meetup.



Wednesday, June 19, 19: TIL how to examine memory areas in Xcode

TIL how to examine memory areas in Xcode Examining Memory With a Debugger, in gdb to be true. That’s what you rare do in Xcode. Usually you just check variables.



Sunday, June 16, 19: Read RxSwift: Requiescat in Pace (RIP)

Read RxSwift: Requiescat in Pace (RIP).



Saturday, June 15, 19: Read WWDC 2019 - The Things You May Have Missed; Contributing to the Swift Benchmark Suite

Passed over WWDC 2019 - The Things You May Have Missed which lists all new what was declared on WWDC 19. List is impressive.

Passed over Continuous Integration and Continuous Delivery with Jenkins and Fastlane and Getting Started with Fastlane for Automating Beta Testing and App Deployment and Swift—Continuous Integration (CI) and Adding Continuous Integration to a Swift project. Next week I will probably follow all this.

Passed over Contributing to the Swift Benchmark Suite.

Passed over parts of AudioKit which implement FFT and STFT. Probably will use one of these.

Read My Tech Interviews Experience: Failures, Successes and Tips for you. Authors own one page CV worth keeping a bookmark. Mentions in the post that Apple employee given him some tips on what to add to the CV since he knew what Apple recruiters look for.



Friday, June 14, 19: Watched Swift Talk episode #156 A First Look at SwiftUI

Watched Swift Talk episode #156 A First Look at SwiftUI. Following months we gonna see a lot of such talks.



[Thursday, June 13, 19: Watched again WWDC 2019 session #704 Core ML 3 Framework

Watched again WWDC 2019 session #704 Core ML 3 Framework. Get something which missed when watched online, like that 100 new network layers are available, and new layers which allow build execution flows.



Wednesday, June 12, 19: Read Nate Cook’s post Swift’s Pointy Bits: Unsafe Swift & Pointer Types; Watched videos about Short-time Fast Fourier Transform

Read Nate Cook’s post Swift’s Pointy Bits: Unsafe Swift & Pointer Types about raw memory manipulation in Swift with UnsafePointer<T>, UnsafeRawPointer, UnsafeMutablePointer<T>, and UnsafeMutableRawPointer, withUnsafeBytes. It has curious example of speeding up array manipulation with withUnsafeMutableBufferPointer by getting rid of bounds check. Unfortunately it mentions only slightly bindMemory and assumingMemoryBound.

Watched videos about Short-time Fast Fourier Transform from Audio Signal Processing for Music Applications.

This PDF with slides from lecture helped a little with understanding how STFT is build. Hand drawing at the bottom of this cheat-sheet helped understand how hop size and window size work together.



Tuesday, June 11, 19: Whole day digging into vDSP Programming Guide

Whole day digging into vDSP Programming Guide figuring out how to implement Short-Time Fourier Transform having only Discrete Fourier Transform primitives.



Monday, June 10, 19: Read vDSP Programming Guide; Re-watched WWDC 2019 session #204 video Introducing SwiftUI: Building Your First App

Read vDSP Programming Guide. How I miss this old format of Apple docs!

Re-watched now offline WWDC 2019 session #204 Introducing SwiftUI: Building Your First App with running all code in Xcode. Found three places where code couldn’t match one on slides.



Sunday, June 09, 19: Passed through First lecture of Coursera’s Audio signal processing course

Passed through First lecture of Coursera’s Audio signal processing course. Here’s output:



Thursday, June 06, 19: Read Mel Frequency Cepstral Coefficient (MFCC) tutorial

Read Mel Frequency Cepstral Coefficient (MFCC) tutorial.

This might help, and this.



Wednesday, June 05, 19: Read Migrating paid app to free app with In-App Purchase; Read Promises in Swift for beginners; Watched WWDC 2019 session #406 video Create ML for Object Detection and Sound Classification; Watched online WWDC 2019 session #222 video Understanding Images in Vision Framework and some more

Reread The Future of Interaction. It is interesting how it was predicted that Apple is working on declarative UI.

Read Migrating paid app to free app with In-App Purchase. Nice idea of comparing bundle version from receipt with the last version of paid app to make user having paid version subscribed. Post also has links to posts about validate in-app purchase receipt.

Read nice post Promises in Swift for beginners.

Bookmark: this is nice server for faking APIs JSONPlaceholder - Fake Online REST API for Testing and Prototyping.

Watched online WWDC 2019 session 406 Create ML for Object Detection and Sound Classification and session 222 Understanding Images in Vision Framework. Both are very interesting and worth watching again.

Watched online WWDC 2019 session 216 SwiftUI Essentials.

Watched online WWDC 2019 session 704 Core ML 3 Framework.

Watched online WWDC 2019 session 209 What’s New in Machine Learning.



Tuesday, June 04, 19: Watched WWDC 2019 session #204 video Introducing SwiftUI: Building Your First App

Installed Netron and played with exploring CoreML models.

Read Reading and Understanding the Swift Driver Source Code.

Read Swift Literals.

Watched online WWDC 2019 session 204 Introducing SwiftUI: Building Your First App.



Monday, June 03, 19: Watched WWDC 2019 keynote; Brush up my understanding of Fast Fourier transform

WTH this catch(...) is???

    catch (CAXException &e) {
        NSLog(@"Error returned from setupAudioSession: %d: %s", (int)e.mError, e.mOperation);
    }
    catch (...) {
        NSLog(@"Unknown error returned from setupAudioSession");
    }

Found out it’s C++ feature, it’s kind of default case for catch clauses.

Working with audio this week. Just checked if I understand dB correctly.

Trying to brush up my understanding of Fast Fourier transform read 1 and 2.

Watched online WWDC 2019 keynote and Platforms State of the Union. Downloaded Xcode 11 and played with it and SwiftUI.



Sunday, June 02, 19: Read a chapter of Deep Work book

Read a chapter of Deep Work book.



Saturday, June 01, 19: Dug in some old plane C code with blocked file reading/writing

Dug in some old plane C code with blocked file reading/writing. Haven’t been doing this for ages.



Friday, May 31, 19: Played with mel-spectrograms

Listened episode 5 of Swift community podcast. Command Line Flags Mentioned:

  • Dump the Swift AST: -parse-ast
  • Dump the Clang AST: -Xclang -ast-dump -fsyntax-only
  • Dump Constraints: -debug-constraints

Browsed mention in podcast post Contributing to Swift — Part 1.

Read mentioned in podcast Slava Pestov’s post The secret life of types in Swift.

Trying to understand aurioTouch sample code came to this post Understanding AurioTouch.

Succeeded to modify aurioTouch sample code have Mel-spectrogram also known as Mel-frequency cepstrum in form of image. This is needed to feed these images to neural network. There’re a lot of samples how to do this in Python with librosa. But no samples how to build mel-spectrogram in Swift or Objective-C.

Watched Swift Talk #154 Markdown Playgrounds: Building a Link Checker. Havn’t got why is it all for.



Thursday, May 30, 19: TIL Backend Driven UI and Server-sent events

From UIKonf 2019 talk What to expect when you are templating? Clue’s approach to Backend Driven UIs by Kate Castellano first time heard about server-sent events.

Would be nice to experiment with this Tracking stolen bike by protocol NB-IoT for monitoring sea water temperature. Interesting to know that NB-IoT (Narrow Band Internet of Things) is supported by many mobile carriers around the world. One battery could power device for a year.

Read NSHipster’s NSDataAsset because met NSDataAsset in one of talks from UIKonf.

Read NSHipster’s CMMotionActivity because it was suggested next article. And then CMDeviceMotion.

Watched episode The Power of Swift for Machine Learning of TensorFlow Meets. Chris mentioned this https://github.com/tensorflow/swift and I jumped to it to find links to nice jupyter notebooks tutorials for Swift for TensorFlow.

Browsed Swift weekly issue 135.



Wednesday, May 29, 19: Read UIAppearance seems not to be that simple; Read Architecture of networking core in iOS app

Read UIAppearance seems not to be that simple. UI_APPEARANCE_SELECTOR - I have never ever met such a beast.

Read Architecture of networking core in iOS app.

Passed over Face Recognition with OpenCV just because accidentally found it was written by Engin Kurutepe from UIKonf.

Watched UIKonf 2019 talk Advanced Colors in iOS by Neha Kulkarni.

Watched UIKonf 2019 talk Promises in iOS by Anne Cahalan.

  • Future is readonly placeholder for unknown future value.
  • Promise is writable single assignment container.

Watched very interesting UIKonf 2019 talk Muse Prototype Challenges by Julia Roggatz. Nice work! A little bet more information here.



Tuesday, May 28, 19: TIL XOR linked list and Unrolled linked lists

Read XOR linked list. Nice trick. But not practical. On modern CPU with cache unrolled lists are faster.

Read about Unrolled linked lists.

Read Improving code readability in iOS development. Holy war in comments about weak/strong outlets confused me a bit.

Read how to create Xcode project from make file Simple C++: From Makefiles to Xcode Builds. And this Setup a C/C++ makefile project in Xcode: syntax highlight, autocompletion, jump to definition… and more! which I fine much better!



Monday, May 27, 19: TIL How OS X Executes Applications

Read Alex Denisov’s post BITCODE DEMYSTIFIED. What I have learned from it:

  • Bitcode is a bitstream representation of LLVM IR;
  • LLVM IR is intermediate representation of LLVM;
  • Mach-O (format for iOS and OS X executables) file has segment with compressed bitcode;
  • AppStore does thinning striping segments for other platforms (CPUs) but not for all iOS versions.

Read How OS X Executes Applications.

  • In order to get a list of dependencies for an executable on OS X, you need to use otool. Here I can see that /bin/ls references three dynamic libraries:
otool -L /bin/ls
/bin/ls:
	/usr/lib/libutil.dylib (compatibility version 1.0.0, current version 1.0.0)
	/usr/lib/libncurses.5.4.dylib (compatibility version 5.4.0, current version 5.4.0)
	/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1319.100.3)


Saturday, May 25, 19: TIL about @autoreleasepool uses in 2019 Swift

Read @autoreleasepool uses in 2019 Swift. Nothing new. I use autoreleasepool in some my projects in Swift.



Friday, May 24, 19: Watched Swift talk #153 Making Impossible States Impossible

Read post of Jeremy Howard from fast.ai C++11, random distributions, and Swift. Interesting to learn what is discrete distribution or triangular distribution.

Side learning:

You might be wondering about the protocol Nullary that’s mentioned above. Perhaps you’ve already heard of unary (a function or operator with one argument), binary (two arguments), and ternary); less known, but equally useful, is the term nullary, which is simply a function or operator with no arguments. As discussed earlier, Swift doesn’t support overloading the () operator, so we add a Nullary protocol using subscript:

    public protocol Nullary {
        associatedtype Element: SignedNumeric
        subscript()->Element { get }
    }

Read Rachel Thomas’ from fast.ai post Advice for Better Blog Posts. Very useful. One day I will start blogging instead of these logging.

Watched Swift talk #153 Making Impossible States Impossible. Nothing new. Then jumped to referenced Type-Safe File Paths with Phantom Types which was a little bit more useful. And then jumped to original talk Strings Are Evil.

Trying to choose proper library for rendering SVG in iOS app browsed SVG element reference.



Thursday, May 23, 19: Reread Andrej Karpathy’s Software 2.0

Reread again Andrej Karpathy’s Software 2.0. Previously I missed mentioning about techniques of training image classifier with defining not only weights but even changing net architecture: Large-Scale Evolution of Image Classifiers.

Bookmarking nice post about building command line Swift utility with colorful output Lets build a Command line app in Swift.



Wednesday, May 22, 19: Reread Flow coordinator pattern on steroids

Read, again, about coordinator pattern, Flow coordinator pattern on steroids.

In attempt to build library for iOS run trough Rust on iOS, Building and Deploying a Rust library on iOS, and Building an iOS App in Rust, Part 1: Getting Started with Rust.

TODO: read Create a Cool 3D Sidebar Menu Animation.



Tuesday, May 21, 19: TIL time CLI

Read NSHipster’s recently updated post Swift Code Formatters.

Side learning: time command line utility for running anything from command line and measure execution time.

Made a bug writing in iOS app out of sandbox. And found this bug only running on real device. Seems like app in simulator can easily write out of sandbox. Are there already malicious repositories which wipe out home folder of your mac when you clone and run app in simulator?

TODO: make CLI for opening app data container by parsing output xcrun simctl appinfo booted com.enote.ScoreView. Then make menu macOS app for this. There’s app with price tag 10$ doing just that.



Monday, May 20, 19: TIL time CLI; Firstly used NS_SWIFT_NAME

let hourlyRate: Double = 19.5
let hoursWorked: Int = 10
let hoursWorked_ = 10
let totalCost: Double = hourlyRate * hoursWorked // Binary operator '*' cannot be applied to operands of type 'Double' and 'Int'
let i: Double = 10.0
let d = i + 100 // Why is this different??? Why there's no compile error here?

That because literal has no exact type and late could become type used in expression.

Everything happens sometimes for the first time. Today is the first time I used NS_SWIFT_NAME. Haven’t been using Objective-C actively for several years already. And last week I had to use huge C++ library in iOS app and for using it from Swift I had to write adapter. Today I decided to polish it for Swift where it happened to use NS_SWIFT_NAME for the first time. But firstly I had to read Renaming Objective-C APIs for Swift about NS_SWIFT_NAME, Improving Objective-C API Declarations for Swift about NS_REFINED_FOR_SWIFT, and Grouping Related Objective-C Constants about NS_ENUM, NS_CLOSED_ENUM, NS_OPTIONS, NS_TYPED_ENUM, NS_TYPED_EXTENSIBLE_ENUM, Marking API Availability in Objective-C about API_AVAILABLE. This one NS_SWIFT_NOTHROW probably gone away.

Have you ever get error ‘swift_name’ attribute has invalid identifier for parameter name”? Like here:

Spent 2 hours googling. There’s no examples in internet for using NS_SWIFT_NAME for method with more than one parameter (Error* parameter doesn’t count). It realized there should be no comma in parameter list in NS_SWIFT_NAME:



Sunday, May 19, 19: Read post of Jeremy Howard from fast.ai High Performance Numeric Programming with Swift: Explorations and Reflections; Read Post Choosing Between Structures and Classes by Apple; Read Swift for TensorFlow Design Overview; Read NSHipster’s OptionSet; Read a chapter of Deep Work book

Read post of Jeremy Howard from fast.ai High Performance Numeric Programming with Swift: Explorations and Reflections. Very nice post describing all nice feature of Swift and comparing Swift’s expressiveness and performance to Python, C, C++.

It is interesting that Howard proposes way to add functionality in both Float and Double without code duplication. I’ve run into same problem sometime ago. Howard says that he failed to find this problem discussed anywhere online.

Side learning from digging into library: finding I jumped to playground to experiment with kinds of map(+):

let v1 = [1.0, -2,  3, 0]
let v2 = [0.5, 12, -2, 1]
let r1 = v1.map { abs($0) }
let r2 = v1.map(abs)
let r3 = zip(v1,v2).map(+)

It works with map(+) on array of tuples. Interesting how in gets compiled. Is + defined on a tuple? Or function parameters which look like a tuple in a source code is a tuple in reality??? I don’t know.

Post refers this nice document by Apple Choosing Between Structures and Classes. Short summary:

  • Use structures by default.
  • Use classes when you need Objective-C interoperability.
  • Use classes when you need to control the identity of the data you’re modeling.
  • Use structures along with protocols to adopt behavior by sharing implementations.

Read Swift for TensorFlow Design Overview. Now I know where quote below comes from:

Swift is just “syntactic sugar for LLVM”

Full quote:

A final pertinent aspect of the design of Swift is that much of the Swift language is actually implemented in its standard library. “Builtin” types like Int and Bool are actually just structs defined in the standard library that wrap magic types and operations. As such, sometimes we joke that Swift is just “syntactic sugar for LLVM”.

Hm, one more quote:

Chris [Lattner] described the language to me as “syntax sugar for LLVM”, since it maps so closely to many of the ideas in that compiler framework.

Read NSHipster’s OptionSet.

Read a chapter of Deep Work book.



Saturday, May 18, 19: Watched Processing CommonMark using Folds

Watched Processing CommonMark using Folds.



Friday, May 17, 19: TIL there’s no library for iOS for rendering SVG with full support of static features

Learned that finding library for iOS for rendering SVG with full support of static (meaning animation is not supported) features is tough. There’re plenty of libraries. But none of them renders what I need. None of them clearly states which features of SVG are supported and which are not.



Thursday, May 16, 19: Read Xcode Build Configuration Files; Read Image Resizing Techniques

Read Xcode Build Configuration Files. How you to use text-based xcconfig - that’s what I always wanted to know.

Side note. I have never heard about SCREAMING_SNAKE_CASE:

According to the POSIX standard environment variables have names consisting solely of uppercase letters, digits, and underscore ( _ ) — a convention I like to call SCREAMING_SNAKE_CASE.

Read Image Resizing Techniques. It’s not only about resizing but also about downsampling as well.

This calculation is smart! Usually I calculate ratio and then multiply sizes to that ratio. Using CGAffineTransform is smart!

```swift let scaleFactor = UIScreen.main.scale let scale = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor) let size = imageView.bounds.size.applying(scale)



Thursday, May 16, 19: Read NSHipster’s API Pollution in Swift Modules; TIL Swift’s Numeric Protocol; TIL what exactly means SVG

Read NSHipster’s API Pollution in Swift Modules.

Ok, learned about existence of (Numeric)[https://swiftdoc.org/v4.2/protocol/numeric/]. This is very interesting Swift’s Numeric Protocol.

SVG. These day I research existing solutions to render music score on iOS. One of solutions renders into SVG. What’s SVG?

Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation. The SVG specification is an open standard developed by the World Wide Web Consortium (W3C) since 1999.



Tuesday, May 14, 19: TIL NSHost/CFHost/Host; Watched Swift Talk #116 Building a Custom XML Decoder; Read Diseconomies of Scale and Lines of Code

Exploring Swift Foundation came across Host class aka NSHost. What? Why a have never heard of it? I remember using something lowlevel like this a couple of years ago. Well, for whatever reason NSHost/Host isn’t available on iOS. But CFHost is. Good to know. One more interesting finding. Host() just crashes. Documentation says:

To create an Host object, use the current(), init(address:), or init(name:) class methods (don’t use alloc and init).

Why then init is public if it shouldn’t be called and just crashes if called?

Should use this in my next app PluggableAppDelegate as AppDelegate replacement.

Watched Swift Talk #116 Building a Custom XML Decoder (Part 2).

Read LilyPond architecture. And bookmarked Erik Sandberg’s master’s thesis Separating input language and formatter in GNU LilyPond for further reading.

Trying to give estimate for complex project I am about to start jumped to Diseconomies of Scale and Lines of Code.

TODO: Dave DeLong’s posts A Better MVC + accompanying repo.



Tuesday, May 14, 19: Read Readdle’s Swift for Android: Our Experience and Tools; Watched Swift Talk episode #115 Building a Custom XML Decoder; Read Ash Furrow’s post Swift Type Aliases: Use Early and Often; Read Dependency Injection in Swift; Read post The Wrong Binary

Researching a way to run Swift code on Android, read Readdle’s Swift for Android: Our Experience and Tools and then browsed Swift doc Getting Started with Swift on Android.

Researching library for parsing MusicXML jumped to watch Swift Talk episode #115 Building a Custom XML Decoder. I like their way to approach implementing complex things: start with stubs provided by Xcode, put fatalError() in all stubs and see where you really need to start with. TODO: watch Part 2.

Accidentally jumped to Designing Code to “Feel” Like Swift, Not Just Compile:

It was clearly written by someone with an expert knowledge of the Apple-included zlib and the C language, and how Swift interoperates with C. But that was the problem, it felt like C, not Swift. It used UnsafeMutableRawBufferPointer and String file paths, and (turns nose up in air) that ain’t Swift.

Side note. I have never heard of such limitation:

If you use the FileManager.default singleton, we’re actually limited to 4 per thread.

Jumped to Working with FileWrapper’s in Swift.

Passed over Toptal’s 10 Essential Swift Interview Questions while preparing for interviewing.

Side note:

enum IntEnum : Int { // `Int` here defines type of rawValue of IntEnum.
                     // Syntax is similar to inheritance for classes and for protocol conformance. 
                     // Does documentation have a name for this?
                     // There's a name for it. It's raw type!
    case one = 1
    case two = 2
    case three = 3
}

This quote is interesting. I didn’t know it’s only for reference types.

Swift defines the AnyObject type alias to represent instances of any reference type, and it’s internally defined as a protocol.

Came across Ash Furrow’s post Swift Type Aliases: Use Early and Often.

And then Dependency Injection in Swift. Ha-ha:

Dependency Injection (DI) is a $25 word for a 5¢ idea…

From where jumped to UICollectionView: Unjustly Maligned. Hm, I have implemented something very similar 3-4 years ago.

Then jumped to very short post giving good example when two-values-enum is better then boolean The Wrong Binary.



Sunday, May 12, 19: Watched Point Free issue #56 What Is a Parser?

Fixing this file from iOS TensorFlow lite ObjectDetection example jumped to read CoreGraphics Geometry Primitives and Functions.

Watched Point Free issue #56 What Is a Parser?: Part 1.



[Saturday, May 11, 19: Watched Swift talk episode #150 The Origins of Reduce; episode #151 Reduce vs. Fold

Watched Swift talk episode #150 The Origins of Reduce.

Watched Swift talk episode #151 Reduce vs. Fold. Idea of fold function is brilliant!



Friday, May 10, 19: Read Accio – SwiftPM for iOS & Co. today!; Read Pure functions in Swift; Read Static factory methods in Swift; Read Using child view controllers as plugins in Swift, all three by John Sundell; Read NSHipster’s post Optional, throws, Result, and async/await

Watched video Secret of 432Hz and Again about 432Hz. It’s about 432Hz vs 440Hz for la of first octave. Yes, I am trying to fill gaps in my knowledge about music for my new job.

Interesting post about expectations from Marzipan.

Passed again over Introducing CwlViews.

A limited iOS implementation was included as part of the MAVB chapter of the App Architecture book I wrote with Chris Eidhof and Florian Kugler, last year. Fun fact: much of the terminology in CwlViews was invented by Chris since the terms I initially used didn’t make sense.

The code that became CwlViews started with a simple question: why are view controllers not reusable?

Passed over Accio – SwiftPM for iOS & Co. today!. Not bad. But I will not use it.

This is actually a problem I have writing try catch code in Swift: Elementary Swift: Catching the Actual Error.

Passed over John Sundell’s post Pure functions in Swift. I like example of refactoring button logic from complex view controller into separate structure ReaderNextButtonLogic.

Passed over Static factory methods in Swift of same author.

And Using child view controllers as plugins in Swift. I like idea of using LoadingViewController, a subclass of UIViewController, and using it as child view controller in any app that needs to show activity indicator. Never thought of such use of child view controllers. Definite, it’s better then using kind of BaseViewController as parent for all controllers in app that need activity indicator. There’s even helpers there which simplify adding and removing child view controllers. I didn’t get another example with ErrorViewController but nontheless, LoadingViewController as child view controller is nice.

Nice answer to my issue to NSHipster post Optional, throws, Result, and async/await led me to Programming to an interface. Fair point:

Program to an interface, not an implementation



Thursday, May 09, 19: TIL Nimble and Quick

I should start to use Nimble to make assertions in unit tests clear. Well, companion Quick i still don’t understand.

Well, that is what I have learned today at my new job:



Wednesday, May 08, 19: Read Why I don’t use PDFs for iOS assets; Read NSHipster’s Optional, throws, Result, and async/await

Bookmarking this TORoundedButton that not to invent bicycle next time.

Bookmarking Why I don’t use PDFs for iOS assets to support my voice against using PDFs in Xcode assets.

Nice post Optional, throws, Result, and async/await. From where jumped to Async/Await for Swift proposal.

This could be good starting point for using FFT to build specrogram.

Read RepetitiveTask, accompanying (playground)[https://github.com/krzyzanowskim/RepetitiveTask].

Would be nice to install this Online Swift Playground on Linux.

TODO: run through this tutorial.

TODO: run this on device. It’s accompanying repo for post Visualizing the audio frequency spectrum on iOS via the Accelerate Framework and FFT(Fast Fourier Transform).

Wow, DICOM viewer for OSX which depend on DCMFramework which points here. Should give it a try.



Tuesday, May 07, 19: Watched WWDC 2018 session Metal for Accelerating Machine Learning

Watched WWDC 2018 session Metal for Accelerating Machine Learning.

Accidentally found mentioning of ScreenSaverDefaults in documentation of ScreenSaver framework which reminded me about this PR to Aerial screensaver. How did I miss ScreenSaverDefaults!?

TODO: try to build Forge. Project has link. Nonetheless there’s no code there and library itself for fast running ML faster then CoreML is for a license, description is very interesting!

I did miss that CoreMl since iOS 11.2 supports custom layers Custom Layers in Core ML. There’s even example code there!



Monday, May 06, 19: Read Handling Input from Apple Pencil and Pencil Interactions documentation; read Apple Pencil at pspdfkit.com; Read John Sundell’s Building iPad Pro features in Swift

Refreshed Apple Pencil API Handling Input from Apple Pencil and Pencil Interactions.

Read Apple Pencil API. It has model trained on Open Images Dataset. It has traffic sign category. I should give it a try!

It’s interesting to read in [Apple Pencil at pspdfkit.com]https://pspdfkit.com/guides/ios/current/annotations/apple-pencil/

There is no simple way to know whether a device supports Apple Pencil, whether the user has one, and if it is currently connected. All an app knows is that if it receives a touch event of type UITouchTypeStylus, then an Apple Pencil was connected at that time.

But SO gives smart solution for that which I should check Stackoverflow thread Detect whether Apple Pencil is connected to an iPad Pro.

Interesting essay Apple Pencil Note-Taking: Why You Should Use Apple Notes, actually.

John Sundell Building iPad Pro features in Swift.

TODO: fix this.

TODO: try this and this.

TODO: Write sample app detecting hand-written input of digits on iOS device screen and drawing in bounding box detected character instead of handwriting. Use MNIST detector for that.

TODO: Play with this sample and this.

TODO: go through this tutorial.



Saturday, May 04, 19: Read John Sundell’s Constructing URLs in Swift

Passed through John Sundell’s Constructing URLs in Swift.



Friday, May 03, 19: Passed over several Swift proposals

Passed through PR to Swift standard library Use String’s underlying UTF-8 view for Float parsing

Passed over Swift proposal Generic Math(s) Functions. That would solve a problem I came across some time ago trying to add something to all numerical types without code duplication.

Passed over another Swift proposal Approximate Equality for Floating Point. This is great:

if x.isAlmostEqual(to: y) {
  // equal enough!
}

if x.isAlmostEqual(to: y, tolerance: 0.001) {
  // equal enough!
}

if x.isAlmostZero( ) {
  // zero enough!
}

Browsed “anti-pitch” Just say “no” to protocols on structural types?.

Interesting discussion Adding more data structures to the standard library by guy preparing for Swift interview.



Monday, April 29, 19: Passed over Decimal aka NSDecimalNumber

What the fuck Decimal in Swift is? Why can’t I just jump to its declaration in Xcode? Why should I google for it to find documentation? Well, it’s old friend NSDecimalNumber. And sure, it’s possible to find it in Xcode in Developer Documentation which is in Help menu. It’s still regrets Xcode can’t jump to source where it’s declared.



Friday, April 26, 19: Passed through App form design best practices; Watched Swift Talk #149 We use SwiftSyntax to add highlighting for Swift code blocks

Passed through App form design best practices. It has link to Placeholders in Form Fields Are Harmful which I will hand over to designers I am working with.

Watched Swift Talk #149 We use SwiftSyntax to add highlighting for Swift code blocks.



Thursday, April 25, 19: TIL partition function of Collection; TIL __consumable in Swift

Writing answer to comment on this PR looked for where first of Array is declared in Swift. Found partition function. I should use it!

    var numbers = [30, 40, 20, 30, 30, 60, 10]
    let p = numbers.partition(by: { $0 > 30 })
    // p == 5
    // numbers == [30, 10, 20, 30, 30, 60, 40]

Further exploring Swift library sources came across __consumable and jumped to Preparing the iteration ABI for move-only types and to Ownership Manifesto.

Accidentally came across this Cityscapes dataset. Worth keeping a bookmark. Hope to use it later for my own purpose.



Wednesday, April 24, 19: Came back to Google’s Swift Style Guide

Change requests in PR to swift-model brought me again to Google’s Swift Style Guide.



Tuesday, April 23, 19: Watched Swift talk episode 147 Markdown Playgrounds: Executing Swift Code and episode 148 Markdown Playgrounds: String Handling; Read documentation Support Universal Links and NSUserActivity

Watched Swift talk episode 147 Markdown Playgrounds: Executing Swift Code.

Watched Swift talk episode 148 Markdown Playgrounds: String Handling.

Refreshed knowledge about Universal Links reading Support Universal Links and NSUserActivity.



Monday, April 22, 19: Watched WWDC 2015 session 412 Time profiling in depth

Watched WWDC 2015 session 412 Time profiling in depth.



Sunday, April 21, 19: Watched again WWDC 2015 session 409 Optimizing Swift Performance

Watched again WWDC 2015 session 409 Optimizing Swift Performance.



Thursday, April 18, 19: Read Understanding Swift for TensorFlow

Read Understanding Swift for TensorFlow. A little bit outdated. This followed with fix.



Wednesday, April 17, 19: Watched Swift Talk episode #147 Markdown Playgrounds: Executing Swift Code; Watched Point free episode #54 Advanced Swift Syntax Enum Properties

Watched Swift Talk episode #147 Markdown Playgrounds: Executing Swift Code. Not impressed.

Watched Point free episode #54 Advanced Swift Syntax Enum Properties. Impressed.



Tuesday, April 16, 19: Watched WWDC episode #409 Optimizing Swift Performance

Watched WWDC episode #409 Optimizing Swift Performance.



Monday, April 15, 19: Watched WWDC 2016 session #419 video Protocol and Value Oriented Programming in UIKit Apps; Watched WWDC 2016 session #416 video Understanding Swift Performance

Watched WWDC 2016 session #419 video Protocol and Value Oriented Programming in UIKit Apps.

Watched WWDC 2016 session #416 video Understanding Swift Performance.



Sunday, April 14, 19: Came across UIView-SmoothCorners repo

Came across UIView-SmoothCorners which worth keeping a reference.



Saturday, April 13, 19: Watched again WWDC 2016 session #414 video Building Better Apps with Value Types in Swift

Watched again WWDC 2016 session #414 video Building Better Apps with Value Types in Swift. Very useful talk about making value semantic types out of (some or all) reference semantic ones.



Friday, April 12, 19: Watched, probably, hundredth time, WWDC 2015 session #408 video Protocol-Oriented Programming in Swift

Watched, probably, hundredth time, WWDC 2015 session #408 video Protocol-Oriented Programming in Swift.



Thursday, April 11, 19: Read The Pragmatic Guide to Scalable Swift Architecture for 2019

Post The Pragmatic Guide to Scalable Swift Architecture for 2019 have good tips:

  • Refactor WHILE working on bugs or within features.
  • For every new feature, you write it correctly from the start.
  • Make SMALL tickets for refactoring specific parts of the codebase

5 Important Swift Patterns that will Immediately Improve your Apps Scalability:

  • make models structs
  • PromiseKit
  • dependency injection
  • Coordinator pattern for decoupling states and events

Read Advanced String interpolation in Swift 5.0 (russion). Fuck! I didn’t know that string literals are possible in interpolation since Swift 2.1: print("Hi, \(user ?? "Anonymous")").

Came across a post Autonomous driving on pavement using PoenCV and Tensorflow (russian).

Passed through https://www.raywenderlich.com/158-coordinator-tutorial-for-ios-getting-started.



Wednesday, April 10, 19: Read fun post by Jesse Squires Agile by degrees: How to estimate engineering project timelines; Read NSHipster’s post NSOperation

Read fun post by Jesse Squires Agile by degrees: How to estimate engineering project timelines. Worth keeping bookmark as it has a link on paper why humans are naturally terrible at estimating for evolutionary reasons, as well as psychological ones — namely, the planning fallacy, optimism bias, and anchoring.

Read another fun post by Jesse Squires Summoning Lucifer: on making my first Mac app as an iOS developer.

Read post (russian) Could user data monetization be a trend in 2019?. Bullshit.

Before writing Operation what I havn’t done for several years, refreshed my knowledge by reading NSHipster post NSOperation.



Tuesday, April 09, 19: Passed over Swift evolution String Gaps and Missing APIs

Read about already accepted additions to String API in Swift String Gaps and Missing APIs. Will appear in Swift 5.1.

Slice, the default SubSequence type, provides base for accessing the original Collection. Substring, String’s SubSequence, should as well.

Sounds like ArraySlice should also provide base, but it doesn’t.

Went to AI for Autonomous Mobility meetup. There’s time for registration for robocar races until 30 of April. Registered. Interesting link with resources.



[Monday, April 08, 19: Re-read Getting Started with Swift Compiler Development; Watched Point Free issue #53 Swift Syntax Enum Properties

Shouldn’t RawValue be used somewhere in CodingUserInfoKey struct? Otherwise it isn’t needed.

Reread Getting Started with Swift Compiler Development to refresh how to build swift.

Watched Point Free issue #53 Swift Syntax Enum Properties. It’s about using new Apple’s tool SwiftSyntax for parsing Swift enum declarations and generating some Swift code. Talk has nice recap of Swift Package Manager.



Saturday, April 06, 19: Read John Sundell’s post Inline types and functions in Swift

Read John Sundell’s post Inline types and functions in Swift. Flashback from the past:

  • AnyObject, equivalent of Objective-C’s id.


Friday, April 05, 19: Watched Swift Talk #146 Markdown Playgrounds: Markdown Syntax Highlighting; Read John Sundell’s Swift sequences: The art of being lazy

Watched Swift Talk #146 Markdown Playgrounds: Markdown Syntax Highlighting. Nothing interesting this time.

Read John Sundell’s Swift sequences: The art of being lazy. It’s about using Sequence and AnySequence.



Thursday, April 04, 19: TIL what’s new in Swift 5.1

Read Swift 5.1 — what’s new?.



Wednesday, April 03, 19: Read John Sundell’s String parsing in Swift

Read John Sundell’s String parsing in Swift. I haven’t used Scanner from Objective-C for ages! Lazy implementation of tokenizer worth a bookmark.



Tuesday, April 02, 19: Read John Sundell’s Different flavors of type erasure in Swift and Avoiding race conditions in Swift

Read Different flavors of type erasure in Swift by John Sundell. It refined my understanding of Swift protocols having Self or associated type requirements and what makes Swift protocols different from Objective-C ones.

Post explains three flavors of type erasure:

  • Generic wrapper types;
  • Type erasure with closures; 👈🏿 I favor this.
  • External specialization.

Read Avoiding race conditions in Swift by John Sundell because previous post had a link to it.



Monday, April 01, 19: Watched Point Free Issue #52 Enum Properties

Watched Point Free Issue #52 Enum Properties. As usual, absolutely crazy stuff!

Side note. Operator for promoting a key path into a function to make possible let admins = userts.filter(^\.isAdmin):

    prefix operator ^
    prefix func ^ <Root, Value>(_ keyPath: KeyPath<Root, Value>) -> (Root) -> Value {
        return { root in root[keyPath: keyPath] }
    }


Thursday, March 28, 19: Read What’s new in Swift 5.0; Watched String Interpolation in Swift 5 (Part 2)

Watched String Interpolation in Swift 5 (Part 2).

Read What’s new in Swift 5.0:

  • Result is now part of Swift bringing new features:
    • get() method either returning the successful value or throwing error
    • initializer accepting a throwing closure makes possible let r = Result { try String(contentsOfFile: f) }
    • general Error protocol could be used, rather than using Result<Int, NetworkError> could use Result<Int, Error>
  • raw strings;
  • customizable string interpolation bring absolutely crazy stuff. should experiment with it (TODO:);
  • @dynamicCallable serves for Python or JavaScript bridging but could be used for creating some creasy stuff;
  • @unknown for handling future enum cases;
  • nested optionals resulting from try? are flattened;
  • isMultiple(of:) for checks like rowNumber % 2 == 0;
  • compactMapValues() in dictionaries for transforming values while keeping keys intact;
  • count(where:) was discarded in betatesting, may be will return in later swift versions;

Other sources mention also:

By the way, CHANGELOG is available!



Thursday, March 28, 19: Read What’s new in Swift 5.0; Watched String Interpolation in Swift 5 (Part 2)

Watched String Interpolation in Swift 5 (Part 2).

Read What’s new in Swift 5.0:

  • Result is now part of Swift bringing new features:
    • get() method either returning the successful value or throwing error
    • initializer accepting a throwing closure makes possible let r = Result { try String(contentsOfFile: f) }
    • general Error protocol could be used, rather than using Result<Int, NetworkError> could use Result<Int, Error>
  • raw strings;
  • customizable string interpolation bring absolutely crazy stuff. should experiment with it (TODO:);
  • @dynamicCallable serves for Python or JavaScript bridging but could be used for creating some creasy stuff;
  • @unknown for handling future enum cases;
  • nested optionals resulting from try? are flattened;
  • isMultiple(of:) for checks like rowNumber % 2 == 0;
  • compactMapValues() in dictionaries for transforming values while keeping keys intact;
  • count(where:) was discarded in betatesting, may be will return in later swift versions;

Other sources mention also:

By the way, CHANGELOG is available!



[Wednesday, March 27, 19: Read Method Dispatch in Swift; @objc and dynamic

Read Method Dispatch in Swift. Old but relevant.

Read @objc and dynamic.

dynamic opts into dynamic dispatch. You might need this for KVO support or if you‘re doing method swizzling.

Interesting:

    protocol MyProtocol {
        //func extensionMethod()
    }
    struct MyStruct: MyProtocol {
    }
    extension MyStruct {
        func extensionMethod() {
            print("In Struct")
        }
    }
    extension MyProtocol {
        func extensionMethod() {
            print("In Protocol")
        }
    }

    let myStruct = MyStruct()
    let proto: MyProtocol = myStruct

    myStruct.extensionMethod() // -> “In Struct”
    proto.extensionMethod() // -> “In Protocol”

Conclusion:

Many people new to Swift expect proto.extensionMethod() to invoke the struct’s implementation. However, the reference type determines the dispatch selection, and the only method that is visible to the protocol is to use direct dispatch. If the declaration for extensionMethod is moved into the protocol declaration, table dispatch is used, and results in the struct’s implementation being invoked. Also, note that both declarations use direct dispatch, so the expected “override” behavior is just not possible, given the direct dispatch semantics. This has caught many new Swift developers off guard, as it seems like expected behavior when coming from an Objective-C background.

So, uncommenting declaration of extensionMethod() in MyProtocol in both cases prints “In Struct”.

Interesting very detailed explanation how objc_msgSend() works objc_msgSend() Tour Part 1: The Road Map.

That is quite interesting The Ghost of Swift Bugs Future:

…watching the Protocol-Oriented Programming in Swift session, a particular construct struck me as the most likely source of arcane, incomprehensible bugs in the future. I expect it to be the novice’s crucible, similar to the way deallocated delegates would lead to crashes in the days before the weak attribute was introduced. I’m not yet sure what the searches will look like, but the fundamental question will be a variation of:

“Why does the method that I wrote overriding protocol extension X never get called?”

Read Mike Ash’s Friday Q&A 2016-04-15: Performance Comparisons of Common Operations, 2016 Edition.



Tuesday, March 26, 19: Read Watch out for protocol extensions in your Swift API (unit tests trap)

Read Watch out for protocol extensions in your Swift API (unit tests trap).



Monday, March 25, 19: Watched Point Free episode #51 Structs 🤝 Enums; Read How not to get desperate with MVVM implementation; Read How to implement MVVM pattern in Swift from scratch

Watched Point Free episode #51 Structs 🤝 Enums. As always, absolutely crazy. Unpractical, but very interesting.

Read How not to get desperate with MVVM implementation.

You might notice that the ViewModel is kinda complex. In the end of this article, we will discuss the bad part of the MVVM. Anyway, for a medium sized project, the MVVM is still a good choice to eat an elephant one bite at a time!

Read How to implement MVVM pattern in Swift from scratch. It’s so interesting to compare what different people understand as MVVM. Here Working With Static Patterns: A Swift MVVM Tutorial is something different.



Sunday, March 24, 19: Passed over Custom View Controller presentations, the right way

Passed over Custom View Controller presentations, the right way about creating popover controller showing a card on bottom of screen.



Saturday, March 23, 19: Read UTF-8 String swift.org blog post; Watched talk on Swift for TensorFlow by Chris Lattner and Brennan Saeta; Passed over swift-log, a Logging API package for Swift 5; Read Key Path Expressions as Functions Swift evolution proposal

Read UTF-8 String about Swift 5 the preferred encoding of strings from UTF-16 to UTF-8 while preserving efficient Objective-C-interoperability.

Watched a talk on Swift for TensorFlow by Chris Lattner and Brennan Saeta given at Dev Summit 2019.

Passed over swift-log, a Logging API package for Swift 5.

a community-driven open-source project which is actively seeking contributions, be it code, documentation, or ideas.

Hope Key Path Expressions as Functions proposal will be accepted.



Friday, March 22, 19: Browsed post Using Google Cloud Translation API to Power Your iOS App with Instant Translation; Read fun post Everything you need to know about Loading Animations; TIL What is a configurable initialization

Browsed quite wordy and detailed post Using Google Cloud Translation API to Power Your iOS App with Instant Translation. Post worth keeping a bookmark. Quite good following of MVVM architecture.

Above post mentions GTAlertCollection which worth keeping a bookmark and using. Unfortunately neither Carthage nor CocoaPods is supported.

Fun post about loading animation Everything you need to know about Loading Animations.

From A Better Syntax for Configurable Initializations TIL what is a configurable initialization?. I don’t like solution. I find Then much consistent.



Thursday, March 21, 19: Read Capture lists in Swift; Passed over Enumeration and Closures chapters in The Swift programming language guide

Read post Capture lists in Swift: what’s the difference between weak, strong, and unowned references?.

Read Wikipedia article Tail recursion about TCA (= tail call optimisation) in some programming languages.

Passed over Enumeration chapter in The Swift programming language guide.

Having this definition from chapter above:

    enum ArithmeticExpression {
        case number(Int)
        indirect case addition(ArithmeticExpression, ArithmeticExpression)
        indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
    }

it is interesting to check real limitation (in regards of stack usage) of recursive implementation of following function:

    func evaluate(_ expression: ArithmeticExpression) -> Int {
        switch expression {
        case let .number(value):
            return value
        case let .addition(left, right):
            return evaluate(left) + evaluate(right)
        case let .multiplication(left, right):
            return evaluate(left) * evaluate(right)
        }
    }

Interesting to do something like in post Tail Recursion, Objective-C, and ARC . Hint for future self: -S key of swiftc is for producing Assembly output swiftc -S main.swift. Different -O options might be needed to experiment with different optimisation levels.

By the way, blog dev etc is not get updated but anyway has many interesting posts, like No parameters. That’s it: () (in (Objective-)C) in a function type declaration means unspecified parameters, not no parameters! This post I will reference when I fix seeing returning mutable collections from method/functions declared immutable return value Mutable Return Values. Very good explanation about self sizing view Auto Layout and Views that Wrap. Especially good is explained Why it doesn’t “just work”. In snippet from example interesting that [super layoutSubviews] is called twice.

    - (void)layoutSubviews {
        [super layoutSubviews];

        CGFloat availableLabelWidth = self.label.frame.size.width;
        self.label.preferredMaxLayoutWidth = availableLabelWidth;

        [super layoutSubviews];
    }

This Subclassing Delegates is also interesting.

And this Timers, Clocks, and Cocoa I could reference when seeing misused timers in apps.

Passed over Closures chapter of The Swift programming language guide.

Post INVERTED EXPECTATIONS mentions useful but barely mentioned property isInverted of XCTestExpectation:

    let notificationExpectation = expectation(forNotification: NSNotification.Name.SomeNotification, object: obj, handler: nil)
    notificationExpectation.isInverted = true
    // exercise your code and wait for the expectation
    wait(for: [notificationExpectation], timeout: 1.0)

Watched quite old talk Convolutional Neural Networks with Metal & Swift 2017 iOS 11 talk and 2018 iOS 12 talk to which I came over keras_mnist_demo repo to which I came exploring who left “🍀” comment in my PR. It did worth spending time watching.



Wednesday, March 20, 19: Read Types chapter of The Swift language reference

Reading again about ObjectIdentifier.

In Swift, only class instances and metatypes have unique identities.

Ok, what metatypes is in Swift?

This brings to Types section of Swift language reference.

In Swift, there are two kinds of types: named types and compound types.

A named type is a type that can be given a particular name when it’s defined. Named types include classes, structures, enumerations, and protocols.

A compound type is a type without a name, defined in the Swift language itself. There are two compound types: function types and tuple types. A compound type may contain named types and other compound types.

That is new:

You can put parentheses around a named type or a compound type. However, adding parentheses around a type doesn’t have any effect. For example, (Int) is equivalent to Int.

Have learned something new about tuples (that’s why it is important to read documentation from time to time):

    var someTuple = (top: 10, bottom: 12)  // someTuple is of type (top: Int, bottom: Int)
    someTuple = (top: 4, bottom: 42) // OK: names match
    someTuple = (9, 99)              // OK: names are inferred      <= I have missed that names of tuple elements might be inferred
    someTuple = (left: 5, right: 5)  // Error: names don't match

This part of Swift always makes me smile:

All tuple types contain two or more types, except for Void which is a type alias for the empty tuple type, ().

And finaly, metatype. Metatype type is a type of a type. SomeClass.self returns SomeClass itself, not an instance of SomeClass. And SomeProtocol.self returns SomeProtocol itself, not an instance of a type that conforms to SomeProtocol at runtime. There’s type(of:) function to take type as a value from instance of some type. Having metatype a class function of that type could be called. Or instance of that type could be created if there’s required initialiser class is final. Strange requirements.



Tuesday, March 19, 19: Played with Swift models for Tensorflow

Played with Swift models for Tensorflow which end up with PR1 and PR2.



Monday, March 18, 19: Read again Chapter 2 of Machine learning with Core ML book; Read Identifying objects in Swift; Read Code encapsulation in Swift

Read again Chapter 2 of Machine learning with Core ML book. Which ended up with bug fix.

Read Identifying objects in Swift. It’s about Equatable, ===, Hashable and … ObjectIdentifier. Have never head of ObjectIdentifier!!!

Read Code encapsulation in Swift.



Sunday, March 17, 19: Read again post of John Sundell Replacing legacy code using Swift protocols

Read again post of John Sundell Replacing legacy code using Swift protocols. I like this approach to refactoring legacy code. Unfortunately it will be hard to change architecture of app (framework) with this approach.



Saturday, March 16, 19: Watched Swift talk about String interpolation in Swift 5; Read very old post of Natasha The Robot Swift: What are Protocols with Associated Types?; Watched Alexis Gallagher’s talk Protocols with Associated Types

Watched Swift talk about string interpolation in Swift 5. Yes, Swift 5 is coming.

Read very old post of Natasha The Robot Swift: What are Protocols with Associated Types?.

That’s it! A protocol with associated type is just a fancy term to a protocol that has generics in it. By using PATs (and protocols in general), we have a powerful tool that promotes really nice composition in favor of messy inheritance.

Then watched Alexis Gallagher’s talk Protocols with Associated Types. Very good explanation of what Protocols with associated types are.

Are Protocols with associated types just generic protocols with wacky syntax? No. And yes, sort of.



Friday, March 15, 19: Passed over Apple docs Logging; Read post of Peter Steinberger Adding Logging to Crash Reports; Read Unused localized strings clean up from a Strings file

Passed through fun post of Marco Arment Why it’s hard to read the time on Infograph.

Passed over Apple docs Logging about unified logging available since iOS 10.0 which I should start using instead of print.

Read post of Peter Steinberger Adding Logging to Crash Reports.

Ideally, we’d love to fully switch to Apple’s os_log API. However, it has one major downside: There’s still no way to access the rolling log to add to the reports that get sent back to us.

I should make some of my websites as AWS Lambdas in Swift Websites using Swift and AWS Lambda. Worth passing through all these stuff.

Just to bookmark useful link A Jekyll theme for automatically generating and deploying landing page sites for mobile apps.

Read Unused localized strings clean up from a Strings file. It’s about open sourced command line tool AbandonedStrings.

Glanced over post about “Subscription Offers”, newly announced for iOS 12.2 feature.

Read short post Grouping elements for better accessibility on iOS.

Read post of member of Zeplin team about detail on how to automate notarizing a macOS app using command line tools.



Thursday, March 14, 19: Read Life in the slow lane or, how we stopped using fastlane for continuous integration

It’s interesting to read that fastlane sucks when many say it’s glorious Life in the slow lane or, how we stopped using fastlane for continuous integration.



Wednesday, March 13, 19: Read post The Sad State of Logging Bugs for Apple

Read sad post The Sad State of Logging Bugs for Apple.



Tuesday, March 12, 19: Read interesting post about building WatchKit app

Read interesting post about building WatchKit app (Intro, WatchKit Adventure #1: The Big Picture. Definitely I should go through this post when I start my first Watch app.



Monday, March 11, 19: Watched Point Free issue #50 Generative Art: Part 2

Watched Point Free issue #50 Generative Art: Part 2. These guys are mad!



Sunday, March 10, 19: Read interesting post about ukrainian number plates detection and recognition

Read interesting post about ukrainian number plates detection and recognition Part 1 and Part 2, GitHub, online demo, Jupyter notebook example demonstrating license plate mask recognition, Jupyter notebook example demonstrating license plate rectangle detection, Jupyter notebook example demonstrating license plate number detection. Have to go over all notebooks some time.



Saturday, March 09, 19: Watched Swift Talk #142 Flow Testing with Protocols; Read Safely supporting new versions of Swift; Read iOS Responder Chain: UIResponder, UIEvent, UIControl and uses

Watched Swift Talk #142 Flow Testing with Protocols.

Read post Safely supporting new versions of Swift. Usually I change Swift version ‘In one big go’ as it described in the post.

Read iOS Responder Chain: UIResponder, UIEvent, UIControl and uses. Reminds that very long time ago I wanted to experiment with inputView to check what else can it show except UIPickerView. Look into UIResponder shows up a lot of new stuff like inputAssistantItem appeared in iOS 9, inputViewController and inputAccessoryViewController in iOS 8. Didn’t get part with implementation of CoordenableViewController. Otherwise post was an interesting reading.



Friday, March 08, 19: Watched WWDC 2017 session What’s New in Swift

Trying to understand ArraySlice, watched WWDC 2017 session What’s New in Swift. This didn’t help much to understand ArraySlice but was useful anyway. Side learnings:

  • private in declaration works for all extensions in a file!!! There’s no need to use fileprivate for that!

  • it’s possible to compose a class with any number of protocols like in func f(_ controls: [UIControl & Shakeable]) {}

Working on PR for Gnosis safe realised that the only way to avoid such double conversion of JSON object (in sense of Objective-C) into Codable is to write custom Encoder which accepts not data but such JSON object and encodes it into Codable. After googling (1, 2) realised that the only way to implement it by now is copy-paste JSONEncoder.swift with minor changes. Mike Ash’s Friday Q&A 2017-07-28: A Binary Coder for Swift worth learning before jumping in.



Thursday, March 07, 19: TIL how to work properly with ArraySlice in Swift

Spent all day implementing different kinds of merge sorting in Swift. It was very useful. One of side findings is in Swift. It seems I don’t understand ArraySlice in particular I don’t understand what happens on write to ArraySlice:

var arr = Array(stride(from: 10, to: 100, by: 10))
print(arr)              // [10, 20, 30, 40, 50, 60, 70, 80, 90]
var slice = arr[3..<5]
print(slice)            // [40, 50]
arr[3] = 9
print(arr)              // [10, 20, 30, 9, 50, 60, 70, 80, 90]
print(slice)            // [40, 50]
slice[slice.indices.lowerBound] = 999
print(arr)              // [10, 20, 30, 9, 50, 60, 70, 80, 90]
print(slice)            // [999, 50]

ArraySlice is explained as ‘window’ to array itself. And it actually is. But. When array (or slice) is written to, it doesn’t influence slice (array). I didn’t understand this behavior. This makes very interesting to have a look in Swift source how Slice is implemented. Don’t see how it might be implemented just with reference to original Array storage.



Wednesday, March 06, 19: Re-watched year old Point Free episode Algebraic Data Types and Some news about contramap

Re-watched year old Point Free episode Algebraic Data Types.

Watched Some news about contramap by Point Free guys. It’s about giving contramap better name pullback.

Watched dotSwift 2019 short talk The underestimated power of keypaths. That is cool:

    people.sorted(by: their(\.lastName)) // read as 'people sorted by their last names'

That have brought me to The power of key paths in Swift.

And that have brought me to Preventing views from being model aware in Swift. It’s about creating something like UserTableViewCellConfigurator. It has nice use case for dependency injection for avoiding singletons.

And that have brought me to Avoiding singletons in Swift. Again, dependency injection is a solution. There is a solution in post how to start moving away from singletons in a non-disruptive way.

That have brought me to Testing Swift code that uses system singletons in 3 easy steps. It has very good example of testing code which uses ` URLSession.shared` singleton.

Read (yes, starting with John Sundell’s blog I can’t stop) Replacing legacy code using Swift protocols.

Watched Implementing JsonRPC with SwiftNIO. That reminds question about implementing RPC which I was asked at interview in Gnosis.



Tuesday, March 05, 19: Watched some videos from dotSwift conferences; TIL libraries Unbox, ObjectMapper, Gloss for mapping objects in Swift

Watched some videos from dotSwift conferences:

  • short video from dotSwift 2017 Subclassing structs. Title is misleading.

  • Marin Todotov’s talk from dotSwift 2017 RxSwift on iOS. debounce(_:, scheduler:) is nice! I like how Marin defines what RxSwift is:
    1. Sync-like async code
    2. With functionalaspect
  • small talk from dotSwift 2017 IOT and iOS. Nothing new.

  • talk Scientific Swift from dotSwift 2019. Curious. Nice reminder about Accelerate framework from the talk:
          import Accelerate
    
          extension Array where Element == Double {
              func sin() -> [Double] {
                  var values = [Double](repeating: 0, count: count)
                  var selfie = self
                  var selfieCount = Int32(count)
                  vvsin(&values, &selfie, &selfieCount)
                  return values
              }
          }
    
          // Playing with it in playground found that vectorised (SIMD) calculations of sin differ from scalar one. Difference is subtle, but it exists:
    
          let a = Array(stride(from: -1.0, to: 1.0, by: 0.1))
          let diff = zip(a.map(sin), a.sin()).map{ $0-$1 }
          print(diff)
          // printed this for one run (because of random input results differ between runs)
          // [0.0, 1.1102230246251565e-16, -1.1102230246251565e-16, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.1102230246251565e-16, 0.0] 
    
  • talk High performance systems in Swift. Good reminder about isKnownUniquelyReferenced(_:). Talk is mostly about implementing reference semantic for classes to speed up copying.

Working on this PR found that some nice Swift libraries for mapping objects exist (more could be found in awesome-ios):



Monday, March 04, 19: TIL Nice trick to spawn playground with shortcut; Watched Generative Art: Part 1

Nice trick to spawn playground with shortcut.

Watched Generative Art: Part 1. What these guys are doing is complete madness!



Monday, March 04, 19: Read post Swift Package Manager builds iOS frameworks

Read post Swift Package Manager builds iOS frameworks. May be times are coming when “Carthage or CocoaPods?” will not be relevant question.



Saturday, March 02, 19: Read Pitch: an Official Style Guide and Formatter for Swift

Read Pitch: an Official Style Guide and Formatter for Swift. I would agree with Dave Verver:

style guides are overrated



Friday, March 01, 19: Watched WWDC 2018 video Embracing Algorithms

Inspired by yesterday’s reading of Analyzing Complexity, watched WWDC 2018 video Embracing Algorithms. Probably, I watched it fifth time today. It’s pure gold. I should watch it again!

Every time you write a loop, replace it with a call to an algorithm. If you can’t find one, make that algorithm yourself and move the loop into its implementation.

If you want to improve the code quality in your organization, replace all of your coding standards with one goal, No Raw Loops.



Thursday, February 28, 19: Read post Analyzing Complexity by Soroush Khanlou

Read post Analyzing Complexity by Soroush Khanlou.



Wednesday, February 27, 19: Read UIView styling with functions

Nice reading UIView styling with functions.

When you use subclasses in Swift to style your views, you loose composition. For example, if you create two UIButton subclasses, FilledButton and RoundedButton, how do you create a button that is both filled and rounded?

Side story. Having this I couldn’t realise what’s going on in curly braces where filled is initialized:

struct ViewStyle<T> {
    let style: (T) -> Void
}

let filled = ViewStyle<UIButton> {
    $0.setTitleColor(.white, for: .normal)
    $0.backgroundColor = .red
}

It took some efort to get it’s just trailing closure for style parameter of default initializer:

let filled = ViewStyle<UIButton>(style: {
    $0.setTitleColor(.white, for: .normal)
    $0.backgroundColor = .red
})

Conclusion of the post at whole. After playing with it in playground for more than an hour I think that some things are rough, but approach definetly worth following it. What I would add - operations like + to compose styles easily.



Tuesday, February 26, 19: TIL prefix(while:) and "0"..."9"

It’s interesting to read Swift standard library declarations. E.g., I didn’t know about existence of prefix(while:) and I didn’t know it is possible to make a range of strings like "0"..."9". It’s never too late to mend.

let rawInput = "126 a.b 22219 zzzzzz"
let numericPrefix = rawInput.prefix(while: { "0"..."9" ~= $0 })
// numericPrefix is the substring "126"

And I don’t know a way to enumerate the range "0"..."9". enumerated() is not available because String is not Strideable. Array("0"..."9") isn’t working for the same reason. May be it does make sence. We could check if value belongs to range because we don’t need anything more then bounds for this. That’s not enough to enumerate. Swift is full of puzzles.



Monday, February 25, 19: Watched Point-Free episode #48 Predictable Randomness: Part 2

Watched Point-Free episode #48 Predictable Randomness: Part 2. Again, got very little.



Sunday, February 24, 19: TIL default memberwise initializer for a structure type is considered private if any of the structure’s stored properties are private

After PR to Gnosis for removing memberwise initialisers realised that (qouting The Swift programming language guide):

The default memberwise initializer for a structure type is considered private if any of the structure’s stored properties are private. Likewise, if any of the structure’s stored properties are file private, the initializer is file private. Otherwise, the initializer has an access level of internal.

There’s even swift_republic ruby gem to fix this Swift deficiency. As well as SwiftInitializerGenerator Xcode Source Code Extension.



Saturday, February 23, 19: Read post Swift dependency injection design pattern

Read post Swift dependency injection design pattern.

Dependency injection means giving an object its instance variables. Really. That’s it.



Thursday, February 21, 19: Watched Point-Free episode #47 Predictable Randomness: Part 1

Watched Point-Free episode #47 Predictable Randomness: Part 1. Got very little.



Wednesday, February 20, 19: Read fun post How I have interviewed hundred people, rejected everyone and only then learnt how to interview

Read fun post How I have interviewed hundred people, rejected everyone and only then learnt how to interview (Russian). It’s extremely good written.



Tuesday, February 19, 19: TIL swift-code-metrics

Read Swift code metrics about open source Python tool available on GitHub. It really has a lot of interesting metrics! But why Python and not Swift? Ok, would be nice to port it to Swift.



Monday, February 18, 19: TIL how to extend all floating point types at ones in Swift

About a month ago, on 13 of January, I have written about exnending all float types (Float, CGFloat, Double and Float80) at once by extending FloatingPoint. This day come. After writing 100 times function for conversion from degrees to radians and vise versa I decided it’s time to write something generic. It turns out not to be that easy.

Intension is to write following, but generic:

extension Double {
    var inRadians: Double {
        return self / (180.0 * Double.pi)
    }
}

This is working:

extension BinaryFloatingPoint {
    func inRadians<T>() -> T where T: BinaryFloatingPoint {
        return T(self) / (T(180.0) * T.pi)
    }
}

First, failed to make it for FloatingPoint just because haven’t found way to cast literal 180.0 (which is Double) to FloatingPoint. Strange. Second, appearance of T here is artificial. There’s no way to get rid of T and use just BinaryFloatingPoint. Third, I haven’t found a syntax to make it work for property, not for a function. Should be possible something like this, but it isn’t working:

extension BinaryFloatingPoint {
    var inRadians: <T> where T: BinaryFloatingPoint { // compiler gets mad here
        return T(self) / (T(180.0) * T.pi)
    }
}


Thursday, February 14, 19: TIL pipeline Yndex is using for turning satellite images into maps

Step by step guide of building machine learning microservice taking image in POST HTTP request and returning JSON Scala + MXNet = Microservice with neural net in prod (Russian). Dockerised. TODO: write such guide for Swift.

How to turn satellite images into maps. Computer vision in Yandex (Russian). Neural nets are used to detect buildings on aerial images: they use semantic segmentation for that instead of object detection. And there is a valid reason for that explained in post.



Wednesday, February 13, 19: Read first chapters from App Architecture book

Read first chapters from “App Architecture” book by Chris Eidhof, Matt Gallagher, and Florian Kugler. I like this definition of App architecture from the book: “the structures and tools used to bring smaller components together to form an application. ”



Tuesday, February 12, 19: TIL String in Swift has sorted() returning [Character]; Array of Equatable is Equatable

Findings of the day:

  • String has sorted() returning [Character]. First, I wasn’t expecting it having this at all. Second, I wasn’t expecting this func return array of characters but not a String. Probably I should examine all String API. Haven’t done this in a while.

  • Array of Equatable is Equatable. This is logical. But I remember implementing this on my own sime time ago. Interesting to find which Swift version broght this.



Monday, February 11, 19: Watched Swift Talk episode The Swift Talk Backend (Part 1)

Watched Swift Talk episode The Swift Talk Backend (Part 1). Guys seem to borrow topics from Point Free.



Sunday, February 10, 19: TIL UIGraphicsImageRenderer

Read post Optimizing Images. Definately I should refactor some my code using UIGraphicsImageRenderer instead of UIGraphicsBeginImageContextWithOptions. Would be nice to play with some code to see real memory savings.



Friday, February 08, 19: Read The Joel Test: 12 Steps to Better Code; The Guerrilla Guide to Interviewing (version 3.0); Sorting Resumes

The Joel Test: 12 Steps to Better Code. It’s actually questions how employer could be evaluated.

This is fun The Guerrilla Guide to Interviewing (version 3.0). It cynical and humorous.

For some reason most people seem to be born without the part of the brain that understands pointers.

As well as links from it Sorting Resumes and The Phone Screen. Joel is smart and cynical!



Thursday, February 07, 19: Read post ABI Stability and More at swift.org

At swift.org read post ABI Stability and More.



Wednesday, February 06, 19: Read Copy on Write in iOS 11

On last job interview when we discussed Swift, interviewer said that recently copy-on-write was implemenented for Foundation classes like NSMutableArray. I was surprised. Missed this somehow. That is why I googled for and came accross post Copy on Write in iOS 11. So, NSMutableArray *ar2 = [ar1 mutableCopy]; doesn’t make copy. Actual copying will be done on first change to copied array. That’s good that Swift makes Objective-C stronger.



Tuesday, February 05, 19: TIL some tricks of using macOS Character Viewer; Passed through of NSHipster’s post about using swift-sh; Returned to NSHipster’s post about TextOutputStream

TIL some tricks of using macOS Character Viewer. Control-clicking a character and choose “Copy Character Info” - it’s sweet! Don’t know why I would need this but it’s good to know that’s possible:

String(decoding: [0xF0, 0x9F, 0x98, 0x82], as: UTF8.self) // 😂.

This is nice feature as well:

"\\N{FACE WITH TEARS OF JOY}".applyingTransform(.toUnicodeName, reverse: true) // "😂".

And it’s good to remember about “Customize List…”” option which is available through Action button at the top left corner of the Character Viewer panel.

Passed through of NSHipster post about using swift-sh to manage dependencies in Swift command line scripts. It’s peice of cake to make bridge example working in command line. It might be whole cake going to refactor the script simplifying it.

Returning again to NSHipster’s post about TextOutputStream. Why print is declared as:

func print<Target>(_ items: Any..., separator: String = " ", terminator: String = "\n", to output: inout Target) where Target : TextOutputStream

and not as

func print(_ items: Any..., separator: String = " ", terminator: String = "\n", to output: inout TextOutputStream)

Swift allows both. What’s the difference? Or these are different ways to express the same?

Swift 5 gets this extention for Character making possible these:

("a" as Character).isASCII // true
("π" as Character).isASCII // false
("a" as Character).asciiValue // Optional(65)
("π" as Character).asciiValue // nil
("\t" as Character).isWhitespace // true
("\n" as Character).isNewline // true
("5" as Character).isNumber // true
("½" as Character).isNumber // true
("5" as Character).isWholeNumber // true
("5" as Character).wholeNumberValue // Optional(5)
("½" as Character).isWholeNumber // false
("½" as Character).wholeNumberValue // nil

and so on…



Monday, February 04, 19: Run through UITableView Infinite Scrolling Tutorial; Read very short introduction into Swift compiler internals

Run through UITableView Infinite Scrolling Tutorial. UITableViewDataSourcePrefetching is something I have read long ano but have never tried. Where those days when I have implemented prefetching logic manually.

Interesting post about creating 3D stereo pairs with bare C++. It’s continue of post Ray tracing with 256 lines of bare C++. It’s absolutely crazy!

Very short introduction into Swift compiler internals. Second part about Internals of front end of Swift compiler. The most interesting part that it contains link to tutorial how to implement with LLVM simple language Kaleidoscope.



Sunday, February 03, 19: Read What’s new in Swift 5.0; Read interesting post about Sowftware 2.0 or Differentiable Programming; TIL Moya - Network abstraction layer written in Swift

Read What’s new in Swift 5.0. Not too much. Those are the features that have already been implemented in the Swift 5.0 branch, but more will undoubtedly come in the months leading up to Swift 5.0’s release.

Apple’s release note for Xcode 10.2 beta is much more detailed and has more information.

Read interesting post about Sowftware 2.0 or Differentiable Programming. Original post of Andrej Karpathy Software 2.0 is much more detailed and interesting.

In the 2.0 stack, the programming is done by accumulating, massaging and cleaning datasets. … Who is going to develop the first Software 2.0 IDEs, which help with all of the workflows in accumulating, visualizing, cleaning, labeling, and sourcing datasets?

This quote reminds me my lookup of appropriate tooling for labling my own dataset of traffic signs.

Similarly, Github is a very successful home for Software 1.0 code. Is there space for a Software 2.0 Github?

That’s true as well. There’s no convinient way neither to publish dataset nor way for several people collaborate on same dataset.

Browsing links for episode #2 of Swift Community podcast accidently come to Moya - Network abstraction layer written in Swift.

You’re a smart developer. You probably use Alamofire to abstract away access to URLSession and all those nasty details you don’t really care about. But then, like lots of smart developers, you write ad hoc network abstraction layers. They are probably called “APIManager” or “NetworkModel”, and they always end in tears.

I envy people able writing such prose.

Don’t understand the need of such framework. And example code looks weird: use of NSArray without any obvious need. Will look into it.

Has to listen podcast again - don’t remember what was talked about Maya there.

Interesting how people contribute in various ways. Ole Begeman contributed with running podcast through Amazon’s Transcribe service. Interesting to give it a try once.



Saturday, February 02, 19: TIL Swift weekly newsletter; Read a couple of very promising Swift proposals

Listened issue #2 Scaling A Codeless Open Source Swift Community of of Swift Community Podcast.

Thanks to the podcast I have subscribed to swift weekly newsletter, a community-driven weekly newsletter about what’s happening in the Swift open source projects at Swift.org. It’s so unexpected to find in Swift resource in issue 126 reference of Jeremy Howard from fast.ai. Jeremy’s try to use Swift is interesting. Interesting his evaluation of Swift.

Wow, Swift discusses inclusion of ordered collections diffing. Not that I needed such functionality ever. But discussion of such complex functionality to standard library is a good sign. By the way, this could change way of updating datasource of table views in iOS and macOS.

Stephen Celis from PointFree proposes for Swift to treat keypaths expressions like functions. That’s interesting.

Fuzz tests for Swift proposal! So many crazy thing people are doing in Swift!



Friday, February 01, 19: Read fun post Initialization in C++ is Seriously Bonkers; Watched Point-Free episode The Many Faces of Flat-Map: Part 4

As a side note, not relevant to iOS, Swift, Objective-C or anything else I am doing - Thermondo. First, site is beautiful, minimalistic, hosted on GitHub pages, made with Minimal Theme. But content is what has caught me - interesting how open companies might be. Each of links from this page worth reading.

  • Work @ Thermondo – Meet our Team
  • Hiring – How to join us
  • Code of Conduct
  • Developer Style Guide
  • Our Tech Stack

Fun post Initialization in C++ is Seriously Bonkers.

Watched The Many Faces of Flat-Map: Part 4. Guys mention about the reason why flatMap in Swift standard library was renamed into compactMap. I didn’t know the story behind this rename. Interesting examples of functions fromThrowing to transform throwing function into another function returning result, and toThrowing function doing vice versa. Even examples of using these functions are bizarre I find them interesting.



Thursday, January 31, 19: Read Missing Guide on Swift Code Style

It seems non only I have thought last week about which Swift style guide we use - Missing Guide on Swift Code Style.



Wednesday, January 30, 19: Read NSHipster’s post about import in Swift

Read NSHipster’s post about import in Swift. Stuff like import func AppKit.NSUserName with importing separate entity, like func or class is discouraged by Google Swift style guide.



Tuesday, January 29, 19: Read NSHipster’s post Bundles and Packages

I’ll point NSHipster’s Bundles and Packages when have to explain someone difference between bundles and packages. Fuck, localizedInfoDictionary func exists on instance of Bundle, could be used like Bundle.main.localizedInfoDictionary["CFBundleName"].



Monday, January 28, 19: TIL xcrun simctl openurl booted maps://?s=Apple+Park opens URL with scheme associated with app, xcrun simctl addmedia booted ~/Desktop/mindblown.gif adds photo to photo library

When for whatever reason I come to NSHipster can’t refrain from reading all posts from main page. From post about simctl learned a way to open with command line an URL with schemes associated with an app xcrun simctl openurl booted maps://?s=Apple+Park. Command to add photo to photo library might be very useful xcrun simctl addmedia booted ~/Desktop/mindblown.gif. Good to know same could be done with dragging photo from e.g. desktop and dropping to photo app in simulator.



Sunday, January 27, 19: TIL Apple’s Swift standard library, Google’s, Official raywenderlich.com, Linkedin and Coursera Swift Style Guides; TIL API Design Guidelines from Swift.org

Yesterday I was asked at job interview which style guide I use for Swift. I don’t know which one. I don’t know even which exist. I definitely use some because I can’t refrain from fixing function call to trailing closure syntax or to add space before opening curly brace. The question is what’s the name of style guide I use. I started to google to name swift style guides available.

  1. Google’s Swift Style guide which is based on Apple’s Swift standard library style. Now I know which style guide I use: Apple’s Swift standard library style. Or one required by default by swiftlint tool.

  2. The Official raywenderlich.com Swift Style Guide.

  3. Linkedin Swift Style Guide.

  4. Coursera Swift coding guidelines. Wow, it’s so short!

And that’s it!

Swift.org has API Design Guidelines, which should be mentioned here.

A book Swift Style: An Opinionated Guide to an Opinionated Language by Erica Sadun should be mentioned. But because the book is of 2017 and style itself is not available without buying a copy of book, this doesn’t count.



Saturday, January 26, 19: Made to some PRs in Spotify stuff as preparation to next round of job interview with them

Traveled, but made to some PRs in Spotify stuff as preparation to next round of job interview with them.



Thursday, January 24, 19: TIL cmark CLI; Read TextOutputStream post in NSHeapster

Looking for replacement for pandoc installed cmark. For my use cases it works better transforming .md into .html. The only inconvenience is absence of headers, but that not a big deal.

Read TextOutputStream post in NSHeapster.

Hipster asks, did you know that the actual signature of print is print(_:separator:terminator:)? Yes I did know that and I am using it regularly. Or that it had a variant named print(_:separator:terminator:to:)? Noooooo! to parameter is for printing into String. Actually not to a String but to a TextOutputStream to which String conforms to. I used to write String(format:), or a loop, or map to build string where print(_:to:) could have been used.

Fixed what I believe is a bug in spotify’s SPTPersistentCache.



Tuesday, January 22, 19: Watched Point Free episode #44 The many faces of flatMap part 3

Watched Point Free episode #44 The many faces of flatMap part 3. This issue is a gold. Optional.init or case let used to flatten pyramid of if let and if with non optionals is what I have dreamt a long. But issue is not about these but about how to get rid of these at all. Sure I will return to this issue many times as well as to other issues about map, flatMap and zip.

Looking for a way to fix Xcode failing run unit tests with stupid error encountered an error (Early unexpected exit, operation never finished bootstrapping - no restart will be attempted. (Underlying error: The test runner exited with code 1 before checking in.)) came across Top 5 Command Line Tools for iOS Developer and then eventually to Facebook’s xctool. Should give it a try.



Monday, January 21, 19: TIL Do What the Fuck You Want To Public License

Ha-ha, that’s fun Do What the Fuck You Want To Public License. This is from this great post Tracer in 256 lines of pure C++. Should go through this!



Saturday, January 19, 19: Watched Swift talk #135 about combined resource download and Point free episode #43 The Many Faces of Flat-Map: Part 2

Watched Swift talk #135 about combined resource download. Is it coincidence that they discuss the same as Point free guys in episode #43 The Many Faces of Flat-Map: Part 2?



Friday, January 18, 19: Read Memory safety of Swift language guide; TIL Swift runtime is able to detect conflicting accesses to memory

Interesting reading in Swift language guide about Memory safety. Tried this snippet:

var stepSize = 1

func increment(_ number: inout Int) {
    number += stepSize
}

increment(&stepSize)
// Error: conflicting accesses to stepSize

Compiles silently. But running produces following runtime error. Have never seen something similar. Good that Swift catches this conflict in runtime, bad it is not able to detect this in compile time.

Simultaneous accesses to 0x1112e2000, but modification requires exclusive access.
Previous access (a modification) started at  (0x1112e3039).
Current access (a read) started at:
0    libswiftCore.dylib                 0x00000001116f5ed0 swift_beginAccess + 469
3    swift                              0x000000010b3620d0 llvm::MCJIT::runFunction(llvm::Function*, llvm::ArrayRef<llvm::GenericValue>) + 365
4    swift                              0x000000010b368830 llvm::ExecutionEngine::runFunctionAsMain(llvm::Function*, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, char const* const*) + 1004
5    swift                              0x000000010a5bd230 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*, swift::UnifiedStatsReporter*) + 52660
6    swift                              0x000000010a5b7f10 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 7717
7    swift                              0x000000010a55f420 main + 1349
8    libdyld.dylib                      0x00007fff5ba79ed8 start + 1
Fatal access conflict detected.
0  swift                    0x000000010e33759a PrintStackTraceSignalHandler(void*) + 42
1  swift                    0x000000010e336d4e SignalHandler(int) + 302
2  libsystem_platform.dylib 0x00007fff5bc64b3d _sigtramp + 29
3  libsystem_platform.dylib 0x000000011ce8d7c7 _sigtramp + 3240266919
4  libsystem_c.dylib        0x00007fff5bb221c9 abort + 127
5  libswiftCore.dylib       0x00000001116f5ca5 swift::fatalError(unsigned int, char const*, ...) + 149
6  libswiftCore.dylib       0x00000001116f61a6 swift_beginAccess + 726
7  libswiftCore.dylib       0x00000001112e30ad swift_beginAccess + 4290695645
8  libswiftCore.dylib       0x00000001112e3048 swift_beginAccess + 4290695544
9  swift                    0x000000010b36223d llvm::MCJIT::runFunction(llvm::Function*, llvm::ArrayRef<llvm::GenericValue>) + 365
10 swift                    0x000000010b368c1c llvm::ExecutionEngine::runFunctionAsMain(llvm::Function*, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, char const* const*) + 1004
11 swift                    0x000000010a5c9fe4 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*, swift::UnifiedStatsReporter*) + 52660
12 swift                    0x000000010a5b9d35 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 7717
13 swift                    0x000000010a55f965 main + 1349
14 libdyld.dylib            0x00007fff5ba79ed9 start + 1
Stack dump:
0.  Program arguments: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -interpret ConflictingAccessToInOutParameters.swift -enable-objc-interop -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -color-diagnostics -module-name ConflictingAccessToInOutParameters 
Abort trap: 6

Another snippet doesn’t even compile.

func balance(_ x: inout Int, _ y: inout Int) {
    let sum = x + y
    x = sum / 2
    y = sum - x
}
var playerOneScore = 42
var playerTwoScore = 30
balance(&playerOneScore, &playerTwoScore)  // OK
balance(&playerOneScore, &playerOneScore)
// Error: conflicting accesses to playerOneScore

Produces following compile time errors. That’s better.

ConflictingAccessToInOutParameters2.swift:9:26: error: inout arguments are not allowed to alias each other
balance(&playerOneScore, &playerOneScore)
                         ^~~~~~~~~~~~~~~
ConflictingAccessToInOutParameters2.swift:9:9: note: previous aliasing argument
balance(&playerOneScore, &playerOneScore)
        ^~~~~~~~~~~~~~~
ConflictingAccessToInOutParameters2.swift:9:9: error: overlapping accesses to 'playerOneScore', but modification requires exclusive access; consider copying to a local variable
balance(&playerOneScore, &playerOneScore)
        ^~~~~~~~~~~~~~~
ConflictingAccessToInOutParameters2.swift:9:26: note: conflicting access is here
balance(&playerOneScore, &playerOneScore)
                         ^~~~~~~~~~~~~~~


Thursday, January 17, 19: Read “The Pragmatic Programmer” Is Essential Reading for Software Developers and Swift CoreNFC as quick as possible

Went through blog post “The Pragmatic Programmer” Is Essential Reading for Software Developers which reminded me I have reread this book again.

Went trough Swift CoreNFC as quick as possible blog post with testing NFC reader in iOS app. Post has small mistake. The first step with enabling NFC reading in developer.apple.com for App ID is not needed. As soon as the feature is enabled in Xcode for the app, this is set in developer.apple.com for app as well.



Wednesday, January 16, 19: Read the first chapter of Machine Learning with CoreML book

Passing over the first chapter of Machine Learning with CoreML book a couple of days ago I spotted immediately that this function might be written shorter, meaning reduce should be just reduce(0, +) and having blurred feelings that map might be shorter.

func calcSimilarity(userRatingsA: [String:Float], userRatingsB:[String:Float]) -> Float{
    let distance = userRatingsA.map( { (movieRating) -> Float in
        if userRatingsB[movieRating.key] == nil{
            return 0
        }
        let diff = movieRating.value - (userRatingsB[movieRating.key] ?? 0)
        return diff * diff
    }).reduce(0) { (prev, curr) -> Float in
        return prev + curr
    }.squareRoot()
    return 1 / (1 + distance)
}

I wasn’t expecting it’s possible to turn it into oneliner:

func calcSimilarity(userRatingsA: [String:Float], userRatingsB: [String:Float]) -> Float {
    let distance = userRatingsA.merging(userRatingsB){$0 - $1}.map{$0.value}.map{$0 * $0}.reduce(0.0, +).squareRoot()
    return 1.0 / (1.0 + distance)
}

Testing refactored function I couldn’t get why results differ from original one. Until I have found out that original implementation is incorrect. This lead to openning issue and pull request for fixing it.

Exploring Swift.org found out that swift-corelibs-foundation welcomes writing unit tests to improve test coverage.

Attended Cocoaheads Berlin January 2019 meetup. The first talk was boring. Talk “DIY Build System for iOS Apps” by Vojta Stavik was quite interesting. It was about building iOS app with command line tools by steps, like compile source files, compile resources, copy runtime(for swift), sign, install in simulator or device. After this talk I can’t answer question: “Why have I thought it’s difficult?”. There’s no practical implication after talk. But it was curious. Slide with app recognising bank notes in the last talk “Creating an Augmented Reality football game with ARKit + CoreML” lead to idea adding similar feature to my abandoned CashCalk app.



Tuesday, January 15, 19: TIL Overflow operators in Swift language guide

Innocent code i += 1. What might be wrong with it? Definately, overflow. In Objective-C developer should anticipate where overflow might happen. Otherwise it just happens silently:

Equal Swift code doesn’t even compile. Compiler is smart enough to detect overflow here:

When value isn’t available in source code compiler isn’t that helpful.

The truth is these snippets are not equal. Objective-C as well as C doesn’t care about overflow. It’s burden of developer to anticipate possible overflow and deal with it. Swift, contrary, raises exception on overflow in arithmentic operations. And this code is not throwable, exception can’t be cought.

App just crashes on overflow. That’s main difference between similar looking Objective-C code:

Swift code behaving similar to one in Objective-C is looking like below. These operators are called in Swift language guide overflow operators.

What are not reflected in Swift language guide are arithmetic operations with reporting overflow:

It might be interesting interview question to ask if there any difference in behaviour of operator i += 1 in Swift and Objective-C.



Monday, January 14, 19: TIL what’s result of -9 % 4 in Swift

Hm. I understood hash in Cartfile as requirement of exact version with commit specified by its hash. Why then it gets updated with carthage update?

This might be Swift interview question: “What’s result of -9 % 4? I didn’t know about difference between module and remainder.



Sunday, January 13, 19: TIL FloatingPoint protocol in Swift; Read Training YOLOv3 for custom objects

Minor PR to Aerial.

Cope with the first chapter of Machine Learning with CoreML book. Later fixed link to cover book if repo with code from book.

Refactoring stupid snippet from the first chapter I jumped to Math.Floating where found about FloatingPoint protocol (Float, Double and Float80 conform to it). Float80 - that’s new for me! As well as BinaryFloatingPoint from there. Conclusion from browsing this file: instead of extending Float and/or Double with some functions one should consider defining this functions over FloatingPoint making new functionality available to all float types.

Just on time comes post about training YOLOv3 for custom objects. Hope to have time follow this tonight.



Saturday, January 12, 19: TIL different kinds of ranges in Swift

Watched first video from missed Vapor meetup. 0... - that’s new for me. It seems I have read about this kinds of ranges but have forgotten. TIL this range is called PartialRangeFrom. Beside regular half-open range Range swift also has PartialRangeThrough, PartialRangeUpTo, and UnboundedRange_, yes, with undersscore at the end. There’re also CountableRange, CountablePartialRangeFrom.

TIL Swift has a thing called DefaultIndices, a collection of indices for an arbitrary collection.

TIL Swift’s RangeExpression protocol has relative(to:) function which allows to convert range expression which might be missing one of one or both of its endpoints, into a concrete range that is bounded on both sides.

let numbers = [10, 20, 30, 40, 50, 60, 70]
let upToFour: PartialRangeUpTo<Int> = ..<4
print(upToFour) // PartialRangeUpTo<Int>(upperBound: 4)
let r1: Range<Int> = upToFour.relative(to: numbers)
print(r1) // 0..<4


Friday, January 11, 19: Watched Swift talk episode about chaining downloads

Accidentally found Xcake - tool for creating Xcode’s .pbxproj files. Didn’t like it because it’s rubi. But this reminded me about similar tools written in Swift: XcodeGen and Xgen (the last is by John Sundell). Both are reguary updated. Connected John Sundell’s project Marathon solves problem where to store Swift command line scripts. That’s sweet! John even has repo with examples of scripts which could be placed to Marathon.

A try without catch? I am missing something?

Watched swift talk episode about chaining downloads. Worth watching it again and playing in playground.

When looking for a way to add Firebase with Carthage found this. Have never seen this before. Anyway, integrating Firebase is a nightmare!



Thursday, January 10, 19: Read Bundle programming guide

Read Bundle programming guide.



Wednesday, January 09, 19: TIL SSH tunnels; For exercise implemented singly linked lists in Swift and tortoise and hare algorithm (aka Floyd’s algorithm) for detecting loops in lists algorithm

Implemented SinglyLinkedList in Swift. Just to train implementing tortoise and hare algorithm (aka Floyd’s algorithm) for looking loops in lists. It was good exercise. List it is not something you work often in Swift.

Read interesting post Practical advises, examples and SSH tunnels. Especial gems:

  • reverse tunnel ssh -v -R 0.0.0.0:1999:127.0.0.1:902 192.168.1.100 user@remoteserver
  • copying identity on remote server ssh-copy-id user@remoteserver
  • remote command execution localhost:~$ ssh remoteserver "cat /var/log/nginx/access.log"
  • copy (tared) local folder on remote server tar -cvj /datafolder | ssh remoteserver "tar -xj -C /datafolder"
  • editing remote files locally vim scp://user@remoteserver//etc/hosts (read explanation in #15 there)
  • mounting remote as local folder over ssh sshfs user@remoteserver:/media/data ~/data/ failed to make it work on OSX.


Tuesday, January 08, 19: Watched issue #42 of Point-free The many faces of flatMap Part 1

Watched issue #42 of Point-free The many faces of flatMap Part 1.



Monday, January 07, 19: TIL keystrokes for Bash for clearing command line

TIL keystrokes for Bash for clearing command line:

  • Ctrl+U to clear up to the beginning;
  • Ctrl+W to delete just a word;
  • Ctrl+C to cancel;
  • Alt+Shift+# to make input a comment and keep it in history.

Note to future self with macOS command line to clone permissions: chmod ``stat -f %A fileWithPerm`` fileToSetPerm.



Saturday, January 05, 19: TIL iOS stuff could be used for detecting traffic signs rectangles

While working on PR to WeScan checked how WeScan (which actually uses iOS goodies) could cope with detecting traffic signs as rectangles. It’s quite promising. Seems I could use this to detect candidates for signs detection:



Friday, January 04, 19: Read post The Complete Guide to iOS and Swift Job Interviews by Paul Hudson

Read post of Paul Hudson, hacking-with-swift-guy, The Complete Guide to iOS and Swift Job Interviews. Worth keeping a bookmark. Found Antoine van der Lee, one of maintainers of WeScan, to which I have contributed to, was interviewed in the post.

That’s why I jumped to WeScan, downloaded last changes. Looked to comments of Antoine to my PRs to check if he was that nice with me how he pretends to be in the interview. He really was! Maid PRs: minor fix, another minor fix for WeScan. The last one resulted in long discussion in comments. That might be a reason to fix Swift documentation for min and max funcs.



Thursday, January 03, 19: TIL git reflog

Came across post about git basics Just enough Git to be (less) dangerous and decided to keep a bookmark to share when someone asks stupid basic question about git. Wait. I have learnt git reflog from this post! And set conflictstyle = diff3 in [merge] section of my .gitconfig. And colors set as well. Funny hack of storing empty file .keep to force git store empty folder.

Read ancient but interesting post How Apple Cheats about how Apple using iPad only UIPopoverController in some apps on iPhone. Post in outdated but nonetheless interesting.

Interesting post Doom of SceneKit. Hope to come back to this bookmark when I start using SceneKit in my app for testing traffic rules.

Repo with links to open source OSX apps might be useful some time.

Installed SwiftRewriter. Should give it a try.



Sunday, December 23, 18: Read Introduction To Swift Memory Layout

Read Introduction To Swift Memory Layout. Haven’t learnt anything new.



Saturday, December 22, 18: Watched Point Free Episode #41 A tour of snapshot testing; TIL xed CLI to run Xcode

Watched Episode #41 of Point Free about snapshot testing.

  • Side learning - xed CLI utility to run Xcode. It exists since Xcode 3. Interesting how have I missed it.

  • In issue guys write snapshot tests for attributed strings library. Library on its own worth giving it a try. About snapshot testing. Definitely I should use it!

  • Fuck. Initialiser UIImage(named:) has two more optional parameters, bundle and compatibleWith. I always have been opening images not from main bundle in two steps: building path and loading image with UIImage(contentsOfFile:).



Friday, December 21, 18: TIL Bloom filter

TIL Bloom filter - very interesting data structure. Never heard of it. Google uses it in BigTable for avoiding costly disk look ups.



Friday, December 21, 18: Watched Swift talk about building Dijkstra path

Watched Swift talk about building Dijkstra path. I have implemented this several times and would be interesting to match this implementation with my own. Unfortunately I have failed to find where I have implement Dijkstra))).



Monday, December 17, 18: TIL how to extract speech from youtube video ans transform speech into text

Came across Interesting example of processing youtube videos to extract speech and transform speech into text (Russian). Tensorflow, code presents.



Sunday, December 16, 18: TIL image segmentation

Interesting exercise on image segmentation. Worth trying myself.



Wednesday, December 12, 18: TIL how to make screen saver in Swift; read several post about secure development

Run all steps of creating screen saver in Swift with help of Saving your screen. Tree lessons learnt:

  • writing screen saver in Swift remember to change Principal class value in Info.plist to ModuleName.ScreenSaverView;
  • set Always Embed Swift Standard Libraries to YES in build settings;
  • never ever use emoji in class name or target name.

Read post Secure Development Is Dead, Long Live Secure Development by Anastasiia Vixentael. Really boring. Zero new knowledge. Post The Weakest Link from the same issue of De Programmatica Ipsum was much more interesting. Not practical, but entertaining.

Nice short post Mac Sandboxing: Privileged File Operations about special keys in entitlements in OSX app bundle to allow out of SandBox file operations. These keys are com.apple.developer.security.privileged-file-operations and com.apple.security.automation.apple-events.

While writing unit tests for Date extension in Parkling app came across post Time traveling in Swift unit tests which helped me a lot. TODO: read follow up post Simple Swift dependency injection with functions.

TIL Playground Graphs. That’s nice!



Tuesday, December 11, 18: TIL Amazon S3 vs EBS vs EFS; TIL AWS instances spot market

TIL Amazon S3 vs EBS vs EFS differences between Amazon S3, Amazon EFS, and Amazon EBS. Amazon S3 is a scalable, durable, highly available, publicly accessible data storage. Amazon EBS is a storage for the drives of your virtual machines. Amazon EFS is automatically scalable storage which you can mount EFS to various AWS services and access it from various virtual machines.

Browsed Howto: Automated AWS spot instance provisioning with persisting of data about automating acquiring AWS spot instance and run ML task on it. I should practice it.

Read similar post How to train Deep Learning models on AWS Spot Instances using Spotty?. Should examine spotty github repo if it universal and could actually run whatever I feed it.

One more similar post Deep Learning on Amazon EC2 Spot Instances Without the Agonizing Pain. It mentions another tool for automating routine tasks associated with the management of Spot Instances.



Monday, December 10, 18: TIL a lot about integers in Swift

Writing unit tests have found that there’s no such thing like Int.random(), only things like Int.random(in:). Findings after small research:

  • Instead of Int.random(in: Int.min ... Int.max) one could write Int.random(in: .min ... .max).
  • Exclusion of random() was deliberate decision to protect users from a common error called modulo bias.
  • There’s one random(), Bool.random().
  • Before Swift 4.2 people were using GameplayKit to shuffle arrays. GameKit has shaped random number generators, like GKGaussianDistribution or GKShuffledDistribution.
  • There’s a bunch of initializers of numeric types, like Int8(exactly: 1_000), Int8(clamping: 500), Int8(truncatingIfNeeded: q).
  • That is smart use of generic public static func >> <RHS>(lhs: Self, rhs: RHS) -> Self where RHS : BinaryInteger.
  • Quotient /ˈkwoʊʃənt/ is a term of a result of division, “Частка” in Ukrainian, “Частное”” in Russian.
  • signum() returns -1, 0 or 1.
  • quotientAndRemainder(dividingBy: n) returns tuple (quotient, remainder).
  • interesting example inside of FixedWidthInteger:
    extension FixedWidthInteger {
      var binaryString: String {
          var result: [String] = []
          for i in 0..<(Self.bitWidth / 8) {
              let byte = UInt8(truncatingIfNeeded: self >> (i * 8))
              let byteString = String(byte, radix: 2)
              let padding = String(repeating: "0",
                                       count: 8 - byteString.count)
              result.append(padding + byteString)
          }
          return "0b" + result.reversed().joined(separator: "_")
      }
          }
    
  • and here goes my first PR into Swift fixing follow up comment for above mentioned snippet for binaryString.
  • FixedWidthInteger has set of operations like addingReportingOverflow(n) returning tuple (partialValue: Self, overflow: Bool). And multipliedFullWidth(n) returning tuple (high: Self, low: Self.Magnitude) as well as a little bit trickier dividingFullWidth. Don’t understand these two. But hope I will recall this when I need to deal with overflows in miltiplication and/or division.
  • leadingZeroBitCount and nonzeroBitCount might be useful. As well as bigEndian, littleEndian, byteSwapped.
  • Interesting to remember about existence of initializers like Int("-123", radix: 8) where radix could be from range 2...36. Why not up to 64? TODO: look into implementation. Important to remember that string parameter should be trimmed otherwise it fails!
  • Operations like masking addition assignment operator &+= exist. Swift programming language book refers these as Overflow Operators while documentation - Advanced Operators.
  • words property exists in integer types. It’s collection of words representing integer type.

May be once I will have time to browse all 40K lines of Integer in Swift.



Friday, December 07, 18: TIL using IBM Watson and Azure to train models for CoreML

Taken small research on using eGPU with Turi Create. It seems Thunderbolt 3 or USB-C MacBook Pro needed to connect eGPU. I am out of game.

Interesting post about using IBM Watson to train models for CoreML Machine Learning in iOS: IBM Watson and CoreML. Don’t see sense for this having CreateML and Turi Create. May be reason is that training uses all power of GPUs at Watson. Follow up post about using Azure for same purpose Machine Learning in iOS: Azure Custom Vision and CoreML. And one more follow up about using Turi Create Machine Learning in iOS: Turi Create and CoreML.

Interesting post When to Avoid Libraries.

Useful post Attributed String with Style. Not only about NSAttributedString, but about splitting configuring UserTableViewCell in UserTableViewCellViewModel, UserTableViewCellViewModelMapper and something AttributedStringStyler. Good site, by the way, created with Jekyll using using the Tale theme.

I should read about coordinators in this blog!



Thursday, December 06, 18: Watched several interesting videos from try! Swift NYC 2018 conference

Interesting post Debouncing in Swift while your iOS app is in the background. I have been doing something similar implementing auto-completion, but not for background.

Video from try! Swift NYC 2018 Strings Seven Ways. I should use this:

struct Identifier<Value>: Equatable, Hashable where Value : Equatable & Hashable { 
	private let value: Value 
} 

struct Product { 
	let identifier: Identifier<String> 
}

Watched Swift Services are Simple from try! Swift NYC 2018 about Kitura.

Watched Super Resolution with CoreML from try! Swift NYC 2018. He has created Framework SuperResolutionKit for this.

Watched Let Them Say What They Want: Adding Siri Shortcuts from try! Swift NYC 2018. It will be useful to re-watch this when I come to implementing this in Parkling.



Tuesday, December 04, 18: TIL imgaug library for augmenting images

Interesting to explore why this compiles:

extension Array where Element: Equatable {
    // For empty array returns false
    var allEqual: Bool {
        if let firstElem = first {
            return !dropFirst().contains { $0 != firstElem }
        }
        return false
    }
}

While this isn’t:

extension Array where Element == Equatable {
    // For empty array returns false
    var allEqual: Bool {
        if let firstElem = first {
            return !dropFirst().contains { $0 != firstElem }
        }
        return false
    }
}

Giving error Binary operator '!=' cannot be applied to two 'Equatable' operands.

Came across library imgaug for augmenting images. Great that it deals with bounding boxes! That exactly what I need (contains referral for 100$ at digitalocean).



Thursday, November 29, 18: TIL using Turi Create

Watched A Guide to Turi Create. Tried to create Jupyter notebook for training first model for object detector for traffic signs. Read turicreate documentation about object detector and preparing data.



Wednesday, November 28, 18: Read How to Prepare for a Technical Interview at Facebook; Dug in sources of Swift standard library

Read How to Prepare for a Technical Interview at Facebook I was caught up with solution:

func isStringUnique(_ s: String) -> Bool {
    return s.count == Set(s).count
}

That’s why I have jumped to source of Swift standard library to check complexity of Set.init(_: Array).

Side note, why they use both Dictionary<Key, Value> and [Key : Value] in same source file: mutating func remove(at index: Dictionary<Key, Value>.Index) -> [Key : Value].Element and mutating func removeValue(forKey key: [Key : Value].Key) -> [Key : Value].Value? It sounds like a good point for experimentation with compiling Swift.

Interesting comment to lazy property of Dictionary:

/// A view onto this collection that provides lazy implementations of
/// normally eager operations, such as `map` and `filter`.
///
/// Use the `lazy` property when chaining operations to prevent
/// intermediate operations from allocating storage, or when you only
/// need a part of the final collection to avoid unnecessary computation.
public var lazy: LazyCollection<Dictionary<Key, Value>> { get }

Swift standard library worth looking into all header files!!!

Again, caught with comment

/// Creates a new set from a finite sequence of items.

Are there infinite sequences?

And I haven’t found answer about complexity of Set.init(_: Array).

Returning to isStringUnique, there’s follow up Code Challenge: Using ASCII & Unicode with Swift. I didn’t get why his THE UNICODE APPROACH implementation is correct. In particular, guard to count less then 128. Or I am missing something or this implementation is incorrect. I have checked everything in playground and have an example of a string which produces wrong result.



Tuesday, November 27, 18: Read Where the &$!#% is Localizable.strings?!?; Read Unit testing retain cycles; Read Clustarisation: algorithms k-means and c-means

Read Where the &$!#% is Localizable.strings?!?.

Read Clustarisation: algorithms k-means and c-means. Post mentions XLIFF format which I was not aware of.

Read Unit testing retain cycles. Nothing new. And I haven’t got the last snippet.

Not practical but curious visualization of bezier curves The Ever so Lovely Bézier Curve.



Monday, November 26, 18: Read iOS 11: Machine Learning for everyone; Read Why learn algorithms?; Read One-shot object detection

Read iOS 11: Machine Learning for everyone. Mostly it’s self-advertising but has useful info as well.

Read Why learn algorithms? with real examples when knowing algorithms needed for making real iOS app. Would be interesting to write same post about my experience.

Read One-shot object detection. TODO: http://machinethink.net/blog/object-detection-with-yolo.



Friday, November 23, 18: TIL date formatters in Swift leaking important details; Read Using unit tests to identify & avoid memory leaks in Swift

Interesting post Sneaky date formatters exposing more than you think. If you refactor date formatter into property and make it let, formatter still can by changed because it’s class. It could lead interesting consequences when some part change formatter thinking they change local copy.

Read post Using unit tests to identify & avoid memory leaks in Swift. Havn’t got everything, especially about closures.

Read post Capturing objects in Swift closures discussing some alternatives to weakly capture self on closures. Haven’t got everything. But might return here later on.

Interesting blog of iOS developer with very narrow specialisation - deep learning on iOS. One of services he provides - converting neural nets to run on iOS devices. Definitely I should keep an eye on this blog. It has very interesting and useful post about one-shot networks like YOLO. And post specifically about YOLO.

Interesting post about MVC on iOS iOS Development and the Wrong Kind of MVC.

Interesting post UIGraphicsImageRenderer, about block based API on CGContext.

Very interesting post Re-creating the Siri Shortcuts Drawer Interaction about building drawer like in Shortcuts app from Apple. Worth further reading and step by step recreation. And it draws attention to how good Shortcuts app is. I should give it a try.

This post about creating infinite scroll view Custom UI Master Class: Infinite Paging Scroll View worth keeping a bookmark on. Haven’t read this carefully.

A Swift MVVM Tutorial just saved for further reading.

Very useful post of John Sundell Avoiding race conditions in Swift. Fuck! private extension! Whole extension can be private! TODO: follow-ups of that post are Unit testing asynchronous Swift code, and Mocking in Swift and Reducing flakiness in Swift tests.

AloeStackView of AirBnB worth trying. AirBnB writes about motivation of developing this in post.

What’s New in Storyboards 401 WWDC 2015 video:

  • Storyboard references (connections between scenes in different storyboards or in one complex storyboard).
  • 7:00 shows interesting custom container view controller which manages several “tabs”. Might be very interesting to build this myself.
  • if view controller doesn’t have view, runtime falls back to loadView method.


Thursday, November 22, 18: Read Swift: Why You Should not Use Default Implementations in Protocols; Watched WWDC 2018 401 session video What’s New in Swift, 403 session video What’s New in Testing and 703 session video Introducing Create ML

Read Swift: Why You Should not Use Default Implementations in Protocols and its friend Swift: Alternative to Default Implementations in Protocols.

Watched WWDC 2018 401 session video What’s New in Swift. I watched it already. But here are things which seem new for me:

  • SWIFT_DETERMINICTIC_HASHING
  • Int.random(in: 0..<10)
  • Float.rand(in: -10.0..<10.0)
  • RandomNumberGenerator protocol which could be passed to random and shuffled
  • #if canImport(UIKit)
  • #if hasTargetEnvironment(simulator)

Watched WWDC 2018 403 session video What’s New in Testing. Nothing new this time, or, better say, nothing close to my current priorities.

Watched WWDC 2018 703 session video Introducing Create ML. Not first time. So nothing new this time. Should give it real try.



Wednesday, November 21, 18: Read Natasha the Robot’s post Swift: When to use guard vs if; Watched Everything a Swift Dev Needs to Know About Machine Learning

Read Natasha the Robot’s post Swift: When to use guard vs if. Her approach pretty much matches mine. Reading article I have found "Coffee Break".localized() which I should definitely use!

Watched Everything a Swift Dev Needs to Know About Machine Learning. Didn’t worth spending time. The only output - references on Videos of Siraj that shows a lot of simple projects made with just a few lines of code and Tutorials of Tensor Flow.



Tuesday, November 20, 18: Read Ranges and Intervals in Swift

Read Ranges and Intervals in Swift about difference between Range (which are collections) and Interval (which are not) in Swift 2. Interval were represented by protocol IntervalType and two implementations HalfOpenInterval and ClosedInterval. Post refers to very interesting gist by Nate Cook.

Updated version of above post, Ranges in Swift 3. Post mentions already implemented in Swift 3 A New Model for Collections and Indices - quite interesting and useful reading.



Monday, November 19, 18: TIL nuances how UserDefaults works in Screen Saver on macOS

While working on PRs to Aerial spent some time exploring why UserDefaults has to call synchronize (contrary to what is stated Developer documentation) before closing ScreenSaverView. Hope to write a post about this.



Saturday, November 17, 18: Watched WWDC 2018 session video 703 Introducing Create ML

Watched WWDC 2018 session video 703 Introducing Create ML. I should try to train some simple classifier with my data om Mac. And give it a try on Ubuntu in command line.



Friday, November 16, 18: Watched WWDC 2018 session video 408 Building faster in Xcode 10

Watched WWDC 2018 session video 408 Building faster in Xcode 10. Somehow xcodebuild -showBuildTimingSummary doesn’t work for me. It just rebuilds project. Nothing else really interested.

Watched WWDC 2018 session video 401 What’s New in Swift.

Interesting finding Guides to contributing to Apple/Swift. Some posts are only available for patrons.



Thursday, November 15, 18: TIL contextual actions in Xcode

What are these actions in Xcode 10??? UPDATE: I am stupid! Xcode is showing some contextual actions, like “Discard Change” here. And list of actions could be filtered by typing in Actions text field. I have thought it’s for entering command line actions.

Post of John Sundell about @autoclosure reminded about safe feature of extracting values from dictionaries which I have forgotten about: letterCounts[letter, defaultValue: 0] += 1.

Happy finally to use Dictionary(grouping: students, by: { $0.first! }). But then had to remove that code.



Wednesday, November 14, 18: Read Chapter 2 of RxSwift book

Interesting project Aerial screen saver where I could contribute. Definitely I should merge core feature of Motivation.

Cope with Chapter 2 of RxSwift book.



Tuesday, November 13, 18: Read NSHipster’s post UIFieldBehavior; Read Chapter 1 of RxSwift book

Read NSHipster’s post UIFieldBehavior. It’s about UIDynamics. Have never touched this. Interesting that I have implemented behavior similar to described in article manually about 5 years ago.

Read Chapter 1 of RxSwift book. Decided to go a chapter per day.