Skip to content

Instantly share code, notes, and snippets.

import Foundation
// Build a HashMap like data structure with next methods
// put(key: K, value: V)
// get(key: K) -> V?
// getRandom() -> (K, V)?
// all of them with average O(1) time complexity.
class HashMap<K, V> where K: Hashable {
private var store = Dictionary<K, V>()
@emarashliev
emarashliev / AddBuildPhase.swift
Last active July 23, 2019 09:01
A swift-sh script that adds a Shell Script Build Phase to a centrist xcodeproj file.
#!/usr/bin/swift sh
import Foundation
import XcodeProj // @tuist
import PathKit
/// INSTRUCTIONS
/// install swift-sh on your mac, more info here 👉 https://github.com/mxcl/swift-sh
/// make this file executable $ chmod u+x AddBuildPhase.swift
/// then just run the file $ ./AddBuildPhase.swift
@propertyWrapper
public struct Field<Value: DatabaseValue> {
public let name: String
private var record: DatabaseRecord?
private var cachedValue: Value?
public init(name: String) {
self.name = name
}
struct FailableDecodable<Base: Decodable>: Decodable {
var base: Base?
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
base = try container.decode(Base.self)
} catch let error {
print(error)
}
var array: [EventLoopFuture<T?>] = []
// do whatever to add futures to this array
EventLoopFuture<[T]>.reduce(into: [], array, on: eventLoop) {
if let value = $1 {
$0.append(value)
}
}
@emarashliev
emarashliev / TranslateMiddleware.swift
Last active March 15, 2019 21:14
Vapor Middleware that catches thrown errors and translate them. The preferred language should be passed by `Accept-Language` header
import NStack
import Vapor
import Sugar
protocol Translatable {
var translationKey: String { get }
}
extension AuthenticationError: Translatable {
var translationKey: String {

Run an image in a new container daemonized

$ sudo docker run -d <image_name>

Run an image in interactive mode with the command /bin/bash

$ sudo docker run -i -t <image_name> /bin/bash
@emarashliev
emarashliev / RepositoryCase2.swift
Last active December 22, 2018 13:44
Repository Case 2
// The Model
final class User<D>: Model where D: Database & QuerySupporting {
typealias Database = D
typealias ID = Int
static var idKey: IDKey { return \.id }
var id: Int?
var name: String
var email: String
@emarashliev
emarashliev / RepositoryCase1.swift
Last active December 22, 2018 13:33
Repository Case 1
// The Model
final class User: Model {
typealias Database = MySQLDatabase /// the problem is this line
typealias ID = Int
static var idKey: IDKey { return \.id }
var id: Int?
var name: String
var email: String
let begin = clock()
// DO SOMETHING
let diff = Double(clock() - begin) / Double(CLOCKS_PER_SEC)
print("Execution time: \(diff)")