hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
1d69bcb7b77f9e2722c59c9a4cc6b31f31750f5e
364
// // UITableView+Extensions.swift // VGSCheckoutSDK import Foundation #if canImport(UIKit) import UIKit #endif // swiftlint:disable all internal extension UITableView { func dequeue<T: UITableViewCell>(cellForRowAt indexPath: IndexPath) -> T { return dequeueReusableCell(withIdentifier: "\(T.self)", for: indexPath) as! T } } // swiftlint:enable all
19.157895
80
0.741758
d92320cf267d29833dd8f01bfbb77649a16d095e
6,890
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared let TableClients = "clients" let TableTabs = "tabs" private let log = Logger.syncLogger class RemoteClientsTable<T>: GenericTable<RemoteClient> { override var name: String { return TableClients } override var version: Int { return 2 } // TODO: index on guid and last_modified. override var rows: String { return [ "guid TEXT PRIMARY KEY", "name TEXT NOT NULL", "modified INTEGER NOT NULL", "type TEXT", "formfactor TEXT", "os TEXT", "version TEXT", ].joined(separator: ",") } // TODO: this won't work correctly with NULL fields. override func getInsertAndArgs(_ item: inout RemoteClient) -> (String, Args)? { let args: Args = [ item.guid, item.name, NSNumber(value: item.modified), item.type, item.formfactor, item.os, item.version, ] return ("INSERT INTO \(name) (guid, name, modified, type, formfactor, os, version) VALUES (?, ?, ?, ?, ?, ?, ?)", args) } override func getUpdateAndArgs(_ item: inout RemoteClient) -> (String, Args)? { let args: Args = [ item.name, NSNumber(value: item.modified), item.type, item.formfactor, item.os, item.version, item.guid, ] return ("UPDATE \(name) SET name = ?, modified = ?, type = ?, formfactor = ?, os = ?, version = ? WHERE guid = ?", args) } override func getDeleteAndArgs(_ item: inout RemoteClient?) -> (String, Args)? { if let item = item { return ("DELETE FROM \(name) WHERE guid = ?", [item.guid]) } return ("DELETE FROM \(name)", []) } override var factory: ((SDRow) -> RemoteClient)? { return { row -> RemoteClient in let guid = row["guid"] as? String let name = row["name"] as! String let mod = (row["modified"] as! NSNumber).uint64Value let type = row["type"] as? String let form = row["formfactor"] as? String let os = row["os"] as? String let version = row["version"] as? String return RemoteClient(guid: guid, name: name, modified: mod, type: type, formfactor: form, os: os, version: version) } } override func getQueryAndArgs(_ options: QueryOptions?) -> (String, Args)? { return ("SELECT * FROM \(name) ORDER BY modified DESC", []) } override func updateTable(_ db: SQLiteDBConnection, from: Int) -> Bool { let to = self.version if from == to { log.debug("Skipping update from \(from) to \(to).") return true } if from < 2 && to >= 2 { let sql = "ALTER TABLE \(TableClients) ADD COLUMN version TEXT" let err = db.executeChange(sql) if err != nil { log.error("Error running SQL in RemoteClientsTable: \(err?.localizedDescription ?? "nil")") log.error("SQL was \(sql)") return false } } return true } } class RemoteTabsTable<T>: GenericTable<RemoteTab> { override var name: String { return TableTabs } override var version: Int { return 2 } // TODO: index on id, client_guid, last_used, and position. override var rows: String { return [ "id INTEGER PRIMARY KEY AUTOINCREMENT", // An individual tab has no GUID from Sync. "client_guid TEXT REFERENCES clients(guid) ON DELETE CASCADE", "url TEXT NOT NULL", "title TEXT", // TODO: NOT NULL throughout. "history TEXT", "last_used INTEGER", ].joined(separator: ",") } private static func convertHistoryToString(_ history: [URL]) -> String? { let historyAsStrings = optFilter(history.map { $0.absoluteString }) let data = try! JSONSerialization.data(withJSONObject: historyAsStrings, options: []) return String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) } private func convertStringToHistory(_ history: String?) -> [URL] { if let data = history?.data(using: String.Encoding.utf8) { if let urlStrings = try! JSONSerialization.jsonObject(with: data, options: [JSONSerialization.ReadingOptions.allowFragments]) as? [String] { return optFilter(urlStrings.map { URL(string: $0) }) } } return [] } override func getInsertAndArgs(_ item: inout RemoteTab) -> (String, Args)? { let args: Args = [ item.clientGUID, item.URL.absoluteString, item.title, RemoteTabsTable.convertHistoryToString(item.history), NSNumber(value: item.lastUsed) ] return ("INSERT INTO \(name) (client_guid, url, title, history, last_used) VALUES (?, ?, ?, ?, ?)", args) } override func getUpdateAndArgs(_ item: inout RemoteTab) -> (String, Args)? { let args: Args = [ item.title, RemoteTabsTable.convertHistoryToString(item.history), NSNumber(value: item.lastUsed), // Key by (client_guid, url) rather than (transient) id. item.clientGUID, item.URL.absoluteString, ] return ("UPDATE \(name) SET title = ?, history = ?, last_used = ? WHERE client_guid IS ? AND url = ?", args) } override func getDeleteAndArgs(_ item: inout RemoteTab?) -> (String, Args)? { if let item = item { return ("DELETE FROM \(name) WHERE client_guid = IS AND url = ?", [item.clientGUID, item.URL.absoluteString]) } return ("DELETE FROM \(name)", []) } override var factory: ((SDRow) -> RemoteTab)? { return { row -> RemoteTab in let clientGUID = row["client_guid"] as? String let url = URL(string: row["url"] as! String)! // TODO: find a way to make this less dangerous. let title = row["title"] as! String let history = self.convertStringToHistory(row["history"] as? String) let lastUsed = row.getTimestamp("last_used")! return RemoteTab(clientGUID: clientGUID, URL: url, title: title, history: history, lastUsed: lastUsed, icon: nil) } } override func getQueryAndArgs(_ options: QueryOptions?) -> (String, Args)? { // Per-client chunks, each chunk in client-order. return ("SELECT * FROM \(name) WHERE client_guid IS NOT NULL ORDER BY client_guid DESC, last_used DESC", []) } }
37.650273
152
0.578374
f768802dcc80447a5e6db96888b7ed3df2de3025
1,110
// Copyright 2022 Pera Wallet, LDA // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Participation.swift import Foundation import MagpieCore import MacaroonUtils final class Participation: ALGAPIModel { var selectionParticipationKey: String? var voteParticipationKey: String? init() { self.selectionParticipationKey = nil self.voteParticipationKey = nil } } extension Participation { enum CodingKeys: String, CodingKey { case selectionParticipationKey = "selection-participation-key" case voteParticipationKey = "vote-participation-key" } }
29.210526
75
0.738739
e522dbd16a6aa02abeeb01deed42631adff6b0dc
2,718
// // QRCode.swift // QRCode // import UIKit public typealias 🔳 = GXQRCodeGenerator /// QRCode generator public struct GXQRCodeGenerator { /** The level of error correction. - Low: 7% - Medium: 15% - Quartile: 25% - High: 30% */ public enum ErrorCorrection: String { case Low = "L" case Medium = "M" case Quartile = "Q" case High = "H" } /// Data contained in the generated QRCode public let data: Data /// Foreground color of the output /// Defaults to black public var color = CIColor(red: 0, green: 0, blue: 0) /// Background color of the output /// Defaults to white public var backgroundColor = CIColor(red: 1, green: 1, blue: 1) /// Size of the output public var size = CGSize(width: 200, height: 200) /// The error correction. The default value is `.Low`. public var errorCorrection = ErrorCorrection.Low // MARK: Init public init(_ data: Data) { self.data = data } public init?(_ string: String) { if let data = string.data(using: .isoLatin1) { self.data = data } else { return nil } } public init?(_ url: URL) { if let data = url.absoluteString.data(using: .isoLatin1) { self.data = data } else { return nil } } // MARK: Generate QRCode /// The QRCode's UIImage representation public var image: UIImage? { guard let ciImage = ciImage else { return nil } // Size let ciImageSize = ciImage.extent.size let widthRatio = size.width / ciImageSize.width let heightRatio = size.height / ciImageSize.height return ciImage.nonInterpolatedImage(withScale: Scale(dx: widthRatio, dy: heightRatio)) } /// The QRCode's CIImage representation public var ciImage: CIImage? { // Generate QRCode guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else { return nil } qrFilter.setDefaults() qrFilter.setValue(data, forKey: "inputMessage") qrFilter.setValue(self.errorCorrection.rawValue, forKey: "inputCorrectionLevel") // Color code and background guard let colorFilter = CIFilter(name: "CIFalseColor") else { return nil } colorFilter.setDefaults() colorFilter.setValue(qrFilter.outputImage, forKey: "inputImage") colorFilter.setValue(color, forKey: "inputColor0") colorFilter.setValue(backgroundColor, forKey: "inputColor1") return colorFilter.outputImage } }
26.910891
94
0.587564
b928f4b6d9d7658220b3c431195d4fe1ebc7d824
361
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } }
25.785714
144
0.753463
2fb3ed4f93ca56ca8821a0af3ead7d4dacca50d2
187
import Foundation public enum ActiveTool { case Smooth case Sharpen case Flatten case Emphasize case Plane case Tilt case Invert case Pan case Zoom }
13.357143
24
0.657754
56f705645a5bda1c9e38207193a48ec880c922d8
6,105
// // Renderer.swift // CreatingAndSamplingTextures // // Created by Huiping Guo on 2021/09/18. // import Foundation import MetalKit import Cocoa class Renderer: NSObject { // The device (aka GPU) used to render private var device: MTLDevice! // A pipeline object to render to the screen. private var drawableRenderPipeline: MTLRenderPipelineState! // The command Queue used to submit commands. private var commandQueue: MTLCommandQueue! // The Metal texture object private var texture: MTLTexture! // The Metal buffer that holds the vertex data. private var vertices: MTLBuffer! // The number of vertices in the vertex buffer. private var numVertices: Int! // The current size of the view. private var viewportSize: vector_uint2 = vector_uint2(x: 0, y: 0) private func loadTextureUsingAAPLImage(url: URL) -> MTLTexture? { guard let image = AAPLImage(tgaFileAtLocation: url) else { return nil } let textureDescriptor = MTLTextureDescriptor.init() // Indicate that each pixel has a blue, green, red, and alpha channel, where each channel is // an 8-bit unsigned normalized value (i.e. 0 maps to 0.0 and 255 maps to 1.0) textureDescriptor.pixelFormat = .bgra8Unorm // Set the pixel dimensions of the texture textureDescriptor.width = Int(image.width) textureDescriptor.height = Int(image.height) // Create the texture from the device by using the descriptor let inputTexture = device.makeTexture(descriptor: textureDescriptor) // Calculate the number of bytes per row in the image. let bytesPerRow: Int = Int(4 * image.width) let region = MTLRegion(origin: MTLOrigin(x: 0, y: 0, z: 0), size: MTLSize(width: textureDescriptor.width, height: textureDescriptor.height, depth: 1)) // Copy the bytes from the data object into the texture let bytes = (image.data as NSData).bytes inputTexture?.replace(region: region, mipmapLevel: 0, withBytes: bytes, bytesPerRow: bytesPerRow) return inputTexture } init(mtkView: MTKView) { super.init() device = mtkView.device guard let imageFileLocation = Bundle.main.url(forResource: "Image", withExtension: "tga") else { return } texture = self.loadTextureUsingAAPLImage(url: imageFileLocation) // Set up a simple MTLBuffer with vertices which include texture coordinates let quadVertices: [(simd_float2,simd_float2)] = [ // Pixel positions, Texture coordinates (simd_float2( 250, -250),simd_float2(1.0, 1.0)), (simd_float2(-250, -250),simd_float2(0.0, 1.0)), (simd_float2( -250, 250),simd_float2(0.0, 0.0)), (simd_float2(250, -250),simd_float2(1.0, 1.0)), (simd_float2(-250, 250),simd_float2(0.0, 0.0)), (simd_float2( 250, 250),simd_float2(1.0, 0.0)), ] // Create a vertex buffer, and initialize it with the quadVertices array self.vertices = device.makeBuffer(bytes: quadVertices, length: quadVertices.count * MemoryLayout<(simd_float2,simd_float2)>.size, options: .storageModeShared) // Calculate the number of vertices by dividing the byte length by the size of each vertex numVertices = quadVertices.count /// Create the render pipeline. // Load the shaders from the default library let defaultLibrary = device.makeDefaultLibrary() // Set up a descriptor for creating a pipeline state object let pipelineStateDescriptor = MTLRenderPipelineDescriptor.init() pipelineStateDescriptor.label = "Texturing Pipeline" pipelineStateDescriptor.vertexFunction = defaultLibrary?.makeFunction(name: "vertexShader") pipelineStateDescriptor.fragmentFunction = defaultLibrary?.makeFunction(name: "samplingShader") pipelineStateDescriptor.colorAttachments[0].pixelFormat = mtkView.colorPixelFormat do { self.drawableRenderPipeline = try device.makeRenderPipelineState(descriptor: pipelineStateDescriptor) } catch { assert(false, "Failed to create pipeline state to render to screen: \(error)") } commandQueue = device.makeCommandQueue() } } extension Renderer: MTKViewDelegate { func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { // Save the size of the drawable to pass to the vertex shader. viewportSize.x = UInt32(size.width) viewportSize.y = UInt32(size.height) } func draw(in view: MTKView) { let commandBuffer = commandQueue.makeCommandBuffer() commandBuffer?.label = "Command Buffer" let drawableRenderPassDescriptor = view.currentRenderPassDescriptor! let renderEncoder = commandBuffer?.makeRenderCommandEncoder(descriptor: drawableRenderPassDescriptor) renderEncoder?.label = "Drawable Render Pass" // Set the region of the drawable to draw into. renderEncoder?.setViewport(MTLViewport(originX: 0, originY: 0, width: Double(viewportSize.x), height: Double(viewportSize.y), znear: -1.0, zfar: 1.0)) renderEncoder?.setRenderPipelineState(drawableRenderPipeline) renderEncoder?.setVertexBuffer(vertices, offset: 0, index: 0) renderEncoder?.setVertexBytes(&viewportSize, length: MemoryLayout<vector_uint2>.size, index: 1) // Set the texture object. The AAPLTextureIndexBaseColor enum value corresponds /// to the 'colorMap' argument in the 'samplingShader' function because its // texture attribute qualifier also uses AAPLTextureIndexBaseColor for its index. renderEncoder?.setFragmentTexture(texture, index: 0) // Draw the triangles. renderEncoder?.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: numVertices) renderEncoder?.endEncoding() // Schedule a present once the framebuffer is complete using the current drawable commandBuffer?.present(view.currentDrawable!) // Finalize rendering here & push the command buffer to the GPU commandBuffer?.commit() } }
37.22561
162
0.69959
9b3afd7fe2a577eba2205244198ac5b0b104bb3c
15,156
//=== HCSR04.swift --------------------------------------------------------===// // // Copyright (c) MadMachine Limited // Licensed under MIT License // // Authors: Ines Zhou // Created: 11/12/2021 // // See https://madmachine.io for more information // //===----------------------------------------------------------------------===// import SwiftIO /// The library for DS3231 real time clock. /// /// You can read the time information including year, month, day, hour, /// minute, second from it. It comes with a battery so the time will always /// keep updated. Once powered off, the RTC needs a calibration. The RTC also /// has two alarms, you can set them to alarm at a specified time. final public class DS3231 { private let i2c: I2C private let address: UInt8 private var daysInMonth: [UInt8] = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] private var readBuffer = [UInt8](repeating: 0, count: 7) /// Initialize the RTC. /// - Parameters: /// - i2c: **REQUIRED** The I2C interface the RTC connects to. The maximum /// I2C speed is 400KHz. /// - address: **OPTIONAL** The sensor's address. It has a default value 0x68. public init(_ i2c: I2C, _ address: UInt8 = 0x68) { let speed = i2c.getSpeed() guard speed == .standard || speed == .fast else { fatalError(#function + ": DS3231 only supports 100kHz (standard) and 400kHz (fast) I2C speed") } self.i2c = i2c self.address = address } /// Set current time to calibrate the RTC. /// /// If the RTC has stopped due to power off, it will be set to the /// specified time. If not, the time will not be reset by default. /// If you want to make it mandatory, you can set the parameter /// `update` to `true`. /// - Parameters: /// - time: Current time from year to second. /// - update: Whether to update the time. public func setTime(_ time: Time, update: Bool = false) { if lostPower() || update { let data = [ binToBcd(time.second), binToBcd(time.minute), binToBcd(time.hour), binToBcd(time.dayOfWeek), binToBcd(time.day), binToBcd(time.month), binToBcd(UInt8(time.year - 2000))] try? writeRegister(Register.second, data) var byte: UInt8 = 0 try? readRegister(Register.status, into: &byte) // Set OSF bit to 0, which means the RTC hasn't stopped // so far after the time is set. try? writeRegister(Register.status, byte & 0b0111_1111) } } /// Read current time. /// - Returns: The time info in a struct. public func readTime() -> Time { try? readRegister(.second, into: &readBuffer, count: 7) let year = UInt16(bcdToBin(readBuffer[6])) + 2000 // Make sure the bit for century is 0. let month = bcdToBin(readBuffer[5] & 0b0111_1111) let day = bcdToBin(readBuffer[4]) let dayOfWeek = bcdToBin(readBuffer[3]) let hour = bcdToBin(readBuffer[2]) let minute = bcdToBin(readBuffer[1]) let second = bcdToBin(readBuffer[0]) let time = Time( year: year, month: month, day: day, hour: hour, minute: minute, second: second, dayOfWeek: dayOfWeek) return time } /// Read current temperature. /// - Returns: Temperature in Celsius. public func readTemperature() -> Float { try? readRegister(.temperature, into: &readBuffer, count: 2) let temperature = Float(readBuffer[0]) + Float(readBuffer[1] >> 6) * 0.25 return temperature } /// Set alarm1 at a specific time. The time can be decided by second, /// minute, hour, day or any combination of them. /// /// The alarm works only once. If you want it to happen continuously, you /// need to clear it manually when it is activated. /// /// Make sure the mode corresponds to the time you set. For example, /// you set the alarm to alert at 1m20s, like 1m20s, 1h1m20s... the mode /// should be `.minute`. /// /// - Parameters: /// - day: The day from 1 to 31 in a month. /// - dayOfWeek: The day from 1 to 7 in a week. /// - hour: The hour from 0 to 23 in a day, /// - minute: The minute from 0 to 59 in an hour. /// - second: The second from 0 to 59 in a minute. /// - mode: The alarm1 mode. public func setAlarm1( day: UInt8 = 0, dayOfWeek: UInt8 = 0, hour: UInt8 = 0, minute: UInt8 = 0, second: UInt8 = 0, mode: Alarm1Mode ) { clearAlarm(1) clearAlarm(2) disableAlarm(2) setSqwMode(SqwMode.off) // Bit7 of second. let A1M1 = (mode.rawValue & 0b0001) << 7 // Bit7 of minute. let A1M2 = (mode.rawValue & 0b0010) << 6 // Bit7 of hour. let A1M3 = (mode.rawValue & 0b0100) << 5 // Bit7 of day. let A1M4 = (mode.rawValue & 0b1000) << 4 // Bit6 of day to decide it is day of month or day of week. let DYDT = (mode.rawValue & 0b1_0000) << 2 let second = binToBcd(second) | A1M1 let minute = binToBcd(minute) | A1M2 let hour = binToBcd(hour) | A1M3 var day: UInt8 = 0 if DYDT == 0 { day = binToBcd(day) | A1M4 | DYDT } else { day = binToBcd(dayOfWeek) | A1M4 | DYDT } let future = [second, minute, hour, day] try? writeRegister(Register.alarm1, future) var byte: UInt8 = 0 try? readRegister(Register.control, into: &byte) if byte & 0b0100 != 0 { try? writeRegister(Register.control, byte | 0b01) } } /// Set alarm2 at a specific time. The time can be decided by minute, /// hour, day or any combination of them. /// /// The alarm works only once. If you want it to happen continuously, you /// need to clear it manually when it is activated. /// /// Make sure the mode corresponds to the time you set. For example, /// you set the alarm to alert at 2m, like 2m, 1h2m... the mode /// should be `.minute`. /// /// - Parameters: /// - day: The day from 1 to 31 in a month. /// - dayOfWeek: The day from 1 to 7 in a week. /// - hour: The hour from 0 to 23 in a day. /// - minute: The minute from 0 to 59 in an hour. /// - mode: The alarm2 mode. public func setAlarm2( day: UInt8 = 0, dayOfWeek: UInt8 = 0, hour: UInt8 = 0, minute: UInt8 = 0, mode: Alarm2Mode ) { clearAlarm(1) clearAlarm(2) disableAlarm(1) setSqwMode(SqwMode.off) let A2M2 = (mode.rawValue & 0b0001) << 7 let A2M3 = (mode.rawValue & 0b0010) << 6 let A2M4 = (mode.rawValue & 0b0100) << 5 let DYDT = (mode.rawValue & 0b1000) << 3 let minute = binToBcd(minute) | A2M2 let hour = binToBcd(hour) | A2M3 var day: UInt8 = 0 if DYDT == 0 { day = binToBcd(day) | A2M4 | DYDT } else { day = binToBcd(dayOfWeek) | A2M4 | DYDT } let future = [minute, hour, day] try? writeRegister(Register.alarm2, future) var byte: UInt8 = 0 try? readRegister(Register.control, into: &byte) if byte & 0b0100 != 0 { try? writeRegister(Register.control, byte | 0b10) } } /// The alarm1 will activate after a specified time interval. The time /// can be specified as day, hour, minute, second or any combination of them. /// - Parameters: /// - day: The days of time interval. /// - hour: The hour of time interval. /// - minute: The minutes of time interval. /// - second: The seconds of time interval. /// - mode: The alarm1 mode. public func setTimer1( day: UInt8 = 0, hour: UInt8 = 0, minute: UInt8 = 0, second: UInt8 = 0, mode: Alarm1Mode ) { let current = readTime() let futureSecond = (current.second + second) % 60 let futureMinute = (current.minute + minute) % 60 + (current.second + second) / 60 let futureHour = (current.hour + hour) % 24 + (current.minute + minute) / 60 if current.year % 4 == 0 { daysInMonth[1] = 29 } let totalDays: UInt8 = daysInMonth[Int(current.month - 1)] let futureDay = (current.day + day) % totalDays + (current.hour + hour) / 24 setAlarm1(day: futureDay, hour: futureHour, minute: futureMinute, second: futureSecond, mode: mode) } /// The alarm2 will activate after a specified time interval. The time /// can be specified as day, hour, minute or any combination of them. /// - Parameters: /// - day: The days of time interval. /// - hour: The hours of time interval. /// - minute: The days of time interval. /// - mode: The alarm2 mode. public func setTimer2( day: UInt8 = 0, hour: UInt8 = 0, minute: UInt8 = 0, mode: Alarm2Mode ) { let current = readTime() let futureMinute = (current.minute + minute) % 60 let futureHour = (current.hour + hour) % 24 + (current.minute + minute) / 60 if current.year % 4 == 0 { daysInMonth[1] = 29 } let totalDays = daysInMonth[Int(current.month - 1)] let futureDay = (current.day + day) % totalDays + (current.hour + hour) / 24 setAlarm2(day: futureDay, hour: futureHour, minute: futureMinute, mode: mode) } /// Check if the specified alarm has been activated. /// If so, it returns true, if not, false. /// - Parameter alarm: The alarm 1 or 2. /// - Returns: A boolean value. public func alarmed(_ alarm: Int) -> Bool { var byte: UInt8 = 0 try? readRegister(Register.status, into: &byte) let alarmFlag = byte & (~(0b1 << (alarm - 1))) return alarmFlag == 1 } /// Clear the alarm status. /// - Parameter alarm: The alarm 1 or 2. public func clearAlarm(_ alarm: Int) { var byte: UInt8 = 0 try? readRegister(Register.status, into: &byte) try? writeRegister(Register.status, byte & (~(0b1 << (alarm - 1)))) } /// The mode of alarm1. public enum Alarm1Mode: UInt8 { /// Alarm per second. case perSecond = 0x0F /// Alarm when seconds match. case second = 0x0E /// Alarm when minutes and seconds match. case minute = 0x0C /// Alarm when hours, minutes and seconds match. case hour = 0x08 /// Alarm when day of month, hours, minutes and seconds match. case dayOfMonth = 0x00 /// Alarm when day of week, hours, minutes and seconds match. /// It doesn't work when you set timer1 and timer2. case dayOfWeek = 0x10 } /// The mode of alarm2. public enum Alarm2Mode: UInt8 { /// Alarm once per minute (00 seconds of every minute). case perMinute = 0x7 /// Alarm when minutes match. case minute = 0x6 /// Alarm when hours and minutes match. case hour = 0x4 /// Alarm when day of month, hours, minutes and seconds match. case dayOfMonth = 0x0 /// Alarm when day of week, hours, minutes and seconds match. /// It doesn't work when you set timer1 and timer2. case dayOfWeek = 0x8 } /// Store the time info. public struct Time { public let year: UInt16 public let month: UInt8 public let day: UInt8 public let hour: UInt8 public let minute: UInt8 public let second: UInt8 public let dayOfWeek: UInt8 public init( year: UInt16, month: UInt8, day: UInt8, hour: UInt8, minute: UInt8, second: UInt8, dayOfWeek: UInt8 ) { self.year = year self.month = month self.day = day self.hour = hour self.minute = minute self.second = second self.dayOfWeek = dayOfWeek } } } extension DS3231 { private enum Register: UInt8 { case second = 0x00 case agingOffset = 0x10 case alarm2 = 0x0B case alarm1 = 0x07 case status = 0x0F case control = 0x0E case temperature = 0x11 } private enum SqwMode: UInt8 { case off = 0x1C case hz1 = 0x00 case kHz1 = 0x08 case kHz4 = 0x10 case kHz8 = 0x18 } private func writeRegister(_ reg: Register, _ data: [UInt8]) throws { var data = data data.insert(reg.rawValue, at: 0) let result = i2c.write(data, to: address) if case .failure(let err) = result { throw err } } private func writeRegister(_ reg: Register, _ value: UInt8) throws { let result = i2c.write([reg.rawValue, value], to: address) if case .failure(let err) = result { throw err } } private func readRegister(_ reg: Register, into byte: inout UInt8) throws { var result = i2c.write(reg.rawValue, to: address) if case .failure(let err) = result { throw err } result = i2c.read(into: &byte, from: address) if case .failure(let err) = result { throw err } } private func readRegister( _ register: Register, into buffer: inout [UInt8], count: Int ) throws { for i in 0..<buffer.count { buffer[i] = 0 } var result = i2c.write(register.rawValue, to: address) if case .failure(let err) = result { throw err } result = i2c.read(into: &buffer, count: count, from: address) if case .failure(let err) = result { throw err } } private func lostPower() -> Bool { var byte: UInt8 = 0 try? readRegister(Register.status, into: &byte) let stopFlag = byte >> 7 return stopFlag == 1 } private func enable32K() { var byte: UInt8 = 0 try? readRegister(Register.status, into: &byte) try? writeRegister(Register.status, byte | 0b1000) } private func disable32K() { var byte: UInt8 = 0 try? readRegister(Register.status, into: &byte) try? writeRegister(Register.status, byte & 0b0111) } private func bcdToBin(_ value: UInt8) -> UInt8 { return value - 6 * (value >> 4) } private func binToBcd(_ value: UInt8) -> UInt8 { return value + 6 * (value / 10) } private func setSqwMode(_ mode: SqwMode) { var byte: UInt8 = 0 try? readRegister(Register.control, into: &byte) try? writeRegister(Register.control, (byte & 0b0011) | mode.rawValue) } private func disableAlarm(_ alarm: Int) { var byte: UInt8 = 0 try? readRegister(Register.control, into: &byte) try? writeRegister(Register.control, byte & (~(0b1 << (alarm - 1)))) } }
33.164114
106
0.566046
2602153cebbd91df06a1f82c01d0bab7514b014d
1,090
// // StorageService.swift // DVPNApp // // Created by Lika Vorobyeva on 18.08.2021. // import Foundation import Foundation final class UserDefaultsStorageStrategy { private let defaults = UserDefaults.standard } // MARK: SettingsStorageStrategyType implementation extension UserDefaultsStorageStrategy: SettingsStorageStrategyType { func object<T: Codable>(ofType type: T.Type, forKey key: String) -> T? { if let data = defaults.value(forKey: key) as? Data, let object = Serializer.fromData(data, withType: type.self) { return object } return nil } func setObject<T: Codable>(_ object: T, forKey key: String) -> Bool { if let encoded = Serializer.toData(from: object) { defaults.set(encoded, forKey: key) return true } return false } func existsObject(forKey key: String) -> Bool { return defaults.object(forKey: key) != nil } func removeObject(forKey key: String) -> Bool { defaults.set(nil, forKey: key) return true } }
24.772727
76
0.638532
ace6ea0176e6a82cd01329e337613f784dec1f38
4,379
/*: # 72. Edit Distance Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. You have the following 3 operations permitted on a word: Insert a character Delete a character Replace a character Example 1: Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') Example 2: Input: word1 = "intention", word2 = "execution" Output: 5 Explanation: intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') */ /*: DP - Rolling Array **Time Complexity:** O(mn) **Space Complexity:** O(n) */ class Solution { func minDistance(_ word1: String, _ word2: String) -> Int { // The goal to match word1 & word2 // so eventually w1.last == w2.last // four scenarios: // xxc vs xxd: replace last one // xx vs xxd: add one char // xxd vs xx: remove one char // xxa vs xxa: no need to do anything var w1 = Array(word1) var w2 = Array(word2) let m = w1.count let n = w2.count let row = Array(repeating: 0, count: n + 1) var f: [[Int]] = Array(repeating: row, count: 2) f[0][0] = 0 var old = 0 var now = 0 for i in 0 ... m { old = now now = 1 - old for j in 0 ... n { if i == 0 { // need to add j char to make it f[now][j] = j continue } if j == 0 { // need to add i char to make it f[now][j] = i continue } // xxc vs xxd: replace last one // xx vs xxd: add one char // xxd vs xx: remove one char f[now][j] = min(f[old][j], f[now][j-1], f[old][j-1]) + 1 if w1[i-1] == w2[j-1] { // xxa vs xxa: no need to do anything f[now][j] = min(f[now][j], f[old][j-1]) } } } return f[now][n] } } /*: DP - No Rolling Array **Time Complexity:** O(mn) **Space Complexity:** O(mn) */ class Solution_No_Rolling { func minDistance(_ word1: String, _ word2: String) -> Int { // The goal to match word1 & word2 // so eventually w1.last == w2.last // four scenarios: // xxc vs xxd: replace last one // xx vs xxd: add one char // xxd vs xx: remove one char // xxa vs xxa: no need to do anything var w1 = Array(word1) var w2 = Array(word2) let m = w1.count let n = w2.count let row = Array(repeating: 0, count: n + 1) var f: [[Int]] = Array(repeating: row, count: m + 1) f[0][0] = 0 for i in 0 ... m { for j in 0 ... n { if i == 0 { // need to add j char to make it f[i][j] = j continue } if j == 0 { // need to add i char to make it f[i][j] = i continue } // xxc vs xxd: replace last one // xx vs xxd: add one char // xxd vs xx: remove one char f[i][j] = min(f[i-1][j], f[i][j-1], f[i-1][j-1]) + 1 if w1[i-1] == w2[j-1] { // xxa vs xxa: no need to do anything f[i][j] = min(f[i][j], f[i-1][j-1]) } } } return f[m][n] } } /*: ## Test */ import XCTest class TestEditDistance: XCTestCase { func testEditDistance1() { let s = "horse" let t = "ros" let output = 3 let solution = Solution() let result = solution.minDistance(s, t) XCTAssertEqual(result, output) let solution_no_rolling = Solution_No_Rolling() let result_no_rolling = solution_no_rolling.minDistance(s, t) XCTAssertEqual(result_no_rolling, output) } func testEditDistance2() { let s = "intention" let t = "execution" let output = 5 let solution = Solution() let result = solution.minDistance(s, t) XCTAssertEqual(result, output) let solution_no_rolling = Solution_No_Rolling() let result_no_rolling = solution_no_rolling.minDistance(s, t) XCTAssertEqual(result_no_rolling, output) } } TestEditDistance.defaultTestSuite.run()
21.465686
107
0.53277
eb098ad1bb573018355296c8bd3897efa6258115
363
import UIKit /// Conforming types can calculate the size that they require within a layout. public protocol Measurable { /// Measures the required size of the receiver. /// /// - parameter constraint: The size constraint. /// /// - returns: The layout size needed by the receiver. func measure(in constraint: SizeConstraint) -> CGSize }
27.923077
78
0.69146
3975e01eda54ca96328b07cc49a2e166c8b9edd8
1,572
// // TextOutputCallbackTableViewCell.swift // FRUI // // Copyright (c) 2019-2020 ForgeRock. All rights reserved. // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. // import UIKit import FRAuth class TextOutputCallbackTableViewCell: UITableViewCell, FRUICallbackTableViewCell { public static let cellIdentifier = "TextOutputCallbackTableViewCellId" public static let cellHeight: CGFloat = 200.0 @IBOutlet weak var textField:FRTextField? @IBOutlet weak var textView: UITextView? var callback: TextOutputCallback? override func awakeFromNib() { super.awakeFromNib() // Initialization code self.textView?.tintColor = FRUI.shared.primaryColor self.textView?.textColor = FRUI.shared.primaryColor } // MARK: - Public public func updateCellData(callback: Callback) { self.callback = callback as? TextOutputCallback self.textView?.text = self.callback?.message var textColor = FRUI.shared.primaryTextColor if #available(iOS 13.0, *) { textColor = UIColor.label } switch self.callback?.messageType { case .error: textColor = FRUI.shared.errorColor break case .warning: textColor = FRUI.shared.warningColor break default: break } self.textView?.tintColor = textColor self.textView?.textColor = textColor } }
28.071429
83
0.641858
768d7855be982671fb7fa0f6b5b79a838f2c0169
1,860
// // ObjectivePGPInterface.swift // passKit // // Created by Danny Moesch on 08.09.19. // Copyright © 2019 Bob Sun. All rights reserved. // import ObjectivePGP struct ObjectivePGPInterface: PGPInterface { private let keyring = ObjectivePGP.defaultKeyring init(publicArmoredKey: String, privateArmoredKey: String) throws { guard let publicKeyData = publicArmoredKey.data(using: .ascii), let privateKeyData = privateArmoredKey.data(using: .ascii) else { throw AppError.keyImport } let publicKeys = try ObjectivePGP.readKeys(from: publicKeyData) let privateKeys = try ObjectivePGP.readKeys(from: privateKeyData) keyring.import(keys: publicKeys) keyring.import(keys: privateKeys) guard publicKeys.first != nil, privateKeys.first != nil else { throw AppError.keyImport } } func decrypt(encryptedData: Data, keyID _: String?, passphrase: String) throws -> Data? { try ObjectivePGP.decrypt(encryptedData, andVerifySignature: false, using: keyring.keys) { _ in passphrase } } func encrypt(plainData: Data, keyID _: String?) throws -> Data { let encryptedData = try ObjectivePGP.encrypt(plainData, addSignature: false, using: keyring.keys, passphraseForKey: nil) if Defaults.encryptInArmored { return Armor.armored(encryptedData, as: .message).data(using: .ascii)! } return encryptedData } func containsPublicKey(with keyID: String) -> Bool { keyring.findKey(keyID)?.isPublic ?? false } func containsPrivateKey(with keyID: String) -> Bool { keyring.findKey(keyID)?.isSecret ?? false } var keyID: [String] { keyring.keys.map(\.keyID.longIdentifier) } var shortKeyID: [String] { keyring.keys.map(\.keyID.shortIdentifier) } }
33.818182
137
0.672043
67fd4c52226e4c1c1399dfa4c33679ffe5970160
628
// // MovieCell.swift // Flix // // Created by Mac on 6/25/1397 AP. // Copyright © 1397 Abraham Asmile. All rights reserved. // import UIKit class MovieCell: UITableViewCell { @IBOutlet weak var posterImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var overviewLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
20.933333
65
0.659236
48d5be72331d7a1f9862c1fbdc9c1a07971c4e72
747
import XCTest import FeeRateKit class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.758621
111
0.601071
29fe0f6decbd51042865db80a2a4715c88ef4a15
2,213
// // NetworkHelper.swift // CheckinNCheckOut // // Created by Ashli Rankin on 2/8/19. // Copyright © 2019 Ashli Rankin. All rights reserved. // import Foundation final class NetworkHelper { private init() {} static let shared = NetworkHelper() func performDataTask(endpointURLString: String, httpMethod: String, httpBody: Data?, handler: @escaping (AppError?, Data?) -> Void) { guard let url = URL(string: endpointURLString) else { handler(AppError.badURL(endpointURLString), nil) return } var request = URLRequest(url: url) request.httpMethod = httpMethod request.httpBody = httpBody let task = URLSession.shared.dataTask(with: request) { (data, response, error) in if let error = error { handler(AppError.networkError(error), nil) } guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { let statusCode = (response as? HTTPURLResponse)?.statusCode ?? -999 handler(AppError.badStatusCode(String(statusCode)), nil) return } if let data = data { handler(nil, data) } } task.resume() } public func performUploadTask(endpointURLString: String, httpMethod: String, httpBody: Data?, completionHandler: @escaping (AppError?, Data?, HTTPURLResponse?) ->Void) { guard let url = URL(string: endpointURLString) else { completionHandler(AppError.badURL("\(endpointURLString)"), nil, nil) return } var request = URLRequest(url: url) request.httpMethod = httpMethod request.setValue("application/json", forHTTPHeaderField: "Content-Type") let task = URLSession.shared.uploadTask(with: request, from: httpBody) { (data, response, error) in if let error = error { completionHandler(AppError.networkError(error), nil, response as? HTTPURLResponse) return } else if let data = data { completionHandler(nil, data, response as? HTTPURLResponse) } } task.resume() } }
34.046154
107
0.619069
e6c78156435e0f34a1f83f78c1fdf6bed8c18844
2,005
/* Copyright (c) 2014 Yichi Zhang https://github.com/yichizhang [email protected] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* NO MORE CGFloat( UInt( arc4random_uniform( UInt32( UInt( someCGFloat ) ) ) ) ) */ import Foundation import UIKit extension String { var floatValue: Float { return (self as NSString).floatValue } var intValue: Int32 { return (self as NSString).intValue } var integerValue: Int { return (self as NSString).integerValue } var CGFloatValue: CGFloat { return CGFloat( (self as NSString).floatValue ) } var NSStringValue: NSString { return (self as NSString) } } extension CGFloat { var UInt32Value: UInt32 { return UInt32(UInt(self)) } } extension Double { var CGFloatValue: CGFloat { return CGFloat(self) } } extension Float { var CGFloatValue: CGFloat { return CGFloat(self) } } extension Int { var CGFloatValue: CGFloat { return CGFloat(self) } } extension UInt32 { var CGFloatValue: CGFloat { return CGFloat(UInt(self)) } }
25.705128
460
0.752618
8ff86b4a7c241f196571215c2569c592a0bc3615
867
// // Episode.swift // Podcasts // // Created by Yu Tawata on 2020/08/18. // import Foundation public struct Episode: Equatable, Codable { public var title: String? public var desc: String? public var pubDate: Date? public var link: URL? public var subtitle: String? public var duration: TimeInterval? public var imageUrl: URL? public var enclosure: URL? public init( title: String?, desc: String?, pubDate: Date?, link: URL?, subtitle: String?, duration: TimeInterval?, imageUrl: URL?, enclosure: URL? ) { self.title = title self.desc = desc self.pubDate = pubDate self.link = link self.subtitle = subtitle self.duration = duration self.imageUrl = imageUrl self.enclosure = enclosure } }
21.675
43
0.588235
2001fe1e2cf6c01cd37f322def801c7be2d5995e
1,623
// // YZSimpleAudioRecorder.swift // twochat // // Created by Yichi on 2/01/2015. // Copyright (c) 2015 Yichi Zhang. All rights reserved. // import Foundation import AVFoundation import UIKit class YZSimpleAudioRecorder: NSObject, AVAudioRecorderDelegate { var audioRecorder:AVAudioRecorder? func startRecordingAndSaveToURL(url:NSURL){ var recordSettings = [ AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: 44100.0, AVNumberOfChannelsKey: 2, AVLinearPCMBitDepthKey: 16, AVLinearPCMIsBigEndianKey: false, AVLinearPCMIsFloatKey: false ] var error:NSError? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryRecord, error: &error) if(error != nil){ println(error?.localizedDescription); error = nil; return; } self.audioRecorder = AVAudioRecorder(URL: url, settings: recordSettings, error:&error) self.audioRecorder?.delegate = self self.audioRecorder?.meteringEnabled = true; if (self.audioRecorder?.prepareToRecord() == true){ self.audioRecorder?.record() } if(error != nil){ println(error?.localizedDescription); error = nil; return; } } func pauseRecording() { self.audioRecorder?.pause() } func stopRecording() { self.audioRecorder?.stop() } func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) { println("Audio recorder record result: \(flag)") self.audioRecorder?.delegate = nil self.audioRecorder = nil } func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder!, error: NSError!) { println(error.localizedDescription) } }
22.859155
92
0.730129
bb287aabb7b8cd6fe01e2ef09c71507b154b7e80
3,413
// // SceneKitViewController.swift // one // // Created by sidney on 4/22/21. // import UIKit import SceneKit import QuartzCore // for the basic animation class SceneKitViewController: BaseViewController { var sceneView = SCNView() var sceneView2 = SCNView() override func viewDidLoad() { super.viewDidLoad() title = "SceneKit" setCustomNav() setup1() setup2() // Do any additional setup after loading the view. } func setup1() { let scene = SCNScene() sceneView.scene = scene sceneView.backgroundColor = .lightGray sceneView.showsStatistics = true sceneView.allowsCameraControl = true sceneView.autoenablesDefaultLighting = true view.addSubview(sceneView) sceneView.snp.makeConstraints { (maker) in maker.top.equalTo(navigationView.snp.bottom) maker.leading.trailing.equalToSuperview() maker.height.equalTo(300) } // camera let cameraNode = SCNNode() cameraNode.camera = SCNCamera() cameraNode.position = SCNVector3(x: 0, y: 0, z: 5) scene.rootNode.addChildNode(cameraNode) // geometry object let torus = SCNTorus(ringRadius: 1, pipeRadius: 0.35) let torusNode = SCNNode(geometry: torus) scene.rootNode.addChildNode(torusNode) // configure the geometry object torus.firstMaterial?.diffuse.contents = UIColor.red.withAlphaComponent(0.3) torus.firstMaterial?.specular.contents = UIColor.white torusNode.rotation = SCNVector4(x: 2.0, y: 2.0, z: 2.0, w: 1.0) // animate the rotation of the torus // let spin = CABasicAnimation(keyPath: "rotation.w") // only animate the angle // spin.toValue = 2.0 * Double.pi // spin.duration = 3 // spin.repeatCount = HUGE // for infinity // torusNode.addAnimation(spin, forKey: "spin around") } func setup2() { view.addSubview(sceneView2) sceneView2.snp.makeConstraints { (maker) in maker.top.equalTo(sceneView.snp.bottom) maker.leading.trailing.equalToSuperview() maker.height.equalTo(SCREEN_HEIGHT - 300 - 44 - STATUS_BAR_HEIGHT) } let scene = SCNScene(named: "BrickLandspeeder4501.obj") let cameraNode = SCNNode() cameraNode.camera = SCNCamera() cameraNode.position = SCNVector3(x: 0, y: 0, z: 5) scene?.rootNode.addChildNode(cameraNode) let lightNode = SCNNode() lightNode.light = SCNLight() lightNode.light?.intensity = 100 lightNode.light?.type = .omni lightNode.position = SCNVector3(x: 0, y: 5, z: 5) scene?.rootNode.addChildNode(lightNode) // 6: Creating and adding ambien light to scene let ambientLightNode = SCNNode() ambientLightNode.light = SCNLight() ambientLightNode.light?.type = .ambient ambientLightNode.light?.color = UIColor.lightGray scene?.rootNode.addChildNode(ambientLightNode) // Allow user to manipulate camera sceneView2.allowsCameraControl = true sceneView2.backgroundColor = UIColor.scheduleMapPositionBkg sceneView2.cameraControlConfiguration.allowsTranslation = false sceneView2.scene = scene } }
33.135922
86
0.629651
76ae6a0b52327355e5ed035c27edfb27c733806d
228
// // TCNewFeatureCell.swift // TCNewFeatureViewProject // // Created by tardis_cxx on 2017-5-11. // Copyright © 2017年 tardis_cxx. All rights reserved. // import UIKit class TCNewFeatureCell: UICollectionViewCell { }
16.285714
54
0.723684
2965c2d8afcd7e78486cdd7f4ea79fd108f28088
3,330
// // Copyright (c) 2019 Hilton Campbell // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension Dictionary { init(_ elements: [(Key, Value)]) { self.init() for (key, value) in elements { self[key] = value } } /// Passthrough 'safe' subscript to make linters happy /// (because SwiftLint can't currently differentiate between array and dictionary subscripts) subscript(safe key: Key) -> Value? { get { return self[key] } set { self[key] = newValue } } /// Returns the union of `self` and the other dictionaries. If more than /// one dictionary has the same key, it will take on the rightmost /// dictionary's value. func union(_ first: Dictionary, _ rest: Dictionary...) -> Dictionary { var result = self for dictionary in [first] + rest { for (key, value) in dictionary { result[key] = value } } return result } /// Unions the other dictionaries with `self`. If more than /// one dictionary has the same key, it will take on the rightmost /// dictionary's value. mutating func formUnion(_ first: Dictionary, _ rest: Dictionary...) { for dictionary in [first] + rest { for (key, value) in dictionary { self[key] = value } } } /// Returns an Array with values generated by running each [key: value] of self through the mapFunction. func toArray<V>(_ map: (Key, Value) -> V) -> [V] { var mapped = [V]() for (key, value) in self { mapped.append(map(key, value)) } return mapped } } /// Returns the union of the two dictionaries. For any keys that both /// dictionaries have in common, the result will take on the value from the /// right dictionary. public func | <K, V>(lhs: Dictionary<K, V>, rhs: Dictionary<K, V>) -> Dictionary<K, V> { return lhs.union(rhs) } /// Unions two dictionaries. For any keys that both dictionaries have /// in common, the left dictionary will take on the value from the right. public func |= <K, V>(lhs: inout Dictionary<K, V>, rhs: Dictionary<K, V>) { lhs.formUnion(rhs) }
37
108
0.645345
56a9b1d16287f5191c2995276c3052502be0cc78
1,621
// Copyright © 2017-2019 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. // // This is a GENERATED FILE, changes made here WILL BE LOST. // import Foundation public final class Account { public var address: String { return TWStringNSString(TWAccountAddress(rawValue)) } public var derivationPath: String { return TWStringNSString(TWAccountDerivationPath(rawValue)) } public var extendedPublicKey: String { return TWStringNSString(TWAccountExtendedPublicKey(rawValue)) } public var coin: CoinType { return CoinType(rawValue: TWAccountCoin(rawValue).rawValue)! } let rawValue: OpaquePointer init(rawValue: OpaquePointer) { self.rawValue = rawValue } public init(address: String, derivationPath: String, extendedPublicKey: String) { let addressString = TWStringCreateWithNSString(address) defer { TWStringDelete(addressString) } let derivationPathString = TWStringCreateWithNSString(derivationPath) defer { TWStringDelete(derivationPathString) } let extendedPublicKeyString = TWStringCreateWithNSString(extendedPublicKey) defer { TWStringDelete(extendedPublicKeyString) } rawValue = TWAccountCreate(addressString, derivationPathString, extendedPublicKeyString) } deinit { TWAccountDelete(rawValue) } }
28.438596
96
0.696484
ebde1fbc903ceaf4c88053056666a16d0001f48e
3,981
// // INSHuDongTalkCell.swift // HaveYouReadToday // // Created by Flamingo on 2020/12/12. // import UIKit class INSHuDongTalkCell: UITableViewCell, TableCellInterface { static let reuseID = "INSHuDongTalkCell" @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var headImgView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var countLabel: UILabel! @IBOutlet weak var contentImgView: UIImageView! @IBOutlet weak var contentImgViewH: NSLayoutConstraint! @IBOutlet weak var contentImgViewT:NSLayoutConstraint! var userModel: INSUserModel? var model: TableCellModelInterface? { didSet { if let cellModel = model as? INSHuDongTalkCellModel { let talkModel: INSTalkModel = cellModel.model userModel = talkModel.user headImgView.sd_setImage(with: URL(string: (talkModel.user?.head)!), placeholderImage: #imageLiteral(resourceName: "pic_user_default"), options: .continueInBackground, completed: nil) nameLabel.text = talkModel.user?.nickName timeLabel.text = talkModel.publishTime?.getPublishTimeStr() let contentStr = talkModel.content?.trimmingCharacters(in: .whitespacesAndNewlines) contentLabel.text = contentStr //设置行距 let attStr = NSMutableAttributedString(string: contentStr!) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 5 attStr.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attStr.length)) contentLabel.attributedText = attStr; if contentStr!.count >= 10 { titleLabel.text = contentStr?.subString(to: 10) } else if contentStr!.count >= 8 && contentStr!.count < 10 { titleLabel.text = contentStr?.subString(to: 8) } else if contentStr!.count >= 6 && contentStr!.count < 8 { titleLabel.text = contentStr?.subString(to: 6) } else { titleLabel.text = "" } if let picStr = talkModel.picture { if picStr.count >= 1 { if picStr.subString(to: 1) != "h" { contentImgView.isHidden = true contentImgViewH.constant = 0 contentImgViewT.constant = 0 } else { contentImgView.isHidden = false contentImgViewH.constant = ((KScreenWidth - 165) * 4)/3 contentImgViewT.constant = 30 contentImgView.sd_setImage(with: URL(string: picStr), placeholderImage: #imageLiteral(resourceName: "talk_default"), options: .continueInBackground, completed: nil) } } } let count: Int = Int(arc4random() % 150) + 33 countLabel.text = "总共\(count)人浏览过" } } } override func awakeFromNib() { super.awakeFromNib() backgroundColor = .clear selectionStyle = .none headImgView.setRadius(25) contentImgView.setRadius(10) } @IBAction func headBtnClicked(_ sender: Any) { let vc = INSDynamicViewController() vc.userModel = userModel currentViewController()?.navigationController?.pushViewController(vc, animated: true) } }
38.650485
198
0.545089
918088050e926dae7aa5bfeaa86b2ea2ef7e3214
14,831
// // Copyright © FINN.no AS, Inc. All rights reserved. // import CoreLocation import FinniversKit import UIKit public protocol LocationInfo { var name: String { get } var latitude: Double { get } var longitude: Double { get } } extension CLLocationCoordinate2D: LocationInfo { public var name: String { return "" } } public enum SearchLocationDataSourceResult { case finished(text: String, locations: [LocationInfo]) case cancelled case failed(error: Error) } public protocol SearchLocationDataSource: AnyObject { func searchLocationViewController(_ searchLocationViewController: SearchLocationViewController, didRequestLocationsFor searchQuery: String, completion: @escaping ((_ result: SearchLocationDataSourceResult) -> Void)) func recentLocation(in searchLocationViewController: SearchLocationViewController) -> [LocationInfo] func homeAddressLocation(in searchLocationViewController: SearchLocationViewController) -> LocationInfo? func showCurrentLocation(in searchLocationViewController: SearchLocationViewController) -> Bool } public protocol SearchLocationViewControllerDelegate: AnyObject { func searchLocationViewControllerWillBeginEditing(_ searchLocationViewController: SearchLocationViewController) func searchLocationViewControllerDidCancelSearch(_ searchLocationViewController: SearchLocationViewController) func searchLocationViewController(_ searchLocationViewController: SearchLocationViewController, didSelectLocation location: LocationInfo?) func searchLocationViewControllerDidSelectCurrentLocation(_ searchLocationViewController: SearchLocationViewController) } public class SearchLocationViewController: ScrollViewController { private enum Section: Int, CaseIterable { case homeAddress = 0 case currentLocation case recentLocations case results } // MARK: - Public Properties public weak var delegate: SearchLocationViewControllerDelegate? public weak var searchLocationDataSource: SearchLocationDataSource? // MARK: - Private Properties private var locations: [LocationInfo] = [] private var didClearText = false private var selectedLocation: LocationInfo? private var recentLocations: [LocationInfo] { return searchLocationDataSource?.recentLocation(in: self) ?? [] } private(set) lazy var searchBar: UISearchBar = { let searchBar = SearchLocationSearchBar(frame: .zero) searchBar.placeholder = "map.search.placeholder".localized() searchBar.searchBarStyle = .minimal searchBar.delegate = self searchBar.backgroundColor = Theme.mainBackground searchBar.translatesAutoresizingMaskIntoConstraints = false searchBar.preservesSuperviewLayoutMargins = false return searchBar }() private lazy var tableView: UITableView = { let tableView = UITableView(frame: .zero, style: .plain) tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = .none tableView.register(IconTitleTableViewCell.self) tableView.register(BasicTableViewCell.self) tableView.translatesAutoresizingMaskIntoConstraints = false return tableView }() private var searchResultsSectionActive: Bool { return !(searchBar.text?.isEmpty ?? true) } private var showHomeAddressOption: Bool { return !searchResultsSectionActive && (searchLocationDataSource?.homeAddressLocation(in: self) != nil) } private var showCurrentLocationOption: Bool { return !searchResultsSectionActive && (searchLocationDataSource?.showCurrentLocation(in: self) ?? false) } public override func scrollViewDidScroll(_ scrollView: UIScrollView) { super.scrollViewDidScroll(scrollView) view.endEditing(false) } } // MARK: - TableView DataSource extension SearchLocationViewController: UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { return Section.allCases.count } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let section = Section(rawValue: section) else { return 0 } switch section { case .homeAddress: return showHomeAddressOption ? 1 : 0 case .currentLocation: return showCurrentLocationOption ? 1 : 0 case .recentLocations: return !searchResultsSectionActive ? recentLocations.count : 0 case .results: return locations.count } } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let section = Section(rawValue: indexPath.section) else { return tableView.dequeue(IconTitleTableViewCell.self, for: indexPath) } switch section { case .homeAddress: let cell = tableView.dequeue(IconTitleTableViewCell.self, for: indexPath) cell.configure(with: HomeAddressCellViewModel()) cell.iconImageView.tintColor = .watermelon return cell case .currentLocation: let cell = tableView.dequeue(IconTitleTableViewCell.self, for: indexPath) cell.configure(with: CurrentLocationCellViewModel()) cell.iconImageView.tintColor = .watermelon return cell case .recentLocations: let cell = tableView.dequeue(IconTitleTableViewCell.self, for: indexPath) let location = recentLocations[safe: indexPath.row] cell.configure(with: LocationCellViewModel(title: location?.name ?? "")) return cell case .results: let cell = tableView.dequeue(BasicTableViewCell.self, for: indexPath) let location = locations[safe: indexPath.row] cell.configure(with: LocationCellViewModel(title: location?.name ?? "")) return cell } } } // MARK: - TableView Delegate extension SearchLocationViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let section = Section(rawValue: indexPath.section) else { return } tableView.deselectRow(at: indexPath, animated: true) endSearchBarEdit() switch section { case .homeAddress: let location = searchLocationDataSource?.homeAddressLocation(in: self) searchBar.text = location?.name delegate?.searchLocationViewController(self, didSelectLocation: location) selectedLocation = location case .currentLocation: searchBar.text = nil delegate?.searchLocationViewControllerDidSelectCurrentLocation(self) case .recentLocations: let location = recentLocations[safe: indexPath.row] searchBar.text = location?.name delegate?.searchLocationViewController(self, didSelectLocation: location) selectedLocation = location case .results: let location = locations[safe: indexPath.row] searchBar.text = location?.name delegate?.searchLocationViewController(self, didSelectLocation: location) selectedLocation = location } } } // MARK: - SearchBar Delegate extension SearchLocationViewController: UISearchBarDelegate { public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { // User clicked the x-button and cleared the text -> should not begin editing guard !didClearText else { didClearText = false return false } // Present if needed if searchBar.superview != view { setup() if let searchText = searchBar.text { loadLocations(forSearchText: searchText) } } delegate?.searchLocationViewControllerWillBeginEditing(self) return true } public func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: false) } public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {} public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { endSearchBarEdit() if let selectedLocation = selectedLocation { // return to previous search searchBar.text = selectedLocation.name loadLocations(forSearchText: selectedLocation.name) delegate?.searchLocationViewController(self, didSelectLocation: selectedLocation) } else { delegate?.searchLocationViewControllerDidCancelSearch(self) selectedLocation = nil searchBar.text = nil searchBar.setShowsCancelButton(false, animated: false) loadLocations(forSearchText: nil) } } public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { // If not active, the user clicked the x-button while not editing and the search should be cancelled if !searchBar.isDescendant(of: view), searchText.isEmpty { didClearText = true delegate?.searchLocationViewControllerDidCancelSearch(self) selectedLocation = nil loadLocations(forSearchText: nil) return } // If the user clears the search field and then hits cancel, the search is cancelled if selectedLocation != nil, searchText.isEmpty { selectedLocation = nil } loadLocations(forSearchText: searchText) } } // MARK: - Private methods private extension SearchLocationViewController { func endSearchBarEdit() { searchBar.endEditing(false) searchBar.setShowsCancelButton(false, animated: false) } func loadLocations(forSearchText searchText: String?) { locations.removeAll() tableView.reloadData() guard let searchText = searchText, !searchText.isEmpty else { return } searchLocationDataSource?.searchLocationViewController(self, didRequestLocationsFor: searchText, completion: { [weak self] result in switch result { case .cancelled: return case let .failed(error): // TODO: handle error when searching DebugLog.write("Location search error: \(error)") return case let .finished(text, locations): DispatchQueue.main.async { guard let query = self?.searchBar.text else { return } if query == text { self?.locations = locations self?.tableView.reloadData() } } } }) } func setup() { view.backgroundColor = UIColor.bgPrimary.withAlphaComponent(0.9) tableView.backgroundColor = UIColor.clear searchBar.removeFromSuperview() view.insertSubview(tableView, belowSubview: topShadowView) view.addSubview(searchBar) NSLayoutConstraint.activate([ searchBar.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: .spacingS), searchBar.topAnchor.constraint(equalTo: view.topAnchor), searchBar.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -.spacingS), topShadowView.bottomAnchor.constraint(equalTo: searchBar.bottomAnchor), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.topAnchor.constraint(equalTo: searchBar.bottomAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor), ]) } } // MARK: - Private class private class SearchLocationSearchBar: UISearchBar { // Makes sure to setup appearance proxy one time and one time only private static let setupSearchBarAppereanceOnce: () = { let textFieldAppearanceInSearch = UITextField.appearance(whenContainedInInstancesOf: [SearchLocationSearchBar.self]) textFieldAppearanceInSearch.defaultTextAttributes = [ NSAttributedString.Key.foregroundColor: UIColor.textPrimary, NSAttributedString.Key.font: UIFont.bodyRegular, ] let barButtondAppearance = UIBarButtonItem.appearance(whenContainedInInstancesOf: [SearchLocationSearchBar.self]) barButtondAppearance.setTitleTextAttributes([.font: UIFont.bodyRegular]) barButtondAppearance.title = "cancel".localized() }() override init(frame: CGRect) { _ = SearchLocationSearchBar.setupSearchBarAppereanceOnce super.init(frame: frame) smartQuotesType = .no smartDashesType = .no } required init?(coder aDecoder: NSCoder) { _ = SearchLocationSearchBar.setupSearchBarAppereanceOnce super.init(coder: aDecoder) smartQuotesType = .no smartDashesType = .no } } private struct HomeAddressCellViewModel: IconTitleTableViewCellViewModel { let detailText: String? = nil var icon: UIImage? { return UIImage(named: .homeAddressIcon).withRenderingMode(.alwaysTemplate) } var iconTintColor: UIColor? { return nil } var title: String { return "map.homeAddress".localized() } var subtitle: String? { return nil } var hasChevron: Bool { return false } } private struct CurrentLocationCellViewModel: IconTitleTableViewCellViewModel { let detailText: String? = nil var icon: UIImage? { return UIImage(named: .currentLocationIcon).withRenderingMode(.alwaysTemplate) } var iconTintColor: UIColor? { return nil } var title: String { return "map.currentLocation".localized() } var subtitle: String? { return nil } var hasChevron: Bool { return false } } private struct RecentLocationCellViewModel: IconTitleTableViewCellViewModel { let detailText: String? = nil var icon: UIImage? { return UIImage(named: .searchSmall) } var iconTintColor: UIColor? { return nil } let title: String var subtitle: String? { return nil } var hasChevron: Bool { return false } } private struct LocationCellViewModel: IconTitleTableViewCellViewModel { let detailText: String? = nil var icon: UIImage? { return nil } var iconTintColor: UIColor? { return nil } let title: String var subtitle: String? { return nil } var hasChevron: Bool { return false } }
35.14455
219
0.677095
e06c35e31ff18fdf2cc5352cbd9a6107856fc7b3
5,159
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck %s -verify // REQUIRES: objc_interop import CoreFoundation import Foundation func testCFToObjC(_ cfStr: CFString, cfMutableStr: CFMutableString) { var nsStr: NSString = cfStr nsStr = cfMutableStr _ = nsStr var nsMutableStr: NSMutableString = cfMutableStr nsMutableStr = cfStr // expected-error{{cannot assign value of type 'CFString' to type 'NSMutableString'}} // sanity check nsStr = nsMutableStr } func testObjCToCF(_ nsStr: NSString, nsMutableStr: NSMutableString) { var cfStr: CFString = nsStr cfStr = nsMutableStr var cfMutableStr: CFMutableString = nsMutableStr cfMutableStr = cfStr // expected-error{{cannot assign value of type 'CFString' to type 'CFMutableString'}} // sanity check cfStr = cfMutableStr } func testCFToNative(_ cfStr: CFString, cfMutableStr: CFMutableString) { var str = cfStr as String str = cfMutableStr as String _ = str } func testNativeToCF(_ str: String) { var cfStr = str as CFString var cfMutableStr = str as CFMutableString // expected-error{{'String' is not convertible to 'CFMutableString'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{26-28=as!}} } func testCFToAnyObject(_ cfStr: CFString, cfMutableStr: CFMutableString, cfTree: CFTree) { var anyObject: AnyObject = cfStr anyObject = cfMutableStr anyObject = cfTree _ = anyObject } func testAnyObjectToCF(_ anyObject: AnyObject) { var cfStr: CFString = anyObject as! CFString var _: CFMutableString = anyObject as! CFMutableString var _: CFTree = anyObject as! CFTree // No implicit conversions. cfStr = anyObject // expected-error{{'AnyObject' is not convertible to 'CFString'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{20-20= as! CFString}} _ = cfStr } func testUncheckableCasts(_ anyObject: AnyObject, nsObject: NSObject, anyObjectType: AnyObject.Type, nsObjectType: NSObject.Type) { if let _ = anyObject as? CFString { } // expected-error{{conditional downcast to CoreFoundation type 'CFString' will always succeed}} expected-note{{did you mean to explicitly compare the CFTypeIDs of 'anyObject' and 'CFString'}} if let _ = nsObject as? CFString { } // expected-error{{conditional downcast to CoreFoundation type 'CFString' will always succeed}} expected-note{{did you mean to explicitly compare the CFTypeIDs of 'nsObject' and 'CFString'}} if let _ = anyObject as? CFTree { } // expected-error{{conditional downcast to CoreFoundation type 'CFTree' will always succeed}} expected-note{{did you mean to explicitly compare the CFTypeIDs of 'anyObject' and 'CFTree'}} if let _ = nsObject as? CFTree { } // expected-error{{will always succeed}} expected-note{{did you mean to explicitly compare the CFTypeIDs of 'nsObject' and 'CFTree'}} if let _ = anyObjectType as? CFString.Type { } // expected-error{{conditional downcast to CoreFoundation type 'CFString.Type' will always succeed}} expected-note{{did you mean to explicitly compare the CFTypeIDs of 'anyObjectType' and 'CFString.Type'}} if let _ = nsObjectType as? CFString.Type { } // expected-error{{conditional downcast to CoreFoundation type 'CFString.Type' will always succeed}} expected-note{{did you mean to explicitly compare the CFTypeIDs of 'nsObjectType' and 'CFString.Type'}} if let _ = anyObjectType as? CFTree.Type { } // expected-error{{conditional downcast to CoreFoundation type 'CFTree.Type' will always succeed}} expected-note{{did you mean to explicitly compare the CFTypeIDs of 'anyObjectType' and 'CFTree.Type'}} if let _ = nsObjectType as? CFTree.Type { } // expected-error{{will always succeed}} expected-note{{did you mean to explicitly compare the CFTypeIDs of 'nsObjectType' and 'CFTree.Type'}} } func testCFConvWithIUO(_ x: CFString!, y: NSString!) { func acceptCFString(_ a: CFString!) { } func acceptNSString(_ b: NSString!) { } acceptNSString(x) acceptCFString(y) } func testBridgedCFDowncast(array: [Any], dictionary: [AnyHashable : Any], set: Set<AnyHashable>) { let cfArray = array as CFArray let cfDictionary = dictionary as CFDictionary let cfSet = set as CFSet _ = array as? CFArray // expected-warning {{conditional cast from '[Any]' to 'CFArray' always succeeds}} _ = dictionary as? CFDictionary // expected-warning {{conditional cast from '[AnyHashable : Any]' to 'CFDictionary' always succeeds}} _ = set as? CFSet // expected-warning {{conditional cast from 'Set<AnyHashable>' to 'CFSet' always succeeds}} _ = array as! CFArray // expected-warning {{forced cast from '[Any]' to 'CFArray' always succeeds}} _ = dictionary as! CFDictionary // expected-warning {{forced cast from '[AnyHashable : Any]' to 'CFDictionary' always succeeds}} _ = set as! CFSet // expected-warning {{forced cast from 'Set<AnyHashable>' to 'CFSet' always succeeds}} _ = cfArray as! [Any] _ = cfDictionary as! [AnyHashable : Any] _ = cfSet as! Set<AnyHashable> _ = cfArray as? [Any] _ = cfDictionary as? [AnyHashable : Any] _ = cfSet as? Set<AnyHashable> }
47.768519
254
0.723978
8f3d8ba7e816c56250aab1c2ba48ea7b0baeb404
921
// // CouponConfirmationModel.swift // aboon // // Created by 原口和音 on 2018/08/12. // Copyright © 2018年 aboon. All rights reserved. // import UIKit import Firebase class CouponConfirmationModel { func useCoupon(roomId: String, members: [Member]) { let db = Firestore.firestore() db.collection("rooms").document(roomId).setData(["isUsed" : true], merge: true) { error in if let error = error { dLog(error as NSError) } } let batch = db.batch() for member in members { let document = db.collection("users").document(member.userId).collection("myCoupons").document(roomId) batch.setData(["isUsed" : true], forDocument: document, merge: true) } batch.commit() { error in if let error = error { dLog(error as NSError) } } } }
26.314286
114
0.562432
469e2be1d0186c4c326e81bf9b19cf86750ef4ea
553
// // WKWindowFeatures.swift // flutter_inappwebview // // Created by Lorenzo Pichilli on 19/02/21. // import Foundation import WebKit extension WKWindowFeatures { public func toMap () -> [String:Any?] { return [ "allowsResizing": allowsResizing, "height": height, "menuBarVisibility": menuBarVisibility, "statusBarVisibility": statusBarVisibility, "toolbarsVisibility": toolbarsVisibility, "width": width, "x": x, "y": y ] } }
22.12
55
0.575045
3a7590e5f8f6a958bd00070c016659ae2deacfbb
406
// // Task.swift // SwiftUITodo // // Created by Suyeol Jeon on 03/06/2019. // Copyright © 2019 Suyeol Jeon. All rights reserved. // import SwiftUI struct Task: Equatable, Hashable, Codable, Identifiable { let id: UUID var title: String var isDone: Bool init(title: String, isDone: Bool) { self.id = UUID() self.title = title self.isDone = isDone } }
18.454545
57
0.6133
79c99e0ed1523ee092e9830982e0cbcbc2577867
2,427
// // InnerFooterViewModelList.swift // // // Created by NohEunTae on 2021/07/01. // // #if os(iOS) import UIKit extension VisibilityTrackableCollectionView { final class InnerFooterViewModelList: InnerViewModelListInterface { var type: VisibilityTrackableViewType { .footer } private let kind = UICollectionView.elementKindSectionFooter var inners: [InnerViewModel] = [] func updateInnerCollectionFullyVisible(using parent: VisibilityTrackableCollectionViewInterface) { guard parent.visibleSupplementaryViews(ofKind: kind).isNotEmpty else { return } let indexPaths = parent.visibleSupplementaryViews(ofKind: kind).compactMap { view -> IndexPath? in guard let _ = view as? InnerVisibilityTrackerInterface else { return nil } return view.currentIndexPath(elementKind: kind) } guard indexPaths.isNotEmpty else { return } indexPaths.forEach { indexPath in guard let (innerTracker, inner) = findInnerVisibilityTracker(parent: parent, key: indexPath) else { addInnerItemIfNotContains(indexPath) return } refreshIfNeeded(inner: inner, innerTracker: innerTracker) addInnerItemIfNotContains(indexPath) reload(inner: inner, innerTracker: innerTracker) } } func findInnerVisibilityTracker( parent: VisibilityTrackableCollectionViewInterface?, key: IndexPath ) -> (InnerVisibilityTrackerInterface, InnerViewModel)? { guard let inner = inners.first(where: { $0.key == key }) , let view = parent?.supplementaryView(forElementKind: kind, at: inner.key) as? InnerVisibilityTrackerInterface else { return nil } return (view, inner) } func findInnerVisibilityTracker( using inner: InnerViewModel, in parent: VisibilityTrackableCollectionViewInterface? ) -> InnerVisibilityTrackerInterface? { parent?.supplementaryView(forElementKind: kind, at: inner.key) as? InnerVisibilityTrackerInterface } } } #endif
35.691176
127
0.597033
fb13d884a4bf54e1e5c161f8769605879fab7191
1,792
import CEvent typealias SocketEvent = OpaquePointer public enum EventType: Int16 { case timeout = 0x01 case read = 0x02 case write = 0x04 case signal = 0x08 case persistent = 0x10 case finalize = 0x40 case closed = 0x80 } public protocol EventHandler { func readEvent() func writeEvent() } public extension EventHandler { func readEvent() {} func writeEvent() {} } public class Event { public let types: [EventType] public let fd: Int32 var internalEvent: SocketEvent! public var handler: EventHandler? public init(types: [EventType], fd: Int32, handler: EventHandler? = nil) { self.types = types self.fd = fd self.handler = handler internalEvent = event_new( EventManager.shared.eventBase, fd, toRaw(), { (fileDescriptor, eventTypeRaw, instancePtr) in guard let eventType = EventType(rawValue: eventTypeRaw) else { return } let event = unsafeBitCast(instancePtr, to: Event.self) event.handle(type: eventType) }, Unmanaged.passUnretained(self).toOpaque() ) } deinit { if let internalEvent = internalEvent { event_del(internalEvent) event_free(internalEvent) } } internal func handle(type: EventType) { switch(type) { case .read: handler?.readEvent() break case .write: handler?.writeEvent() break default: print("[Event] Unhandled type: \(type)") break } } public func remove() { if let internalEvent = internalEvent { event_del(internalEvent) } } public func add() { if let internalEvent = internalEvent { event_add(internalEvent, nil) } } internal func getEvent() -> SocketEvent { return internalEvent! } @inline(__always) final func toRaw() -> Int16 { return types.reduce(0) { return $0 + $1.rawValue } } }
19.478261
75
0.675781
01e5aa4c30da899a0d2d96e5b8f62e2f7b00d3e5
4,544
// // ListViewController.swift // PhotoMaps // // Created by Aleksei Artamonov on 7/3/18. // Copyright © 2018 test. All rights reserved. // import UIKit class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! lazy var refreshControl: UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(ListViewController.handleRefresh(_:)), for: UIControlEvents.valueChanged) refreshControl.tintColor = UIColor.red return refreshControl }() var viewModel = ListViewModel(with:UserLocationService.shared, and: DataProvider(with: SessionManager())) { didSet { updateUI() } } @objc func handleRefresh(_ refreshControl: UIRefreshControl) { self.viewModel.refreshViewModel() } func updateUI() { viewModel.cells.bindAndFire { [weak self] in print($0) self?.tableView.reloadData() } viewModel.refreshing.bindAndFire {[weak self] in if $0 == true { self?.refreshControl.beginRefreshing() } else { self?.refreshControl.endRefreshing() } } viewModel.errorMessage.bindAndFire { [weak self] in if !$0.isEmpty { let alert = UIAlertController(title: "Error", message: $0, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil)) self?.present(alert, animated: true, completion: nil) } } self.viewModel.refreshViewModel() } override func viewDidLoad() { super.viewDidLoad() self.tableView.addSubview(self.refreshControl) updateUI() // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.presentDetailsForCelWithIndex(withIndex: indexPath.row) tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { self.presentDetailsForCelWithIndex(withIndex: indexPath.row) } func presentDetailsForCelWithIndex(withIndex index: Int) { guard let annotation = self.viewModel.provideAnnotationForCellBy(index: index) else { return } let vm = DetailViewModel(with: self.viewModel.locationService, self.viewModel.dataProvider, true, annotation) let controller = DetailViewController.detailViewController(withViewModel: vm) self.present(controller, animated: true, completion: nil) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ListTableViewCell", for: indexPath) as! ListTableViewCell self.viewModel.cells.value[indexPath.row].name.bindAndFire { string in cell.nameLabel.text = string } self.viewModel.cells.value[indexPath.row].lat.bindAndFire { string in cell.latLabel.text = string } self.viewModel.cells.value[indexPath.row].lon.bindAndFire { string in cell.lonLabel.text = string } self.viewModel.cells.value[indexPath.row].distance.bindAndFire { string in cell.distanceLabel.text = string } return cell } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.cells.value.count } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
34.424242
123
0.642165
f8ff336156a647271322c69161adbbee676668d6
420
// // URLRequestConveritble.swift // Creative Minds Task -IMDB- // // Created by Youssef on 4/13/20. // Copyright © 2020 Youssef. All rights reserved. // import Foundation import Alamofire protocol URLRequestConvertible: Alamofire.URLRequestConvertible { var method: HTTPMethod { get } var parameters: [String: Any]? { get } var url: URL { get } var encoding: ParameterEncoding { get } }
21
65
0.683333
d6c02d65077edc8c1e608689cc2b88dc636cc068
1,690
import PlaygroundSupport import TortoiseGraphics import CoreGraphics let myFrame = CGRect(x: 0, y: 0, width: 500, height: 500) let canvas = PlaygroundCanvas(frame: myFrame) canvas.frameRate = 120 canvas.color = .white PlaygroundPage.current.liveView = canvas canvas.drawing { turtle in //Go to the left turtle.penUp() turtle.goto(-150, 0) //Adjust pen width turtle.penSize(5) //Face turtle for J turtle.setHeading(325) //Hide turtle //turtle.hideTortoise() //Uppercase J turtle.curve(withSides: 30, withSize: 15, drawSides: 9) turtle.curve(withSides: 12, withSize: 4, drawSides: 4) turtle.curve(withSides: 75, withSize: 100, drawSides: 2) turtle.curve(withSides: 15, withSize: 5, drawSides: 7) turtle.curve(withSides: 50, withSize: 17, drawSides: 5) turtle.curve(withSides: 90, withSize: 2, drawSides: 9) turtle.setHeading(90) //print("y position after J is \(turtle.ycor)") //print("Heading after J is \(turtle.heading)") //Lowercase o before v turtle.curve(withSides: -30, withSize: 5, drawSides: 6) turtle.curve(withSides: 30, withSize: 9, drawSides: 1) turtle.curve(withSides: 20, withSize: 7, drawSides: 24) turtle.setHeading(140) print("y position at the top of a lowercase letter is \(turtle.ycor)") turtle.curve(withSides: -15, withSize: 15, drawSides: 4) //print("y position after o is \(turtle.ycor)") //print("Heading after o is \(turtle.heading)") //Lowercase v after o turtle.curve(withSides: 20, withSize: 4, drawSides: 4) print("y position after curve up is \(turtle.ycor)") turtle.hideTortoise() }
30.727273
74
0.666864
db2242c5dc9ce4760a900e65c4055e21ec09d479
1,912
// // CoinbaseSocketClientDelegate.swift // CoinbaseSocketSwift // // Created by Hani Shabsigh on 11/5/17. // Copyright © 2017 Hani Shabsigh. All rights reserved. // import Foundation @objc public protocol CoinbaseSocketClientDelegate: class { @objc optional func coinbaseSocketDidConnect(socket: CoinbaseSocketClient) @objc optional func coinbaseSocketDidDisconnect(socket: CoinbaseSocketClient, error: Error?) @objc optional func coinbaseSocketClientOnErrorMessage(socket: CoinbaseSocketClient, error: ErrorMessage) @objc optional func coinbaseSocketClientOnSubscriptions(socket: CoinbaseSocketClient, subscriptions: SubscriptionsMessage) @objc optional func coinbaseSocketClientOnHeartbeat(socket: CoinbaseSocketClient, heartbeat: HeartbeatMessage) @objc optional func coinbaseSocketClientOnTicker(socket: CoinbaseSocketClient, ticker: TickerMessage) @objc optional func coinbaseSocketClientOnSnapshot(socket: CoinbaseSocketClient, snapshot: SnapshotMessage) @objc optional func coinbaseSocketClientOnUpdate(socket: CoinbaseSocketClient, update: UpdateMessage) @objc optional func coinbaseSocketClientOnReceived(socket: CoinbaseSocketClient, received: ReceivedMessage) @objc optional func coinbaseSocketClientOnOpen(socket: CoinbaseSocketClient, open: OpenMessage) @objc optional func coinbaseSocketClientOnDone(socket: CoinbaseSocketClient, done: DoneMessage) @objc optional func coinbaseSocketClientOnMatch(socket: CoinbaseSocketClient, match: MatchMessage) @objc optional func coinbaseSocketClientOnChange(socket: CoinbaseSocketClient, change: ChangeMessage) @objc optional func coinbaseSocketClientOnMarginProfileUpdate(socket: CoinbaseSocketClient, marginProfileUpdate: MarginProfileUpdateMessage) @objc optional func coinbaseSocketClientOnActivate(socket: CoinbaseSocketClient, activate: ActivateMessage) }
56.235294
144
0.819561
6a594f7761f57275c1ba96746bc63de37dd1081b
1,571
// // CheckoutTableItems.swift // Cart // // Created by Jens Meder on 12.06.17. // Copyright © 2017 Jens Meder. All rights reserved. // import UIKit internal final class CheckoutTableItems: NSObject, UITableViewDataSource, UITableViewDelegate { private let items: CartItems private let identifier: OOString private let currencies: Currencies // MARK: Init internal convenience init(items: CartItems, currencies: Currencies) { self.init( identifier: ConstString("checkoutItem"), items: items, currencies: currencies ) } internal required init(identifier: OOString, items: CartItems, currencies: Currencies) { self.items = items self.identifier = identifier self.currencies = currencies } // MARK: UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: identifier.stringValue) if cell == nil { cell = UITableViewCell(style: .value1, reuseIdentifier: identifier.stringValue) } let item = self.items[indexPath.row] cell?.textLabel?.text = item.product.name.stringValue let value = item.product.price.value * currencies.current.rate cell?.detailTextLabel?.text = String(format: "%.2f %@", arguments: [value, currencies.current.sign.stringValue]) return cell! } func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { return nil } }
29.092593
114
0.745385
11727961bd62a7a76ddcc4da11de74c84d8efe43
6,006
// // NestC2CViewController.swift // i2app // // Created by Arcus Team on 6/27/17. /* * Copyright 2019 Arcus Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // import Foundation import Cornea class NestC2CViewController: BasePairingViewController { // MARK: Properties @IBOutlet weak var webView: UIWebView! private var presenter: NestC2CPresenterProtocol! var isReconnectFlow = false // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() navBar(withTitle: NSLocalizedString("Link Account", comment: ""), enableBackButton: false) navigationItem.setHidesBackButton(true, animated: false) navigationItem.leftBarButtonItem = nil presenter = NestC2CPresenter(delegate: self) presenter.fetchRevokedDevices() createNavigationCancelButton() if let url = URL(string: presenter.nestPairURL()) { webView.loadRequest(URLRequest(url: url)) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } // MARK: Events func cancelButtonTapped() { // Check if device details exists in the stack and if so present it if let navigationController = navigationController { let viewControllers = navigationController.viewControllers for viewController in viewControllers { if let viewController = viewController as? DeviceDetailsTabBarController { navigationController.popToViewController(viewController, animated: true) return } } } navigateToDashboard() } // MARK: Helpers fileprivate func navigateToDashboard() { if let appDelegate = UIApplication.shared.delegate as? AppDelegate { DispatchQueue.main.async { DevicePairingManager.sharedInstance().stopPairingProcessAndNotifications() ApplicationRoutingService.defaultService.showDashboard() } } } fileprivate func createNavigationCancelButton() { let editButton = UIButton(type: .custom) editButton.setAttributedTitle(FontData.getString(NSLocalizedString("Cancel", comment: ""), withFont: FontDataTypeNavBar), for: UIControlState()) editButton.frame = CGRect(x: 0, y: 0, width: 50, height: 12) editButton.addTarget(self, action: #selector(cancelButtonTapped), for: .touchUpInside) navigationItem.leftBarButtonItem = UIBarButtonItem(customView: editButton) } fileprivate func presentPairedDeviceConfiguration() { var devicesJustPaired = DevicePairingManager.sharedInstance().justPairedDevices let reconnected = presenter.reconnectedDevices() if reconnected.count > 0 { if devicesJustPaired == nil { devicesJustPaired = NSMutableArray() } for device in reconnected { // check if revoked device is already in justPairedDevices if !checkFor(device: device, inDeviceList: devicesJustPaired!) { devicesJustPaired?.add(device) } } } DevicePairingManager.sharedInstance().justPairedDevices = devicesJustPaired DispatchQueue.main.async { if devicesJustPaired != nil && devicesJustPaired!.count > 0 { DevicePairingManager.sharedInstance().customizeDevice(self) } else { self.navigateToDashboard() } } } private func checkFor(device: DeviceModel, inDeviceList list: NSArray) -> Bool { for deviceFromList in list { if let deviceFromList = deviceFromList as? DeviceModel { if deviceFromList.address == device.address { return true } } } return false } } // MARK: UIWebViewDelegate extension NestC2CViewController: UIWebViewDelegate { func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { // Make sure we do not hit the url with state=pair twice in order to avoid creating two nest tokens // ITWO-12743 if request.url?.absoluteString.range(of: "") != nil && request.url?.absoluteString.range(of: "state=pair") == nil { // Check for status code let configuration = URLSessionConfiguration.default let session = URLSession(configuration: configuration) let task = session.dataTask(with: request) { (_, response, _) in if let response = response as? HTTPURLResponse { if response.statusCode == 204 { // Go to adding devices self.presentPairedDeviceConfiguration() } else if response.statusCode == 203 { // Go to the dashboard DevicePairingManager.sharedInstance().stopPairingProcessAndNotifications() self.navigateToDashboard() } else if response.statusCode == 400 || response.statusCode == 404 { self.createNavigationCancelButton() } } } task.resume() } return true } func webViewDidFinishLoad(_ webView: UIWebView) { // Check for cancel button if let url = webView.request?.url { if url.absoluteString.range(of: "") != nil && url.absoluteString.range(of: "state=") != nil { navigationItem.leftBarButtonItem = nil } else { createNavigationCancelButton() } } } } // MARK: NestC2CPresenterDelegate extension NestC2CViewController: NestC2CPresenterDelegate { }
29.880597
103
0.669497
d528dad697fd341ef807505d95a9f2b978c39c0d
7,625
// // SimpleDialogInputView.swift // BLE_ChatRoom // // Created by Jimmy on 2019/8/24. // Copyright © 2019 Jimmy. All rights reserved. // import Foundation import UIKit protocol SimpleDialogInputViewDelegate: AnyObject { func sendMessage(_ message: String) } class SimpleDialogInputView: UIView { public var nonactivated_placeholder = "Aa" public var activated_placeholder = "_enter_text".localized public var maximumNumberOfLines = 4 public var textViewDelegate: UITextViewDelegate? public weak var delegate: SimpleDialogInputViewDelegate? private lazy var textView: UITextView = { let v = UITextView() v.layer.cornerRadius = 20 v.layer.masksToBounds = true v.font = UIFont.systemFont(ofSize: 20) v.delegate = self v.bounces = false v.isScrollEnabled = false v.contentInset = .zero v.textContainerInset = UIEdgeInsets(top: v.textContainerInset.top, left: 10, bottom: v.textContainerInset.bottom, right: 20) return v }() private var textViewHeightConstraint: NSLayoutConstraint? private lazy var placeholderLabel: UILabel = { let l = UILabel() l.text = nonactivated_placeholder l.font = textView.font l.textColor = UIColor.lightGray.withAlphaComponent(0.6) l.backgroundColor = .clear return l }() private lazy var sendButton: UIButton = { let b = UIButton() b.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside) b.setImage(UIImage.microphone, for: .normal) b.backgroundColor = .clear return b }() @objc private func buttonPressed(_ sender: UIButton) { if !textView.text.isEmpty { delegate?.sendMessage(textView.text) } } override var intrinsicContentSize: CGSize { get { return CGSize(width: self.bounds.width, height: textView.bounds.height + 20) } } private lazy var containerView: UIView = { // let v = UIView() return self }() override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("required init(coder:) not implemented") } private func setupUI() { backgroundColor = .yellow textView .attachTo(view: containerView, with: .side(.left(inset: .init(top: 0, left: 10, bottom: 0, right: 0)))) .attachTo(view: containerView, with: .side(.bottom(inset: .init(top: 0, left: 0, bottom: -10, right: 0)))) .attachTo(view: containerView, with: .side(.top(inset: .init(top: 10, left: 0, bottom: 0, right: 0)))) textViewHeightConstraint = textView.heightAnchor.constraint(equalToConstant: 40) textViewHeightConstraint?.isActive = true placeholderLabel.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(placeholderLabel) sendButton.attachTo(view: containerView, with: .side(.right(inset: .init(top: 0, left: 0, bottom: 0, right: -10)))) [ placeholderLabel.leftAnchor.constraint(equalTo: textView.leftAnchor, constant: 20), placeholderLabel.bottomAnchor.constraint(equalTo: textView.bottomAnchor), placeholderLabel.heightAnchor.constraint(equalToConstant: 40), sendButton.bottomAnchor.constraint(equalTo: textView.bottomAnchor), sendButton.heightAnchor.constraint(equalToConstant: 40), sendButton.leftAnchor.constraint(equalTo: textView.rightAnchor, constant: 10), sendButton.widthAnchor.constraint(equalTo: sendButton.heightAnchor, multiplier: 1.0), ].forEach({$0.isActive = true}) } } extension SimpleDialogInputView: UITextViewDelegate { func textViewDidChangeSelection(_ textView: UITextView) { textViewDelegate?.textViewDidChangeSelection?(textView) } func textViewShouldEndEditing(_ textView: UITextView) -> Bool { return textViewDelegate?.textViewShouldEndEditing?(textView) ?? true } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { return textViewDelegate?.textViewShouldEndEditing?(textView) ?? true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { return textViewDelegate?.textView?(textView, shouldChangeTextIn: range, replacementText: text) ?? true } func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { return textViewDelegate?.textView?(textView, shouldInteractWith: URL, in: characterRange, interaction: interaction) ?? true } func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { return textViewDelegate?.textView?(textView, shouldInteractWith: textAttachment, in: characterRange, interaction: interaction) ?? true } enum TextViewDelegateActions { case didChange case didEndEditing case didBeginEditing } func textViewDidChange(_ textView: UITextView) { togglePlaceHolder() toggleTextViewConstraint(textViewDelegateAction: .didChange) textViewDelegate?.textViewDidChange?(textView) sendButton.setImage(textView.text.isEmpty ? UIImage.microphone : UIImage.send, for: .normal) } private func togglePlaceHolder() { placeholderLabel.isHidden = !textView.text.isEmpty } func textViewDidEndEditing(_ textView: UITextView) { togglePlaceHolder() toggleTextViewConstraint(textViewDelegateAction: .didEndEditing) textViewDelegate?.textViewDidEndEditing?(textView) } func textViewDidBeginEditing(_ textView: UITextView) { toggleTextViewConstraint(textViewDelegateAction: .didBeginEditing) textViewDelegate?.textViewDidBeginEditing?(textView) } private func toggleTextViewConstraint(textViewDelegateAction: TextViewDelegateActions) { let textView = self.textView switch textViewDelegateAction { case .didBeginEditing, .didChange: let size = CGSize(width: textView.frame.size.width, height: .infinity) let estimatedSize = textView.sizeThatFits(size) let numberOfLines = Int(estimatedSize.height / textView.font!.lineHeight) textView.isScrollEnabled = numberOfLines > maximumNumberOfLines if numberOfLines > maximumNumberOfLines { textViewHeightConstraint?.constant = CGFloat(self.maximumNumberOfLines) * textView.font!.lineHeight + textView.textContainerInset.top + textView.textContainerInset.bottom } else { textViewHeightConstraint?.constant = estimatedSize.height } if textViewDelegateAction == .didBeginEditing { DispatchQueue.main.async { self.textView.selectedRange.location = self.textView.text.count } } case .didEndEditing: textViewHeightConstraint?.constant = 40 textView.isScrollEnabled = false textView.contentOffset = .zero textView.textContainer.lineBreakMode = .byTruncatingTail } setNeedsLayout() } }
38.705584
187
0.664787
61c31782044e8518bcca67d6e803cbe8a11496fa
9,266
// // 🦠 Corona-Warn-App // import ExposureNotification #if DEBUG final class ClientMock { // MARK: - Creating a Mock Client. /// Creates a mock `Client` implementation with given default values. /// /// - parameters: /// - availableDaysAndHours: return this value when the `availableDays(_:)` or `availableHours(_:)` is called, or an error if `urlRequestFailure` is passed. /// - downloadedPackage: return this value when `fetchDay(_:)` or `fetchHour(_:)` is called, or an error if `urlRequestFailure` is passed. /// - submissionError: when set, `submit(_:)` will fail with this error. /// - urlRequestFailure: when set, calls (see above) will fail with this error init( availableDaysAndHours: DaysAndHours = DaysAndHours(days: [], hours: []), downloadedPackage: PackageDownloadResponse? = nil, submissionError: SubmissionError? = nil, availablePackageRequestFailure: Client.Failure? = nil, fetchPackageRequestFailure: Client.Failure? = nil ) { self.availableDaysAndHours = availableDaysAndHours self.downloadedPackage = downloadedPackage self.availablePackageRequestFailure = availablePackageRequestFailure self.fetchPackageRequestFailure = fetchPackageRequestFailure if let error = submissionError { onSubmitCountries = { $2(.failure(error)) } } } init() {} // MARK: - Properties. var submissionResponse: KeySubmissionResponse? var availablePackageRequestFailure: Client.Failure? var fetchPackageRequestFailure: Client.Failure? var availableDaysAndHours: DaysAndHours = DaysAndHours(days: [], hours: []) var downloadedPackage: PackageDownloadResponse? lazy var supportedCountries: [Country] = { // provide a default list of some countries let codes = ["DE", "IT", "ES", "PL", "NL", "BE", "CZ", "AT", "DK", "IE", "LT", "LV", "EE"] return codes.compactMap({ Country(countryCode: $0) }) }() // MARK: - Configurable Mock Callbacks. var onGetTestResult: ((String, Bool, TestResultHandler) -> Void)? var onSubmitCountries: ((_ payload: CountrySubmissionPayload, _ isFake: Bool, _ completion: @escaping KeySubmissionResponse) -> Void) = { $2(.success(())) } var onGetRegistrationToken: ((String, String, String?, Bool, @escaping RegistrationHandler) -> Void)? var onGetTANForExposureSubmit: ((String, Bool, @escaping TANHandler) -> Void)? var onSupportedCountries: ((@escaping CountryFetchCompletion) -> Void)? var onGetOTPEdus: ((String, PPACToken, Bool, @escaping OTPAuthorizationCompletionHandler) -> Void)? var onGetOTPEls: ((String, PPACToken, @escaping OTPAuthorizationCompletionHandler) -> Void)? var onSubmitErrorLog: ((Data, @escaping ErrorLogSubmitting.ELSSubmissionResponse) -> Void)? var onSubmitAnalytics: ((SAP_Internal_Ppdd_PPADataIOS, PPACToken, Bool, @escaping PPAnalyticsSubmitionCompletionHandler) -> Void)? var onTraceWarningDiscovery: ((String, @escaping TraceWarningPackageDiscoveryCompletionHandler) -> Void)? var onTraceWarningDownload: ((String, Int, @escaping TraceWarningPackageDownloadCompletionHandler) -> Void)? var onDCCRegisterPublicKey: ((Bool, String, String, @escaping DCCRegistrationCompletionHandler) -> Void)? var onGetDigitalCovid19Certificate: ((String, Bool, @escaping DigitalCovid19CertificateCompletionHandler) -> Void)? } extension ClientMock: ClientWifiOnly { func fetchHours( _ hours: [Int], day: String, country: String, completion completeWith: @escaping (HoursResult) -> Void ) { var errors = [Client.Failure]() var buckets = [Int: PackageDownloadResponse]() let group = DispatchGroup() hours.forEach { hour in group.enter() fetchHour(hour, day: day, country: country) { result in switch result { case let .success(hourBucket): buckets[hour] = hourBucket case let .failure(error): errors.append(error) } group.leave() } } group.notify(queue: .main) { completeWith( HoursResult(errors: errors, bucketsByHour: buckets, day: day) ) } } func fetchHour(_ hour: Int, day: String, country: String, completion: @escaping HourCompletionHandler) { if let failure = fetchPackageRequestFailure { completion(.failure(failure)) return } completion(.success(downloadedPackage ?? ClientMock.dummyResponse)) } } extension ClientMock: Client { private static let dummyResponse = PackageDownloadResponse(package: SAPDownloadedPackage(keysBin: Data(), signature: Data()), etag: "\"etag\"") func availableDays(forCountry country: String, completion: @escaping AvailableDaysCompletionHandler) { if let failure = availablePackageRequestFailure { completion(.failure(failure)) return } completion(.success(availableDaysAndHours.days)) } func availableHours(day: String, country: String, completion: @escaping AvailableHoursCompletionHandler) { if let failure = availablePackageRequestFailure { completion(.failure(failure)) return } completion(.success(availableDaysAndHours.hours)) } func fetchDay(_ day: String, forCountry country: String, completion: @escaping DayCompletionHandler) { if let failure = fetchPackageRequestFailure { completion(.failure(failure)) return } completion(.success(downloadedPackage ?? ClientMock.dummyResponse)) } func submit(payload: CountrySubmissionPayload, isFake: Bool, completion: @escaping KeySubmissionResponse) { onSubmitCountries(payload, isFake, completion) } func getRegistrationToken( forKey: String, withType: String, dateOfBirthKey: String?, isFake: Bool, completion completeWith: @escaping RegistrationHandler ) { guard let onGetRegistrationToken = self.onGetRegistrationToken else { completeWith(.success("dummyRegistrationToken")) return } onGetRegistrationToken(forKey, withType, dateOfBirthKey, isFake, completeWith) } func getTestResult(forDevice device: String, isFake: Bool, completion completeWith: @escaping TestResultHandler) { guard let onGetTestResult = self.onGetTestResult else { completeWith( .success( FetchTestResultResponse( testResult: TestResult.positive.rawValue, sc: nil, labId: "SomeLabId" ) ) ) return } onGetTestResult(device, isFake, completeWith) } func getTANForExposureSubmit(forDevice device: String, isFake: Bool, completion completeWith: @escaping TANHandler) { guard let onGetTANForExposureSubmit = self.onGetTANForExposureSubmit else { completeWith(.success("dummyTan")) return } onGetTANForExposureSubmit(device, isFake, completeWith) } func authorize( otpEdus: String, ppacToken: PPACToken, isFake: Bool, forceApiTokenHeader: Bool = false, completion: @escaping OTPAuthorizationCompletionHandler ) { guard let onGetOTPEdus = self.onGetOTPEdus else { completion(.success(Date())) return } onGetOTPEdus(otpEdus, ppacToken, isFake, completion) } func authorize( otpEls: String, ppacToken: PPACToken, completion: @escaping OTPAuthorizationCompletionHandler ) { guard let onGetOTPEls = self.onGetOTPEls else { completion(.success(Date())) return } onGetOTPEls(otpEls, ppacToken, completion) } func submit( payload: SAP_Internal_Ppdd_PPADataIOS, ppacToken: PPACToken, isFake: Bool, forceApiTokenHeader: Bool, completion: @escaping PPAnalyticsSubmitionCompletionHandler ) { guard let onSubmitAnalytics = self.onSubmitAnalytics else { completion(.success(())) return } onSubmitAnalytics(payload, ppacToken, isFake, completion) } func traceWarningPackageDiscovery( country: String, completion: @escaping TraceWarningPackageDiscoveryCompletionHandler ) { guard let onTraceWarningDiscovery = self.onTraceWarningDiscovery else { completion(.success((TraceWarningDiscovery(oldest: 448163, latest: 448522, eTag: "FakeETag")))) return } onTraceWarningDiscovery(country, completion) } func traceWarningPackageDownload( country: String, packageId: Int, completion: @escaping TraceWarningPackageDownloadCompletionHandler ) { guard let onTraceWarningDownload = self.onTraceWarningDownload else { completion(.success(downloadedPackage ?? ClientMock.dummyResponse)) return } onTraceWarningDownload(country, packageId, completion) } func dccRegisterPublicKey( isFake: Bool, token: String, publicKey: String, completion: @escaping DCCRegistrationCompletionHandler ) { guard let onDCCRegisterPublicKey = self.onDCCRegisterPublicKey else { completion(.success(())) return } onDCCRegisterPublicKey(isFake, token, publicKey, completion) } func submit( errorLogFile: Data, otpEls: String, completion: @escaping ErrorLogSubmitting.ELSSubmissionResponse ) { guard let onSubmitErrorLog = self.onSubmitErrorLog else { completion(.success(LogUploadResponse(id: "\(Int.random(in: 0..<Int.max))", hash: errorLogFile.sha256String()))) return } onSubmitErrorLog(errorLogFile, completion) } func getDigitalCovid19Certificate( registrationToken token: String, isFake: Bool, completion: @escaping DigitalCovid19CertificateCompletionHandler ) { guard let onGetDigitalCovid19Certificate = self.onGetDigitalCovid19Certificate else { completion(.success((DCCResponse(dek: "dataEncryptionKey", dcc: "coseObject")))) return } onGetDigitalCovid19Certificate(token, isFake, completion) } } #endif
32.173611
158
0.749406
39dbaf5df70b2f335ecc0b951377efff7e86333c
22,553
// // PackageCollectionViewCell.swift // Sileo // // Created by CoolStar on 7/30/19. // Copyright © 2019 CoolStar. All rights reserved. // import Foundation import SwipeCellKit class PackageCollectionViewCell: SwipeCollectionViewCell { @IBOutlet var imageView: UIImageView? @IBOutlet var titleLabel: UILabel? @IBOutlet var authorLabel: UILabel? @IBOutlet var descriptionLabel: UILabel? @IBOutlet var separatorView: UIView? @IBOutlet var unreadView: UIView? var item: CGFloat = 0 var numberOfItems: CGFloat = 0 var alwaysHidesSeparator = false var stateBadgeView: PackageStateBadgeView? override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public var targetPackage: Package? { didSet { if let targetPackage = targetPackage { titleLabel?.text = targetPackage.name authorLabel?.text = "\(ControlFileParser.authorName(string: targetPackage.author ?? "")) • \(targetPackage.version)" descriptionLabel?.text = targetPackage.packageDescription let url = targetPackage.icon ?? "" self.imageView?.image = AmyNetworkResolver.shared.image(url, size: imageView?.frame.size) { [weak self] refresh, image in if refresh, let strong = self, let image = image, url == strong.targetPackage?.icon { DispatchQueue.main.async { strong.imageView?.image = image } } } ?? UIImage(named: "Tweak Icon") titleLabel?.textColor = targetPackage.commercial ? self.tintColor : .sileoLabel } unreadView?.isHidden = true self.accessibilityLabel = String(format: String(localizationKey: "Package_By_Author"), self.titleLabel?.text ?? "", self.authorLabel?.text ?? "") self.refreshState() } } public var provisionalTarget: ProvisionalPackage? { didSet { if let provisionalTarget = provisionalTarget { titleLabel?.text = provisionalTarget.name ?? "" authorLabel?.text = "\(provisionalTarget.author ?? "") • \(provisionalTarget.version ?? "")" descriptionLabel?.text = provisionalTarget.description let url = provisionalTarget.icon ?? "" self.imageView?.image = AmyNetworkResolver.shared.image(url, size: imageView?.frame.size) { [weak self] refresh, image in if refresh, let strong = self, let image = image, url == strong.provisionalTarget?.icon { DispatchQueue.main.async { strong.imageView?.image = image } } } ?? UIImage(named: "Tweak Icon") titleLabel?.textColor = .sileoLabel } unreadView?.isHidden = true self.accessibilityLabel = String(format: String(localizationKey: "Package_By_Author"), self.titleLabel?.text ?? "", self.authorLabel?.text ?? "") self.refreshState() } } override func awakeFromNib() { super.awakeFromNib() self.selectedBackgroundView = UIView() self.selectedBackgroundView?.backgroundColor = UIColor.lightGray.withAlphaComponent(0.25) self.isAccessibilityElement = true self.accessibilityTraits = .button self.delegate = self stateBadgeView = PackageStateBadgeView(frame: .zero) stateBadgeView?.translatesAutoresizingMaskIntoConstraints = false stateBadgeView?.state = .installed if let stateBadgeView = stateBadgeView { self.contentView.addSubview(stateBadgeView) if let imageView = imageView { stateBadgeView.centerXAnchor.constraint(equalTo: imageView.rightAnchor).isActive = true stateBadgeView.centerYAnchor.constraint(equalTo: imageView.bottomAnchor).isActive = true } } NotificationCenter.default.addObserver([self], selector: #selector(PackageCollectionViewCell.refreshState), name: DownloadManager.reloadNotification, object: nil) weak var weakSelf = self NotificationCenter.default.addObserver(weakSelf as Any, selector: #selector(updateSileoColors), name: SileoThemeManager.sileoChangedThemeNotification, object: nil) } @objc func updateSileoColors() { if !(targetPackage?.commercial ?? false) { titleLabel?.textColor = .sileoLabel } } override func layoutSubviews() { super.layoutSubviews() var numberOfItemsInRow = CGFloat(1) if UIDevice.current.userInterfaceIdiom == .pad || UIApplication.shared.statusBarOrientation.isLandscape { numberOfItemsInRow = (self.superview?.bounds.width ?? 0) / 300 } if alwaysHidesSeparator || ceil((item + 1) / numberOfItemsInRow) == ceil(numberOfItems / numberOfItemsInRow) { separatorView?.isHidden = true } else { separatorView?.isHidden = false } } func setTargetPackage(_ package: Package, isUnread: Bool) { self.targetPackage = package unreadView?.isHidden = !isUnread } override func tintColorDidChange() { super.tintColorDidChange() if targetPackage?.commercial ?? false { titleLabel?.textColor = self.tintColor } unreadView?.backgroundColor = self.tintColor } @objc func refreshState() { guard let targetPackage = targetPackage else { stateBadgeView?.isHidden = true return } stateBadgeView?.isHidden = false let queueState = DownloadManager.shared.find(package: targetPackage) let isInstalled = PackageListManager.shared.installedPackage(identifier: targetPackage.package) != nil switch queueState { case .installations: stateBadgeView?.state = isInstalled ? .reinstallQueued : .installQueued case .upgrades: stateBadgeView?.state = .updateQueued case .uninstallations: stateBadgeView?.state = .deleteQueued default: stateBadgeView?.state = .installed stateBadgeView?.isHidden = !isInstalled } } } extension PackageCollectionViewCell: SwipeCollectionViewCellDelegate { func collectionView(_ collectionView: UICollectionView, editActionsForItemAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? { // Different actions depending on where we are headed // Also making sure that the set package actually exists if let provisionalPackage = provisionalTarget { guard let repo = provisionalPackage.repo, let url = URL(string: repo), orientation == .right else { return nil } if !RepoManager.shared.hasRepo(with: url) { return [addRepo(provisionalPackage)] } return nil } guard let package = targetPackage, UserDefaults.standard.optionalBool("SwipeActions", fallback: true) else { return nil } var actions = [SwipeAction]() let queueFound = DownloadManager.shared.find(package: package) // We only want delete if we're going left, and only if it's in the queue if orientation == .left { if queueFound != .none { actions.append(cancelAction(package)) } return actions } // Check if the package is actually installed if let installedPackage = PackageListManager.shared.installedPackage(identifier: package.package) { let repo = RepoManager.shared.repoList.first(where: { $0.rawEntry == package.sourceFile }) // Check we have a repo for the package if queueFound != .uninstallations { actions.append(uninstallAction(package)) } if package.filename != nil && repo != nil { // Check if can be updated if DpkgWrapper.isVersion(package.version, greaterThan: installedPackage.version) { if queueFound != .upgrades { actions.append(upgradeAction(package)) } } else { // Only add re-install if it can't be updated if queueFound != .installations { actions.append(reinstallAction(package)) } } } else { let allPkgs = PackageListManager.shared.allPackages if let pkg = allPkgs?.first(where: { $0.version == package.version && $0.package == package.package }) { let queueFound = DownloadManager.shared.find(package: pkg) if DpkgWrapper.isVersion(pkg.version, greaterThan: installedPackage.version) { if queueFound != .upgrades { actions.append(upgradeAction(pkg)) } } else { // Only add re-install if it can't be updated if queueFound != .installations { actions.append(reinstallAction(pkg)) } } } } } else { if queueFound != .installations { actions.append(getAction(package)) } } return actions } func collectionView(_ collectionView: UICollectionView, editActionsOptionsForItemAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions { var options = SwipeOptions() options.expansionStyle = .selection return options } private func addRepo(_ package: ProvisionalPackage) -> SwipeAction { let addRepo = SwipeAction(style: .default, title: String(localizationKey: "Add_Source.Title")) { _, _ in if let repo = package.repo, let url = URL(string: repo), let tabBarController = self.window?.rootViewController as? UITabBarController, let sourcesSVC = tabBarController.viewControllers?[2] as? UISplitViewController, let sourcesNavNV = sourcesSVC.viewControllers[0] as? SileoNavigationController { tabBarController.selectedViewController = sourcesSVC if let sourcesVC = sourcesNavNV.viewControllers[0] as? SourcesViewController { sourcesVC.presentAddSourceEntryField(url: url) } } if let package = CanisterResolver.package(package) { CanisterResolver.shared.queuePackage(package) } self.hapticResponse() self.hideSwipe(animated: true) } addRepo.backgroundColor = .systemPink addRepo.image = UIImage(systemNameOrNil: "plus.app") return addRepo } private func cancelAction(_ package: Package) -> SwipeAction { let cancel = SwipeAction(style: .destructive, title: String(localizationKey: "Cancel")) { _, _ in DownloadManager.shared.remove(package: package.package) DownloadManager.shared.reloadData(recheckPackages: true) self.hapticResponse() self.hideSwipe(animated: true) } cancel.image = UIImage(systemNameOrNil: "x.circle") return cancel } private func uninstallAction(_ package: Package) -> SwipeAction { let uninstall = SwipeAction(style: .destructive, title: String(localizationKey: "Package_Uninstall_Action")) { _, _ in let queueFound = DownloadManager.shared.find(package: package) if queueFound != .none { DownloadManager.shared.remove(package: package.package) } DownloadManager.shared.add(package: package, queue: .uninstallations) DownloadManager.shared.reloadData(recheckPackages: true) self.hapticResponse() self.hideSwipe(animated: true) } uninstall.image = UIImage(systemNameOrNil: "trash.circle") return uninstall } private func upgradeAction(_ package: Package) -> SwipeAction { let update = SwipeAction(style: .default, title: String(localizationKey: "Package_Upgrade_Action")) { _, _ in let queueFound = DownloadManager.shared.find(package: package) if queueFound != .none { DownloadManager.shared.remove(package: package.package) } DownloadManager.shared.add(package: package, queue: .upgrades) DownloadManager.shared.reloadData(recheckPackages: true) self.hapticResponse() self.hideSwipe(animated: true) } update.backgroundColor = .systemBlue update.image = UIImage(systemNameOrNil: "icloud.and.arrow.down") return update } private func reinstallAction(_ package: Package) -> SwipeAction { let reinstall = SwipeAction(style: .default, title: String(localizationKey: "Package_Reinstall_Action")) { _, _ in let queueFound = DownloadManager.shared.find(package: package) if queueFound != .none { DownloadManager.shared.remove(package: package.package) } DownloadManager.shared.add(package: package, queue: .installations) DownloadManager.shared.reloadData(recheckPackages: true) self.hapticResponse() self.hideSwipe(animated: true) } reinstall.image = UIImage(systemNameOrNil: "arrow.clockwise.circle") reinstall.backgroundColor = .systemOrange return reinstall } private func getAction(_ package: Package) -> SwipeAction { let install = SwipeAction(style: .default, title: String(localizationKey: "Package_Get_Action")) { _, _ in let queueFound = DownloadManager.shared.find(package: package) if queueFound != .none { DownloadManager.shared.remove(package: package.package) } if package.sourceRepo != nil && !package.package.contains("/") { if !package.commercial { DownloadManager.shared.add(package: package, queue: .installations) DownloadManager.shared.reloadData(recheckPackages: true) } else { self.updatePurchaseStatus(package) { error, provider, purchased in guard let provider = provider else { return self.presentAlert(paymentError: .invalidResponse, title: String(localizationKey: "Purchase_Auth_Complete_Fail.Title", type: .error)) } if let error = error { return self.presentAlert(paymentError: error, title: String(localizationKey: "Purchase_Auth_Complete_Fail.Title", type: .error)) } if purchased { DownloadManager.shared.add(package: package, queue: .installations) DownloadManager.shared.reloadData(recheckPackages: true) } else { if provider.isAuthenticated { self.initatePurchase(provider: provider, package: package) } else { DispatchQueue.main.async { self.authenticate(provider: provider, package: package) } } } } } } self.hapticResponse() self.hideSwipe(animated: true) } if package.commercial { install.image = UIImage(systemNameOrNil: "dollarsign.circle") } else { install.image = UIImage(systemNameOrNil: "square.and.arrow.down") } install.backgroundColor = .systemGreen return install } private func legacyGet(_ package: Package) -> Bool { let existingPurchased = UserDefaults.standard.array(forKey: "cydia-purchased") as? [String] let isPurchased = existingPurchased?.contains(package.package) ?? false if isPurchased { DownloadManager.shared.add(package: package, queue: .installations) DownloadManager.shared.reloadData(recheckPackages: true) return true } return false } private func updatePurchaseStatus(_ package: Package, _ completion: ((PaymentError?, PaymentProvider?, Bool) -> Void)?) { guard let repo = package.sourceRepo else { return self.presentAlert(paymentError: .noPaymentProvider, title: String(localizationKey: "Purchase_Auth_Complete_Fail.Title", type: .error)) } PaymentManager.shared.getPaymentProvider(for: repo) { error, provider in guard let provider = provider else { if let completion = completion { completion(.noPaymentProvider, nil, false) } return } if error != nil { if self.legacyGet(package) { if let completion = completion { completion(nil, provider, true) } } } provider.getPackageInfo(forIdentifier: package.package) { error, info in guard let info = info else { if let completion = completion { completion(error, provider, false) } return } if error != nil { if self.legacyGet(package) { if let completion = completion { completion(nil, provider, true) } } return } if info.purchased { DownloadManager.shared.add(package: package, queue: .installations) DownloadManager.shared.reloadData(recheckPackages: true) if let completion = completion { completion(nil, provider, true) } } else { if let completion = completion { completion(nil, provider, false) } } } } } private func initatePurchase(provider: PaymentProvider, package: Package) { provider.initiatePurchase(forPackageIdentifier: package.package) { error, status, actionURL in if status == .cancel { return } guard !(error?.shouldInvalidate ?? false) else { return self.authenticate(provider: provider, package: package) } if error != nil || status == .failed { self.presentAlert(paymentError: error, title: String(localizationKey: "Purchase_Initiate_Fail.Title", type: .error)) } guard let actionURL = actionURL, status != .immediateSuccess else { return self.updatePurchaseStatus(package, nil) } DispatchQueue.main.async { PaymentAuthenticator.shared.handlePayment(actionURL: actionURL, provider: provider, window: self.window) { error, success in if error != nil { let title = String(localizationKey: "Purchase_Complete_Fail.Title", type: .error) return self.presentAlert(paymentError: error, title: title) } if success { self.updatePurchaseStatus(package, nil) } } } } } private func authenticate(provider: PaymentProvider, package: Package) { PaymentAuthenticator.shared.authenticate(provider: provider, window: self.window) { error, success in if error != nil { return self.presentAlert(paymentError: error, title: String(localizationKey: "Purchase_Auth_Complete_Fail.Title", type: .error)) } if success { self.updatePurchaseStatus(package, nil) } } } private func presentAlert(paymentError: PaymentError?, title: String) { DispatchQueue.main.async { UIApplication.shared.windows.last?.rootViewController?.present(PaymentError.alert(for: paymentError, title: title), animated: true, completion: nil) } } private func hapticResponse() { if #available(iOS 13, *) { let generator = UIImpactFeedbackGenerator(style: .soft) generator.impactOccurred() } else { let generator = UINotificationFeedbackGenerator() generator.notificationOccurred(.success) } } }
45.37827
169
0.551678
6494dffb7c2c3624142a765cddec1b00851badd5
1,491
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Foundation import AWSCore public class AmplifyAWSServiceConfiguration: AWSServiceConfiguration { static let version = "1.6.0" override public class func baseUserAgent() -> String! { //TODO: Retrieve this version from a centralized location: //https://github.com/aws-amplify/amplify-ios/issues/276 let platformInfo = AmplifyAWSServiceConfiguration.platformInformation() let systemName = UIDevice.current.systemName.replacingOccurrences(of: " ", with: "-") let systemVersion = UIDevice.current.systemVersion let localeIdentifier = Locale.current.identifier return "\(platformInfo) \(systemName)/\(systemVersion) \(localeIdentifier)" } override public var userAgent: String { return AmplifyAWSServiceConfiguration.baseUserAgent() } override public func copy(with zone: NSZone? = nil) -> Any { return super.copy(with: zone) } override init() { super.init(region: .Unknown, credentialsProvider: nil) } override public init(region regionType: AWSRegionType, credentialsProvider: AWSCredentialsProvider) { super.init(region: regionType, credentialsProvider: credentialsProvider) } public init(region regionType: AWSRegionType) { super.init(region: regionType, credentialsProvider: nil) } }
33.133333
93
0.694836
8f3480a5f648246f139a49161c293940efaf3332
2,047
// // UIToolbarExtensionTests.swift // BFKit-Swift // // The MIT License (MIT) // // Copyright (c) 2015 - 2019 Fabrizio Brancati. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. @testable import BFKit import Foundation import UIKit import XCTest internal class UIToolbarExtensionTests: XCTestCase { internal func testSetTrasparentTraslucent() { let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) toolbar.setTransparent(true, translucent: false) XCTAssertFalse(toolbar.isTranslucent) XCTAssertNotNil(toolbar.backgroundImage(forToolbarPosition: .any, barMetrics: .default)) XCTAssertNotNil(toolbar.shadowImage(forToolbarPosition: .any)) toolbar.setTransparent(false, translucent: true) XCTAssertTrue(toolbar.isTranslucent) XCTAssertNil(toolbar.backgroundImage(forToolbarPosition: .any, barMetrics: .default)) XCTAssertNil(toolbar.shadowImage(forToolbarPosition: .any)) } }
42.645833
96
0.735222
299d26572a8bb1e451c41061520b07772b37cad6
3,604
// // MainTabBarController.swift // ljwb // // Created by comma on 16/5/16. // Copyright © 2016年 lj. All rights reserved. // import UIKit class MainTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() addChildViewControllers() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) setupComposeBtn() } private func addChildViewControllers(){ let jsonPath = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil) let jsonData = NSData(contentsOfFile: jsonPath!) do{ let dictArray = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers) for dict in dictArray as! [[String:String]] { addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!) } }catch{ addChildViewController("HomeTableViewController", title: "首页", imageName: "tabbar_home") addChildViewController("MessageTableViewController", title: "消息", imageName: "tabbar_message_center") // 添加占位控制器 addChildViewController("NullViewController", title: "", imageName: "") addChildViewController("DiscoverTableViewController", title: "发现", imageName: "tabbar_discover") addChildViewController("ProfileTableViewController", title: "我", imageName: "tabbar_profile") } } private func addChildViewController(childControllerName: String, title : String, imageName:String) { let namespace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String print(namespace) let cls:AnyClass = NSClassFromString(namespace + "." + childControllerName)! let vcCls = cls as! UIViewController.Type let vc = vcCls.init() vc.title = title; vc.tabBarItem.image = UIImage(named: imageName) vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted") let nav = UINavigationController() nav.addChildViewController(vc) addChildViewController(nav) } private func setupComposeBtn() { tabBar.addSubview(composeBtn) let width = tabBar.bounds.width / CGFloat(viewControllers!.count) let rect = CGRect(x: width * 2, y: 0, width: width, height: tabBar.bounds.height) composeBtn.frame = rect } func composeBtnClick() { print("hello") } //懒加载 private lazy var composeBtn:UIButton = { let button = UIButton() button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal) button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted) button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal) button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) button.addTarget(self, action: "composeBtnClick", forControlEvents: UIControlEvents.TouchUpInside) return button }() }
29.785124
130
0.606271
1ecccda966a587c4dfd477be2807cc035f428f53
1,285
// // UILabel+Extensions.swift // // Created by Vignesh J on 07/10/20. // import UIKit extension UILabel { public func addCharacterSpacing(kernValue: CGFloat = 2) { guard let labelText = text, !labelText.isEmpty else { return } self.set(attributedText: labelText, kernValue: kernValue) } public func set(attributedText text: String, kernValue: CGFloat = 2) { let attributedString = NSMutableAttributedString(string: text) attributedString.addAttribute(NSAttributedString.Key.kern, value: kernValue, range: NSRange(location: 0, length: attributedString.length - 1)) self.attributedText = attributedString } public func size(forWidth width: CGFloat) -> CGSize { if let attributedText = self.attributedText { return attributedText.size(forWidth: width) } else if let text = self.text, let font = self.font { return text.size(forWidth: width, font: font) } else { return .zero } } }
30.595238
90
0.523735
380c7ff437ee8e9b68afe64d0bc7813a6874211a
3,769
// // ScanQrViewController.swift // IPtProxyUI // // Created by Benjamin Erhart on 2021-11-29. // Copyright © 2019-2021 Guardian Project. All rights reserved. // import UIKit import AVFoundation public protocol ScanQrDelegate: AnyObject { func scanned(value: String?) } open class ScanQrViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { private var captureSession: AVCaptureSession? private var videoPreviewLayer: AVCaptureVideoPreviewLayer? open weak var delegate: ScanQrDelegate? open override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString( "Scan QR Code", bundle: Bundle.iPtProxyUI, comment: "") if #available(iOS 13.0, *) { view.backgroundColor = .systemGroupedBackground } else { view.backgroundColor = .init(red: 242/255, green: 242/255, blue: 247/255, alpha: 1) } } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) startReading() } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) stopReading() } // MARK: AVCaptureMetadataOutputObjectsDelegate /** BUGFIX: Signature of method changed in Swift 4, without notifications. No migration assistance either. See https://stackoverflow.com/questions/46639519/avcapturemetadataoutputobjectsdelegate-not-called-in-swift-4-for-qr-scanner */ public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { if metadataObjects.count > 0, let metadata = metadataObjects[0] as? AVMetadataMachineReadableCodeObject, metadata.type == .qr { if let navC = navigationController { navC.popViewController(animated: true) delegate?.scanned(value: metadata.stringValue) } } } // MARK: Private Methods private func startReading() { if let captureDevice = AVCaptureDevice.default(for: .video) { do { let input = try AVCaptureDeviceInput(device: captureDevice) captureSession = AVCaptureSession() captureSession?.addInput(input) let captureMetadataOutput = AVCaptureMetadataOutput() captureSession?.addOutput(captureMetadataOutput) captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) captureMetadataOutput.metadataObjectTypes = [.qr] videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!) videoPreviewLayer?.videoGravity = .resizeAspectFill videoPreviewLayer?.frame = view.layer.bounds view.layer.addSublayer(videoPreviewLayer!) captureSession?.startRunning() return } catch { // Just fall thru to alert. } } let warning = UILabel(frame: .zero) warning.text = NSLocalizedString( "Camera access was not granted or QR Code scanning is not supported by your device.", bundle: Bundle.iPtProxyUI, comment: "") warning.translatesAutoresizingMaskIntoConstraints = false warning.numberOfLines = 0 warning.textAlignment = .center if #available(iOS 13.0, *) { warning.textColor = .secondaryLabel } else { warning.textColor = .init(red: 60/255, green: 60/255, blue: 67/255, alpha: 0.6) } view.addSubview(warning) warning.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16).isActive = true warning.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true warning.topAnchor.constraint(equalTo: view.topAnchor, constant: 16).isActive = true warning.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16).isActive = true } private func stopReading() { captureSession?.stopRunning() captureSession = nil videoPreviewLayer?.removeFromSuperlayer() videoPreviewLayer = nil } }
27.510949
126
0.748474
22645f96a1db60645f3d37de32e5e38382a569c4
3,249
// // SuperheroViewController.swift // Flix_Part1 // // Created by Mike Su on 10/23/18. // Copyright © 2018 Mike Su. All rights reserved. // import UIKit class SuperheroViewController: UIViewController, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! var movies: [[String: Any]] = [] override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.minimumInteritemSpacing = 5 layout.minimumLineSpacing = layout.minimumInteritemSpacing let cellsPerLine: CGFloat = 2 let interItemSpacingTotal = layout.minimumInteritemSpacing * (cellsPerLine - 1) let width = collectionView.frame.size.width / cellsPerLine - interItemSpacingTotal / cellsPerLine layout.itemSize = CGSize(width: width, height: width * 3 / 2) fetchMovies() // Do any additional setup after loading the view. } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return movies.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PosterCell", for: indexPath) as! PosterCell let movie = movies[indexPath.item] if let posterPathString = movie["poster_path"] as? String { let baseURLString = "https://image.tmdb.org/t/p/w500" let posterURL = URL(string: baseURLString + posterPathString)! cell.posterImageView.af_setImage(withURL: posterURL) } return cell } func fetchMovies() { //Request networking let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed")! let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10) let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main) let task = session.dataTask(with: request) { (data, response, error) in if let error = error { print(error.localizedDescription) } else if let data = data { let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] let movies = dataDictionary["results"] as! [[String: Any]] self.movies = movies self.collectionView.reloadData() //self.refreshControl.endRefreshing() } } task.resume() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
34.56383
121
0.63835
2f117590279ae314405b114e84e19b35d8a08663
3,127
// // SSNTextFieldTests.swift // FrameworkTests // // Created by Dima on 29.05.2020. // Copyright © 2020 VGS. All rights reserved. // import XCTest @testable import VGSCollectSDK class SSNTextFieldTests: XCTestCase { var collector: VGSCollect! var ssnTextField: VGSTextField! override func setUp() { collector = VGSCollect(id: "tntva5wfdrp") ssnTextField = VGSTextField() let config = VGSConfiguration(collector: collector, fieldName: "ssn") config.type = .ssn config.isRequired = true ssnTextField.configuration = config ssnTextField.textField.secureText = "123-44-5555" } override func tearDown() { collector = nil ssnTextField = nil } func testAlias() { XCTAssertTrue(ssnTextField.state.fieldName == "ssn") } func testContent() { XCTAssertTrue(ssnTextField.textField.secureText == "123-44-5555") } func testStates() { let state = ssnTextField.state XCTAssertFalse(state.isEmpty) XCTAssertTrue(state.isValid) XCTAssertTrue(state.isRequired) XCTAssertNotNil(state.description) XCTAssertTrue(state is SSNState, "SSNState should be available for .ssn configuration") } func testNotValidSSNReturnsFalse() { let config = VGSConfiguration(collector: collector, fieldName: "ssn") config.type = .ssn config.formatPattern = "" ssnTextField.configuration = config let notValidSSN = [ "111111111", "222222222", "555555555", "666666666", "999999999", "000000000", "000123456", "143004563", "235230000", "923423423", "666123456", "123456789", "219099999", "078051120", "457555462", "22334455", "3434343", "11111111222" ] for ssn in notValidSSN { ssnTextField.textField.secureText = ssn ssnTextField.focusOn() XCTAssertFalse(ssnTextField.state.isValid) XCTAssertFalse(ssnTextField.state.isEmpty) if let state = ssnTextField.state as? SSNState { XCTAssertTrue(state.last4 == "") } } } func testValidSSNReturnsTrue() { let config = VGSConfiguration(collector: collector, fieldName: "ssn") config.type = .ssn ssnTextField.configuration = config let validSSN = [ "111111112", "222232222", "455555555", "166666666", "899999999", "001010001", "100123456", "143104563", "235231000", "823423423", "665123455", "123456780", "219099998", "078051125", "457555465", /// mask should cut extra symbols "234567890123456789" ] for ssn in validSSN { ssnTextField.textField.secureText = ssn ssnTextField.focusOn() XCTAssertTrue(ssnTextField.state.isValid) XCTAssertTrue(ssnTextField.state.inputLength == 9) XCTAssertFalse(ssnTextField.state.isEmpty) if let state = ssnTextField.state as? SSNState { XCTAssertTrue(state.last4.count == 4) } } } }
29.5
95
0.618484
1d3c0d0385665853eefcfc07853d279f3d705dd0
1,149
// // tippyUITests.swift // tippyUITests // // Created by Xiaoyan Yang on 2/1/20. // Copyright © 2020 codepath. All rights reserved. // import XCTest class tippyUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
32.828571
182
0.687554
09aa2a5645887ea778fb5a7da75c4d4e4ec4ace4
2,770
import Foundation import CoreData import UIKit extension RootViewController { func clearData() { let delegate = UIApplication.sharedApplication().delegate as? AppDelegate if let context = delegate?.managedObjectContext { do { let entityNames = ["PostItem"] for entityName in entityNames { let fetchRequest = NSFetchRequest(entityName: entityName) let objects = try(context.executeFetchRequest(fetchRequest)) as? [NSManagedObject] for object in objects! { context.deleteObject(object) try(context.save()) } } } catch let err { print(err) } } } func insertData(rawPostItem: RawPostItem) { if let context = delegate?.managedObjectContext { let sample = NSEntityDescription.insertNewObjectForEntityForName("PostItem", inManagedObjectContext: context) as! PostItem sample.title = rawPostItem.title sample.creator = rawPostItem.creator sample.pubDate = rawPostItem.pubDate sample.link = rawPostItem.link sample.abstract = rawPostItem.abstract sample.content = rawPostItem.content sample.imageHeading = rawPostItem.imageHeading sample.creatorAvatar = rawPostItem.creatorAvatar do { try(context.save()) } catch let err { print(err) } } } func loadSampleData() { let sample: RawPostItem = RawPostItem(title: "Introducing Lazer", creator: "Team Super Monkey Bomb", pubDate: NSDate(), link: "https://github.com/zizhengwu/lazer", abstract: "Welcome to Lazer! Lazer wants to provide meaningful relaxation to you. By choosing your favourite topics, you will get the most interesting content tailored for you.", content: "Welcome to Lazer! Lazer wants to provide meaningful relaxation to you. By choosing your favourite topics, you will get the most interesting content tailored for you. <br><br>Lazer is certainly not another app to overwhelm you with endless information that you are not interested in. You could only read within your accepted relaxation / bucket time. When time is up, you will be reminded that you should get back to work. <br><br>Enjoy reading and keep working!", imageHeading: "http://i.imgur.com/JoTiTtg.png", creatorAvatar: "http://i.imgur.com/hmyoWhi.png") insertData(sample) } func loadData() { } }
43.968254
921
0.601083
cce85551b885dc386965f605eedd6f60ab9effad
11,273
// // EMUserProfileManager.swift // Hyphenate-Demo-Swift // // Created by dujiepeng on 2017/6/15. // Copyright © 2017 dujiepeng. All rights reserved. // import UIKit import Parse import Hyphenate let kPARSE_HXUSER = "hxuser" //let kPARSE_HXUSER = "HyphenateUser" let kPARSE_HXUSER_USERNAME = "username" let kPARSE_HXUSER_NICKNAME = "nickname" let kPARSE_HXUSER_AVATAR = "avatar" extension UIImage { func imageByScalingAndCroppingForSize(targetSize:CGSize) -> UIImage { let sourceImage = self var newImage : UIImage? = nil let imageSize = sourceImage.size let width = imageSize.width let height = imageSize.height let targetWidth = targetSize.width let targetHeight = targetSize.height var scaleFactor = 0.0 var scaleWidth = targetWidth var scaleHeight = targetHeight var thumbnailPoint = CGPoint(x: 0, y: 0 ) if imageSize != targetSize { let widthFactor = targetWidth / width let heightFactor = targetHeight / height if widthFactor > heightFactor { scaleFactor = Double(widthFactor) } else { scaleFactor = Double(heightFactor) } scaleWidth = CGFloat(Double(width) * scaleFactor) scaleHeight = CGFloat(Double(height) * scaleFactor) if widthFactor > heightFactor { thumbnailPoint.y = (targetHeight - scaleHeight) * 0.5 } else { thumbnailPoint.x = (targetWidth - scaleWidth) * 0.5 } } UIGraphicsBeginImageContext(targetSize) var thumbnailRect = CGRect.zero thumbnailRect.origin = thumbnailPoint thumbnailRect.size.width = scaleWidth thumbnailRect.size.height = scaleHeight sourceImage.draw(in: thumbnailRect) newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } } class UserProfileEntity: NSObject { var objectId:String? var username:String? var nickname:String? var imageUrl:String? override init() { super.init() } class func initPFObject(PFObject object: PFObject) -> UserProfileEntity{ let entity = UserProfileEntity() entity.username = object[kPARSE_HXUSER_USERNAME] as? String entity.nickname = object[kPARSE_HXUSER_NICKNAME] as? String let useranmeImage = object[kPARSE_HXUSER_AVATAR] as? PFFile if useranmeImage != nil { entity.imageUrl = useranmeImage?.url } return entity } } class EMUserProfileManager: NSObject { private var _currentName : String? var users = Dictionary<String, UserProfileEntity>() var objectId : String? var defaultACL: PFACL? static let sharedInstance = EMUserProfileManager() override init() { super.init() defaultACL = PFACL() defaultACL?.getPublicReadAccess = true defaultACL?.getPublicWriteAccess = true } func intParse() { let userDefault = UserDefaults.standard let objId : String? = userDefault.object(forKey: kPARSE_HXUSER + EMClient.shared().currentUsername) as? String if objId != nil { self.objectId = objId } _currentName = EMClient.shared().currentUsername initData() } func claerParse() { objectId = nil let userDefault = UserDefaults.standard if _currentName != nil { userDefault.removeObject(forKey: kPARSE_HXUSER + _currentName!) _currentName = nil } users.removeAll() } func initData() { users.removeAll() let query = PFQuery.init(className: kPARSE_HXUSER) query.findObjectsInBackground { (objects, error) in if objects != nil && objects!.count > 0 { for user in objects! { let entity = UserProfileEntity.initPFObject(PFObject: user) if (entity.username?.characters.count)! > 0 { user.setObject(entity, forKey: entity.username!) } } } } } func uploadUserHeadImageProfileInBackground(image: UIImage, complation:@escaping (Bool, Error?) -> Void) { weak var weakSelf = self let img = image.imageByScalingAndCroppingForSize(targetSize: CGSize.init(width: 120, height: 120)) if objectId != nil && (objectId?.characters.count)! > 0 { let object = PFObject(withoutDataWithClassName: kPARSE_HXUSER, objectId: objectId) DispatchQueue.global().async { do{ try object.fetchIfNeeded() } catch {} } let data = UIImageJPEGRepresentation(img, 0.5) let imageFile = PFFile.init(name: "image.png", data: data!) object[kPARSE_HXUSER_AVATAR] = imageFile object.saveInBackground(block: { (successed, error) in if successed { weakSelf?.savePFUserInDisk(obj: object) } complation(successed, error) }) } else { queryPFObject(complation: { (object, error) in if object != nil { let data = UIImageJPEGRepresentation(img, 0.5) let imageFile = PFFile.init(name: "image.png", data: data!) object?[kPARSE_HXUSER_AVATAR] = imageFile object!.saveInBackground(block: { (successed, error) in if successed { weakSelf?.savePFUserInDisk(obj: object) } complation(successed, error) }) }else { complation(false, error) } }) } } func updateUserProfileInBackground(param:Dictionary<String, Any>?, complation:@escaping (Bool, Error?) -> Void) { weak var weakSelf = self if objectId != nil && (objectId?.characters.count)! > 0 { let object = PFObject(withoutDataWithClassName: kPARSE_HXUSER, objectId: objectId) DispatchQueue.global().async { do{ try object.fetchIfNeeded() } catch {} } if param != nil && (param?.keys.count)! > 0 { for key in (param?.keys)! { object.setObject(param?[key]! as Any, forKey: key) } } weak var uObject = object object.saveInBackground(block: { (successed, error) in if successed { weakSelf?.savePFUserInDisk(obj: uObject) } complation(successed, error) }) } else { queryPFObject(complation: { (object, error) in if object != nil { if param != nil && (param?.keys.count)! > 0 { for key in (param?.keys)! { object?.setObject(param?[key]! as Any, forKey: key) } } weak var uObject = object! object!.saveInBackground(block: { (successed, error) in if successed { weakSelf?.savePFUserInDisk(obj: uObject) } complation(successed, error) }) }else { complation(false, error) } }) } } func loadUserProfileInBackgroundWithBuddy(buddyList:Array<String>, saveToLocat save:Bool, complation:@escaping (Bool, Error?)->Void) { var usernames = Array<String>() for buddyName in buddyList { if buddyName.characters.count > 0 { if getUserProfileByUsername(username: buddyName) == nil { usernames.append(buddyName) } } } if usernames.count == 0 { complation(true, nil) return } loadUserProfileInBackground(usernames: usernames, saveToLocal: save, complation: complation) } func loadUserProfileInBackground(usernames:Array<String>, saveToLocal save:Bool, complation:@escaping (Bool, Error?)->Void) { weak var weakSelf = self let query = PFQuery.init(className: kPARSE_HXUSER) query.whereKey(kPARSE_HXUSER_USERNAME, containedIn: usernames) query.findObjectsInBackground { (objects, error) in if error == nil { for user in objects! { let pfUser = user as PFObject if save { weakSelf?.savePFUserInDisk(obj: pfUser) } else { weakSelf?.savePFUserInMemory(obj: pfUser) } } complation(true, nil) } else { complation(false, error) } } } func getUserProfileByUsername(username:String?) -> UserProfileEntity? { if username != nil { if users[username!] != nil { return users[username!] } } return nil } func getCurUserProfile() -> UserProfileEntity? { return getUserProfileByUsername(username: EMClient.shared().currentUsername) } func getNickNameWithUsername(username:String) -> String { let entity = getUserProfileByUsername(username: username) if entity?.nickname != nil && (entity?.nickname?.characters.count)! > 0 { return (entity?.nickname)! } return username } // MARK: - Private func savePFUserInDisk(obj: PFObject?) { if obj != nil { obj!.pinInBackground(withName: EMClient.shared().currentUsername) savePFUserInMemory(obj: obj!) } } func savePFUserInMemory(obj: PFObject) { let entity = UserProfileEntity.initPFObject(PFObject: obj) users[entity.username!] = entity } func queryPFObject(complation:@escaping (PFObject?, Error?) -> Void) { let query = PFQuery.init(className: kPARSE_HXUSER) query.whereKey(kPARSE_HXUSER_USERNAME, equalTo: EMClient.shared().currentUsername) weak var weakSelf = self query.findObjectsInBackground { (objects, error) in if error == nil { if objects != nil && (objects?.count)! > 0 { let object = objects![0] as PFObject object.acl = weakSelf?.defaultACL let userDefault = UserDefaults.standard userDefault.set(object.objectId, forKey: kPARSE_HXUSER+EMClient.shared().currentUsername) userDefault.synchronize() complation(object, error) } }else { complation(nil,error) } } } }
35.009317
138
0.546971
2695f6ff467d8dbfd2c6373b425f00d986e917bc
1,100
import UIKit public extension CardView { /// It is compatible with any type of UIScrollView and UIScrollViewDelegate: /// (e.g. UITableViewDelegate, UICollectionViewDelegateFlowLayout and any other custom type). /// Do not overwrite scrollView.delegate, it will be used by ScrollShadeViewContent. public convenience init(scrollView: UIScrollView, delegate: UIScrollViewDelegate?, headerView: UIView) { self.init(content: ScrollShadeViewContent(scrollView: scrollView, delegate: delegate), headerView: headerView) } } public extension ShadeView { /// It is compatible with any type of UIScrollView and UIScrollViewDelegate: /// (e.g. UITableViewDelegate, UICollectionViewDelegateFlowLayout and any other custom type). /// Do not overwrite scrollView.delegate, it will be used by ScrollShadeViewContent. public convenience init(scrollView: UIScrollView, delegate: UIScrollViewDelegate?, headerView: UIView) { self.init(content: ScrollShadeViewContent(scrollView: scrollView, delegate: delegate), headerView: headerView) } }
45.833333
118
0.754545
feb565839e4016391470a7ea5baf4ae89c8a2e1d
551
// // GitTag.swift // VibesPush // // Created by Moin' Victor on 15/09/2020. // Copyright © 2020 Vibes. All rights reserved. // import Foundation /// A small data object to hold a Git Tag public struct GitTag { let name: String } extension GitTag: JSONEncodable, JSONDecodable { init?(json: VibesJSONDictionary) { guard let name = json["name"] as? String else { return nil } self.name = name } func encodeJSON() -> VibesJSONDictionary { return [ "name": name as AnyObject, ] } }
19.678571
68
0.615245
91137094820b06ab77080b1e326f23a34cb3da75
1,840
// // AppDelegate.swift // NiceOff // // Created by Paul Loots on 2019/09/28. // Copyright © 2019 Paul Loots. All rights reserved. // import UIKit import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. Api.Game.deleteGame(onSuccess: {print("Game Deleted")}, onError: {error in print("Delete Error") print(error)}) } }
40.888889
179
0.734783
d536f373b90e13c7580382f3cf4881790a6ee5ef
1,672
// // NSHostComponent.swift // TokamakAppKit // // Created by Max Desiatov on 29/12/2018. // import AppKit import Tokamak /// Any host component that is supposed to be rendered by `AppKitRenderer` /// should implement this protocol or any of concrete subprotocols: /// `NSViewComponent` for `NSView` targets, `NSControlComponent` for /// `NSControl` targets and `NSValueComponent` for `NSControl` components /// providing a configurable single value: `NSSlider`, /// `NSStepper`, `NSDatePicker`, or `NSSegmentedControl`. protocol NSHostComponent: AnyHostComponent { static func mountTarget( to parent: NSTarget, component: AppKitRenderer.MountedHost, _ renderer: AppKitRenderer ) -> NSTarget? static func update(target: NSTarget, node: AnyNode) static func unmount(target: NSTarget, completion: @escaping () -> ()) } extension NSHostComponent { static func targetAssertionFailure(_ function: String = #function) { typeAssertionFailure("target", function) } static func childrenAssertionFailure(_ function: String = #function) { typeAssertionFailure("children", function) } static func propsAssertionFailure(_ function: String = #function) { typeAssertionFailure("props", function) } static func parentAssertionFailure(_ function: String = #function) { typeAssertionFailure("parent target", function) } static func boxAssertionFailure(_ function: String = #function) { typeAssertionFailure("box", function) } private static func typeAssertionFailure(_ type: String, _ function: String) { assertionFailure(""" UIKitHostComponent passed unsupported \(type) type in \(function) """) } }
29.857143
80
0.732656
1cfa80661c71c8f93412c22ba45ef4a2b571f5fc
1,547
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Character // RUN: %target-run %target-swift-reflection-test %t/reflect_Character 2>&1 | FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop import SwiftReflectionTest class TestClass { var t: Character init(t: Character) { self.t = t } } var obj = TestClass(t: "A") reflect(object: obj) // CHECK-64: Reflecting an object. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_Character.TestClass) // CHECK-64: Type info: // CHECK-64: <null type info> // CHECK-32: Reflecting an object. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_Character.TestClass) // CHECK-32: Type info: // CHECK-32: <null type info> reflect(any: obj) // CHECK-64: Reflecting an existential. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_Character.TestClass) // CHECK-64: Type info: // CHECK-64: (reference kind=strong refcounting=native) // CHECK-32: Reflecting an existential. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_Character.TestClass) // CHECK-32: Type info: // CHECK-32: (reference kind=strong refcounting=native) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
26.672414
127
0.692308
094588e5e2f0ce0852d223002b3641067511382a
404
// // BeerStep.swift // MVVM-RxSwift-snapKit // // Created by GoEun Jeong on 2021/05/09. // import RxFlow enum BeerStep: Step { // Global case alert(String) // TabBar case TabBarIsRequired // Beer List case BeerListIsRequired case BeerDetailIsPicked (beer: Beer) // Search Beer case SearchBeerIsRequired // Random Beer case RandomBeerIsRequired }
14.962963
41
0.65099
01b81a9a138b5d4b1e93fa14f17afeb7fce81458
969
// // PublishRelay.swift // RxRelay // // Created by Krunoslav Zaher on 3/28/15. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import RxSwift /// 包装 `PublishSubject` 的结构体,不需要初始值。 /// /// 不会产生 error or completed 事件 public final class PublishRelay<Element>: ObservableType { private let subject: PublishSubject<Element> // Accepts `event` and emits it to subscribers public func accept(_ event: Element) { self.subject.onNext(event) } /// Initializes with internal empty subject. public init() { self.subject = PublishSubject() } /// Subscribes observer public func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element { self.subject.subscribe(observer) } /// - returns: Canonical interface for push style sequence public func asObservable() -> Observable<Element> { self.subject.asObservable() } }
26.189189
121
0.668731
dd8cfd6cc8dc14c217fff63e5a0a5b9d27041ce2
823
// // ViewController.swift // Number // // Created by HY on 2018/2/27. // Copyright © 2018年 XY. All rights reserved. // import UIKit struct XYModel:Codable { var age:Number? var name:Number? } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let dict = ["age":NSNull(),"name":123] as [String : Any] let data = try! JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted) do { let model = try JSONDecoder().decode(XYModel.self, from: data) print(model) } catch { print(error) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
19.595238
125
0.582017
e21e7053568e59f8cd5b94a430fdebfe2b0af7e6
3,148
// // MovieTableViewCell.swift // DiscoverMovies // // Created by Qingfeng Liu on 2020-01-22. // Copyright © 2020 Qingfeng Liu. All rights reserved. // import UIKit class MovieTableViewCell: UITableViewCell { @IBOutlet weak var posterImage: UIImageView! @IBOutlet weak var movieTitle: UILabel! @IBOutlet weak var releaseDate: UILabel! @IBOutlet weak var popularity: UILabel! var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView() func setMovie(movie:Movie) { let posterURL = IMAGE_BASE_URL + movie.poster_path guard let imageURL = URL(string: posterURL) else { print("imageURL invalid") return } showActivityIndicatory() DispatchQueue.global().async {[weak self] in guard let imageData = try? Data(contentsOf: imageURL) else { return } let image = UIImage(data: imageData) if let reducedImageData = image?.jpeg(.low) { let reducedImage = UIImage(data: reducedImageData) DispatchQueue.main.async { self?.posterImage.image = reducedImage//image self?.hideActivityIndicator() } } else { let reducedImage = UIImage(data: imageData) DispatchQueue.main.async { self?.posterImage.image = reducedImage//image self?.hideActivityIndicator() } } } movieTitle.text = movie.original_title releaseDate.text = movie.release_date releaseDate.textAlignment = .right releaseDate.adjustsFontSizeToFitWidth = true popularity.text = "Popularity: " + String(movie.popularity) popularity.textAlignment = .right popularity.adjustsFontSizeToFitWidth = true } func showActivityIndicatory(){ activityIndicator.frame = CGRect(x: 0, y: 0, width: 30, height: 30) activityIndicator.center = posterImage.center activityIndicator.hidesWhenStopped = true activityIndicator.style = UIActivityIndicatorView.Style.whiteLarge posterImage.addSubview(activityIndicator) activityIndicator.startAnimating() } func hideActivityIndicator(){ activityIndicator.stopAnimating() } } extension UIImage { enum JPEGQuality: CGFloat { case lowest = 0 case low = 0.25 case medium = 0.5 case high = 0.75 case highest = 1 } /// Returns the data for the specified image in JPEG format. /// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory. /// - returns: A data object containing the JPEG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format. func jpeg(_ jpegQuality: JPEGQuality) -> Data? { return jpegData(compressionQuality: jpegQuality.rawValue) } }
37.47619
242
0.635642
bf284f8507bc6a19999ffc2da0621c7a97f10cce
432
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not --crash %target-swift-frontend %s -emit-ir typealias e:A.d)class A:A}a
43.2
79
0.747685
03bcf3a574088650fd3a9cf240393ea8852d751f
775
// swift-tools-version:5.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Zip", products: [ .library(name: "Zip", targets: ["Zip"]) ], targets: [ .target( name: "Minizip", dependencies: [], path: "Zip/minizip", exclude: ["module"], linkerSettings: [ .linkedLibrary("z") ]), .target( name: "Zip", dependencies: ["Minizip"], path: "Zip", exclude: ["minizip", "zlib"]), .testTarget( name: "ZipTests", dependencies: ["Zip"], path: "ZipTests"), ] )
25.833333
96
0.482581
cc32eaa510d667226abefc09ce51e241146c469e
1,155
// swift-tools-version:5.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "NumberTicker", platforms: [ .iOS(.v13), .macOS(.v10_15), .tvOS(.v13), .watchOS(.v6) ], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "NumberTicker", targets: ["NumberTicker"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "NumberTicker", dependencies: []), .testTarget( name: "NumberTickerTests", dependencies: ["NumberTicker"]), ] )
33
122
0.602597
e86c7926de36ac2d44ac20e968757bafe6ebbebe
25,309
// Protocol Buffers for Swift // // Copyright 2014 Alexey Khohklov(AlexeyXo). // Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License") // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation let DEFAULT_RECURSION_LIMIT:Int = 64 let DEFAULT_SIZE_LIMIT:Int = 64 << 20 // 64MB let BUFFER_SIZE:Int = 4096 public class CodedInputStream { public var buffer:Data private var input:InputStream? private var bufferSize:Int = 0 private var bufferSizeAfterLimit:Int = 0 private var bufferPos:Int = 0 private var lastTag:Int32 = 0 private var totalBytesRetired:Int = 0 private var currentLimit:Int = 0 private var recursionDepth:Int = 0 private var recursionLimit:Int = 0 private var sizeLimit:Int = 0 public init (data:Data) { buffer = data bufferSize = buffer.count currentLimit = Int.max recursionLimit = DEFAULT_RECURSION_LIMIT sizeLimit = DEFAULT_SIZE_LIMIT } public init (stream:InputStream) { buffer = Data(capacity: BUFFER_SIZE)! bufferSize = 0 input = stream input?.open() // currentLimit = Int.max recursionLimit = DEFAULT_RECURSION_LIMIT sizeLimit = DEFAULT_SIZE_LIMIT } private func isAtEnd() throws -> Bool { if bufferPos == bufferSize { if !(try refillBuffer(mustSucceed: false)) { return true } } return false } private func refillBuffer(mustSucceed:Bool) throws -> Bool { guard bufferPos >= bufferSize else { throw ProtocolBuffersError.illegalState("RefillBuffer called when buffer wasn't empty.") } if (totalBytesRetired + bufferSize == currentLimit) { guard !mustSucceed else { throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message") } return false } totalBytesRetired += bufferSize bufferPos = 0 bufferSize = 0 if let input = self.input { let pointer = UnsafeMutablePointer<UInt8>((buffer as NSData).bytes) bufferSize = input.read(pointer, maxLength:buffer.count) } if bufferSize <= 0 { bufferSize = 0 guard !mustSucceed else { throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message") } return false } else { recomputeBufferSizeAfterLimit() let totalBytesRead = totalBytesRetired + bufferSize + bufferSizeAfterLimit guard totalBytesRead <= sizeLimit || totalBytesRead >= 0 else { throw ProtocolBuffersError.invalidProtocolBuffer("Size Limit Exceeded") } return true } } public func readRawData(size:Int) throws -> Data { let pointer = UnsafePointer<UInt8>((buffer as NSData).bytes) guard size >= 0 else { throw ProtocolBuffersError.invalidProtocolBuffer("Negative Size") } if totalBytesRetired + bufferPos + size > currentLimit { try skipRawData(size: currentLimit - totalBytesRetired - bufferPos) throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message") } if (size <= bufferSize - bufferPos) { let data = Data(bytes: pointer + bufferPos, count: size) bufferPos += size return data } else if (size < BUFFER_SIZE) { let bytes = Data(capacity: size)! var pos = bufferSize - bufferPos let byPointer = UnsafeMutablePointer<UInt8>((bytes as NSData).bytes) memcpy(byPointer, pointer + bufferPos, pos) bufferPos = bufferSize _ = try refillBuffer(mustSucceed: true) while size - pos > bufferSize { memcpy(byPointer + pos,pointer, bufferSize) pos += bufferSize bufferPos = bufferSize _ = try refillBuffer(mustSucceed: true) } memcpy(byPointer + pos, pointer, size - pos) bufferPos = size - pos return bytes } else { let originalBufferPos = bufferPos let originalBufferSize = bufferSize totalBytesRetired += bufferSize bufferPos = 0 bufferSize = 0 var sizeLeft = size - (originalBufferSize - originalBufferPos) var chunks:Array<Data> = Array<Data>() while (sizeLeft > 0) { var chunk = Data(capacity:min(sizeLeft, BUFFER_SIZE))! var pos:Int = 0 while pos < chunk.count { var n:Int = 0 if input != nil { let pointer = UnsafeMutablePointer<UInt8>((chunk as NSData).bytes) n = input!.read(pointer + pos, maxLength:chunk.count - pos) } guard n > 0 else { throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message") } totalBytesRetired += n pos += n } sizeLeft -= chunk.count chunks.append(chunk) } let bytes = Data(capacity: size)! let byPointer = UnsafeMutablePointer<UInt8>((bytes as NSData).bytes) var pos = originalBufferSize - originalBufferPos memcpy(byPointer, pointer + originalBufferPos, pos) for chunk in chunks { let chPointer = UnsafeMutablePointer<UInt8>((chunk as NSData).bytes) memcpy(byPointer + pos, chPointer, chunk.count) pos += chunk.count } return bytes } } // public func readRawData(size:Int) throws -> Data { // // guard size >= 0 else { // throw ProtocolBuffersError.invalidProtocolBuffer("Negative Size") // } // // if totalBytesRetired + bufferPos + size > currentLimit { // try skipRawData(size: currentLimit - totalBytesRetired - bufferPos) // throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message") // } // // if size <= bufferSize - bufferPos { // let pointer = UnsafePointer<UInt8>((buffer as NSData).bytes) // let data = Data(bytes: UnsafePointer<UInt8>(pointer + Int(bufferPos)), count: Int(size)) // bufferPos += size // return data // } else if (size < BUFFER_SIZE) { // // let bytes = Data(bytes: [0], count: size) // var pos = bufferSize - bufferPos // let pointer = UnsafeMutablePointer<UInt8>((bytes as NSData).bytes) // let bpointer = UnsafeMutablePointer<UInt8>((buffer as NSData).bytes) // memcpy(pointer, bpointer + bufferPos, pos) // //// buffer.copyBytes(to: pointer, from: bufferPos..<bufferPos+pos) // bufferPos = bufferSize // // _ = try refillBuffer(mustSucceed: true) // // while (size - pos > bufferSize) { // //// let pointerBuffer = UnsafeMutablePointer<UInt8>((buffer as NSData).bytes) // memcpy(pointer + pos, bpointer, bufferSize) // //// bytes.copyBytes(to: pointerBuffer, from: pos..<pos + bufferSize) // pos += bufferSize // bufferPos = bufferSize // _ = try refillBuffer(mustSucceed: true) // } // // let pointerBuffer = UnsafeMutablePointer<UInt8>((buffer as NSData).bytes) //// bytes.copyBytes(to: pointerBuffer, from: pos..<(pos + bufferSize) - size - pos) // memcpy(pointer + pos, bpointer, size - pos) // bufferPos = size - pos // return bytes // // } else { // // let originalBufferPos = bufferPos // let originalBufferSize = bufferSize // // totalBytesRetired += bufferSize // bufferPos = 0 // bufferSize = 0 // let bpointer = UnsafeMutablePointer<UInt8>((buffer as NSData).bytes) // var sizeLeft = size - (originalBufferSize - originalBufferPos) // var chunks:Array<Data> = Array<Data>() // // while (sizeLeft > 0) { // var chunk = Data(bytes: [0], count: BUFFER_SIZE) // var pos:Int = 0 // while (pos < chunk.count) { // // var n:Int = 0 // if let input = self.input { // let pointer = UnsafeMutablePointer<UInt8>((chunk as NSData).bytes) // n = input.read(pointer + pos, maxLength:chunk.count - pos) // } // guard n > 0 else { // throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message") // } // totalBytesRetired += n // pos += n // } // sizeLeft -= chunk.count // chunks.append(chunk) // } // // // var bytes = Data(bytes: [0], count: 0) // var pos:Int = originalBufferSize - originalBufferPos // let cpointer = UnsafeMutablePointer<UInt8>((bytes as NSData).bytes) // memcpy(cpointer, bpointer + Int(originalBufferPos), pos) //// bytes[0..<pos] = buffer[originalBufferPos..<originalBufferPos+pos] // // for chunk in chunks { // let chpointer = UnsafeMutablePointer<UInt8>((chunk as NSData).bytes) // memcpy(pointer + pos, cpointer, chunk.count) //// bytes[pos..<pos+chunk.count] = chunk[0..<chunk.count] // pos += chunk.count // } // // return bytes // } // } public func skipRawData(size:Int) throws{ guard size >= 0 else { throw ProtocolBuffersError.invalidProtocolBuffer("Negative Size") } if (totalBytesRetired + bufferPos + size > currentLimit) { try skipRawData(size: currentLimit - totalBytesRetired - bufferPos) throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message") } if (size <= (bufferSize - bufferPos)) { bufferPos += size } else { var pos:Int = bufferSize - bufferPos totalBytesRetired += pos bufferPos = 0 bufferSize = 0 while (pos < size) { let data = Data(bytes: [0], count: size - pos) var n:Int = 0 guard let input = self.input else { n = -1 throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message") } let pointer = UnsafeMutablePointer<UInt8>((data as NSData).bytes) n = input.read(pointer, maxLength:Int(size - pos)) pos += n totalBytesRetired += n } } } public func readRawLittleEndian32() throws -> Int32 { let b1:Int8 = try readRawByte() let b2:Int8 = try readRawByte() let b3:Int8 = try readRawByte() let b4:Int8 = try readRawByte() var result:Int32 = (Int32(b1) & 0xff) result |= ((Int32(b2) & 0xff) << 8) result |= ((Int32(b3) & 0xff) << 16) result |= ((Int32(b4) & 0xff) << 24) return result } public func readRawLittleEndian64() throws -> Int64 { let b1:Int8 = try readRawByte() let b2:Int8 = try readRawByte() let b3:Int8 = try readRawByte() let b4:Int8 = try readRawByte() let b5:Int8 = try readRawByte() let b6:Int8 = try readRawByte() let b7:Int8 = try readRawByte() let b8:Int8 = try readRawByte() var result:Int64 = (Int64(b1) & 0xff) result |= ((Int64(b2) & 0xff) << 8) result |= ((Int64(b3) & 0xff) << 16) result |= ((Int64(b4) & 0xff) << 24) result |= ((Int64(b5) & 0xff) << 32) result |= ((Int64(b6) & 0xff) << 40) result |= ((Int64(b7) & 0xff) << 48) result |= ((Int64(b8) & 0xff) << 56) return result } public func readTag() throws -> Int32 { if (try isAtEnd()) { lastTag = 0 return 0 } let tag = lastTag lastTag = try readRawVarint32() guard lastTag != 0 else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Tag: after tag \(tag)") } return lastTag } public func checkLastTagWas(value:Int32) throws { guard lastTag == value else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Tag: after tag \(lastTag)") } } public func skipField(tag:Int32) throws -> Bool { let wireFormat = WireFormat.getTagWireType(tag: tag) guard let format = WireFormat(rawValue: wireFormat) else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Wire Type") } switch format { case .varint: _ = try readInt32() return true case .fixed64: _ = try readRawLittleEndian64() return true case .lengthDelimited: try skipRawData(size: Int(try readRawVarint32())) return true case .startGroup: try skipMessage() try checkLastTagWas(value: WireFormat.endGroup.makeTag(fieldNumber: WireFormat.getTagFieldNumber(tag: tag))) return true case .endGroup: return false case .fixed32: _ = try readRawLittleEndian32() return true default: throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Wire Type") } } private func skipMessage() throws { while (true) { let tag:Int32 = try readTag() let fieldSkip = try skipField(tag: tag) if tag == 0 || !fieldSkip { break } } } public func readDouble() throws -> Double { let convert:Int64 = try readRawLittleEndian64() var result:Double = 0.0 result = WireFormat.convertTypes(convertValue: convert, defaultValue: result) return result } public func readFloat() throws -> Float { let convert:Int32 = try readRawLittleEndian32() var result:Float = 0.0 result = WireFormat.convertTypes(convertValue: convert, defaultValue: result) return result } public func readUInt64() throws -> UInt64 { var retvalue:UInt64 = 0 retvalue = WireFormat.convertTypes(convertValue: try readRawVarint64(), defaultValue:retvalue) return retvalue } public func readInt64() throws -> Int64 { return try readRawVarint64() } public func readInt32() throws -> Int32 { return try readRawVarint32() } public func readFixed64() throws -> UInt64 { var retvalue:UInt64 = 0 retvalue = WireFormat.convertTypes(convertValue: try readRawLittleEndian64(), defaultValue:retvalue) return retvalue } public func readFixed32() throws -> UInt32 { var retvalue:UInt32 = 0 retvalue = WireFormat.convertTypes(convertValue: try readRawLittleEndian32(), defaultValue:retvalue) return retvalue } public func readBool() throws ->Bool { return try readRawVarint32() != 0 } public func readRawByte() throws -> Int8 { if (bufferPos == bufferSize) { _ = try refillBuffer(mustSucceed: true) } let pointer = UnsafeMutablePointer<Int8>((buffer as NSData).bytes) let res = pointer[Int(bufferPos)] bufferPos+=1 return res } public class func readRawVarint32(firstByte:UInt8, inputStream:InputStream) throws -> Int32 { if ((Int32(firstByte) & 0x80) == 0) { return Int32(firstByte) } var result:Int32 = Int32(firstByte) & 0x7f var offset:Int32 = 7 while offset < 32 { var b:UInt8 = UInt8() guard inputStream.read(&b, maxLength: 1) > 0 else { throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message") } result |= (Int32(b) & 0x7f) << offset if ((b & 0x80) == 0) { return result } offset += 7 } while offset < 64 { var b:UInt8 = UInt8() guard inputStream.read(&b, maxLength: 1) > 0 else { throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message") } if ((b & 0x80) == 0) { return result } offset += 7 } throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message") } public func readRawVarint32() throws -> Int32 { var tmp : Int8 = try readRawByte(); if (tmp >= 0) { return Int32(tmp); } var result : Int32 = Int32(tmp) & 0x7f; tmp = try readRawByte() if (tmp >= 0) { result |= Int32(tmp) << 7; } else { result |= (Int32(tmp) & 0x7f) << 7; tmp = try readRawByte() if (tmp >= 0) { result |= Int32(tmp) << 14; } else { result |= (Int32(tmp) & 0x7f) << 14; tmp = try readRawByte() if (tmp >= 0) { result |= Int32(tmp) << 21; } else { result |= (Int32(tmp) & 0x7f) << 21; tmp = try readRawByte() result |= (Int32(tmp) << 28); if (tmp < 0) { // Discard upper 32 bits. for _ in 0..<5 { let byte = try readRawByte() if (byte >= 0) { return result; } } throw ProtocolBuffersError.invalidProtocolBuffer("MalformedVarint") } } } } return result; } public func readRawVarint64() throws -> Int64 { var shift:Int64 = 0 var result:Int64 = 0 while (shift < 64) { let b = try readRawByte() result |= (Int64(b & 0x7F) << shift) if ((Int32(b) & 0x80) == 0) { return result } shift += 7 } throw ProtocolBuffersError.invalidProtocolBuffer("MalformedVarint") } public func readString() throws -> String { let size = Int(try readRawVarint32()) if size <= (bufferSize - bufferPos) && size > 0 { let pointer = UnsafeMutablePointer<Int8>((buffer as NSData).bytes) let result = String(bytesNoCopy: pointer + bufferPos, length: size, encoding: String.Encoding.utf8, freeWhenDone: false) bufferPos += size return result! } else { let data = try readRawData(size: size) return String(data: data, encoding: String.Encoding.utf8)! } } public func readData() throws -> Data { let size = Int(try readRawVarint32()) if size < bufferSize - bufferPos && size > 0 { let pointer = UnsafeMutablePointer<Int8>((buffer as NSData).bytes) let data = Data(bytes: UnsafePointer<UInt8>(pointer + bufferPos), count: size) bufferPos += size return data } else { return try readRawData(size: size) } } public func readUInt32() throws -> UInt32 { let value:Int32 = try readRawVarint32() var retvalue:UInt32 = 0 retvalue = WireFormat.convertTypes(convertValue: value, defaultValue:retvalue) return retvalue } public func readEnum() throws -> Int32 { return try readRawVarint32() } public func readSFixed32() throws -> Int32 { return try readRawLittleEndian32() } public func readSFixed64() throws -> Int64 { return try readRawLittleEndian64() } public func readSInt32() throws -> Int32 { return WireFormat.decodeZigZag32(n: try readRawVarint32()) } public func readSInt64() throws -> Int64 { return WireFormat.decodeZigZag64(n: try readRawVarint64()) } public func setRecursionLimit(limit:Int) throws -> Int { guard limit >= 0 else { throw ProtocolBuffersError.illegalArgument("Recursion limit cannot be negative") } let oldLimit:Int = recursionLimit recursionLimit = limit return oldLimit } public func setSizeLimit(limit:Int) throws -> Int { guard limit >= 0 else { throw ProtocolBuffersError.illegalArgument("Recursion limit cannot be negative") } let oldLimit:Int = sizeLimit sizeLimit = limit return oldLimit } private func resetSizeCounter() { totalBytesRetired = 0 } private func recomputeBufferSizeAfterLimit() { bufferSize += bufferSizeAfterLimit let bufferEnd:Int = totalBytesRetired + bufferSize if (bufferEnd > currentLimit) { bufferSizeAfterLimit = bufferEnd - currentLimit bufferSize -= bufferSizeAfterLimit } else { bufferSizeAfterLimit = 0 } } public func pushLimit(byteLimit:Int) throws -> Int { guard byteLimit >= 0 else { throw ProtocolBuffersError.invalidProtocolBuffer("Negative Size") } let newByteLimit = byteLimit + totalBytesRetired + bufferPos let oldLimit = currentLimit guard newByteLimit <= oldLimit else { throw ProtocolBuffersError.invalidProtocolBuffer("MalformedVarint") } currentLimit = newByteLimit recomputeBufferSizeAfterLimit() return oldLimit } public func popLimit(oldLimit:Int) { currentLimit = oldLimit recomputeBufferSizeAfterLimit() } public func bytesUntilLimit() ->Int { if currentLimit == Int.max { return -1 } let currentAbsolutePosition:Int = totalBytesRetired + bufferPos return currentLimit - currentAbsolutePosition } public func readGroup(fieldNumber:Int, builder:MessageBuilder, extensionRegistry:ExtensionRegistry) throws { guard recursionDepth < recursionLimit else { throw ProtocolBuffersError.invalidProtocolBuffer("Recursion Limit Exceeded") } recursionDepth+=1 _ = try builder.mergeFrom(codedInputStream: self, extensionRegistry:extensionRegistry) try checkLastTagWas(value: WireFormat.endGroup.makeTag(fieldNumber: Int32(fieldNumber))) recursionDepth-=1 } public func readUnknownGroup(fieldNumber:Int32, builder:UnknownFieldSet.Builder) throws { guard recursionDepth < recursionLimit else { throw ProtocolBuffersError.invalidProtocolBuffer("Recursion Limit Exceeded") } recursionDepth+=1 _ = try builder.mergeFrom(codedInputStream: self) try checkLastTagWas(value: WireFormat.endGroup.makeTag(fieldNumber: fieldNumber)) recursionDepth-=1 } public func readMessage(builder:MessageBuilder, extensionRegistry:ExtensionRegistry) throws { let length = try readRawVarint32() guard recursionDepth < recursionLimit else { throw ProtocolBuffersError.invalidProtocolBuffer("Recursion Limit Exceeded") } let oldLimit = try pushLimit(byteLimit: Int(length)) recursionDepth+=1 _ = try builder.mergeFrom(codedInputStream: self, extensionRegistry:extensionRegistry) try checkLastTagWas(value: 0) recursionDepth-=1 popLimit(oldLimit: oldLimit) } }
35.797737
132
0.547908
11aa3c7a2222266bda0c2fa9c892709e7adeaa1c
8,137
// // TestBaPhed.swift // Graduation RequirementUITests // // Created by Shiqing. // Copyright © 2018 EECS393. All rights reserved. // import XCTest class TestBaPhed: XCTestCase { override func setUp() { // setup code here // stop immediately when a failure occurs continueAfterFailure = false // launch the application XCUIApplication().launch() } override func tearDown() { } //Test the correct functionality of users selecting how many PHED courses they have already taken func testBsPhed() { let app = XCUIApplication() app.pickerWheels["Spring 2020"].press(forDuration: 0.7); let confirmButton = app.buttons["Confirm"] confirmButton.tap() let selectButton = app.buttons["Select"] selectButton.tap() let tablesQuery = app.tables tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["EECS 132"]/*[[".cells.staticTexts[\"EECS 132\"]",".staticTexts[\"EECS 132\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["EECS 233"]/*[[".cells.staticTexts[\"EECS 233\"]",".staticTexts[\"EECS 233\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["EECS 281"]/*[[".cells.staticTexts[\"EECS 281\"]",".staticTexts[\"EECS 281\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["EECS 302"]/*[[".cells.staticTexts[\"EECS 302\"]",".staticTexts[\"EECS 302\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["EECS 340"]/*[[".cells.staticTexts[\"EECS 340\"]",".staticTexts[\"EECS 340\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() let doneButton = tablesQuery.buttons["Done"] doneButton.tap() let pickerWheel = app/*@START_MENU_TOKEN@*/.pickerWheels["0"]/*[[".pickers.pickerWheels[\"0\"]",".pickerWheels[\"0\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/ pickerWheel/*@START_MENU_TOKEN@*/.press(forDuration: 1.6);/*[[".tap()",".press(forDuration: 1.6);"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/ confirmButton.tap() pickerWheel/*@START_MENU_TOKEN@*/.press(forDuration: 0.6);/*[[".tap()",".press(forDuration: 0.6);"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/ confirmButton.tap() app.pickerWheels["Bachelor of Science"].swipeDown(); confirmButton.tap() selectButton.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["MATH 121"]/*[[".cells.staticTexts[\"MATH 121\"]",".staticTexts[\"MATH 121\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["MATH 122 or MATH 124"]/*[[".cells.staticTexts[\"MATH 122 or MATH 124\"]",".staticTexts[\"MATH 122 or MATH 124\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["MATH 223 or MATH 227"]/*[[".cells.staticTexts[\"MATH 223 or MATH 227\"]",".staticTexts[\"MATH 223 or MATH 227\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["MATH 201 or MATH 307"]/*[[".cells.staticTexts[\"MATH 201 or MATH 307\"]",".staticTexts[\"MATH 201 or MATH 307\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["CHEM 111"]/*[[".cells.staticTexts[\"CHEM 111\"]",".staticTexts[\"CHEM 111\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["ENGR 145"]/*[[".cells.staticTexts[\"ENGR 145\"]",".staticTexts[\"ENGR 145\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["PHYS 121 or PHYS 123"]/*[[".cells.staticTexts[\"PHYS 121 or PHYS 123\"]",".staticTexts[\"PHYS 121 or PHYS 123\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["PHYS 122 or PHYS 124"]/*[[".cells.staticTexts[\"PHYS 122 or PHYS 124\"]",".staticTexts[\"PHYS 122 or PHYS 124\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() doneButton.tap() pickerWheel/*@START_MENU_TOKEN@*/.press(forDuration: 0.5);/*[[".tap()",".press(forDuration: 0.5);"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/ confirmButton.tap() } func testBsPhedTwo() { let app = XCUIApplication() app.pickerWheels["Spring 2020"].press(forDuration: 0.7); let confirmButton = app.buttons["Confirm"] confirmButton.tap() let selectButton = app.buttons["Select"] selectButton.tap() let tablesQuery = app.tables tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["EECS 132"]/*[[".cells.staticTexts[\"EECS 132\"]",".staticTexts[\"EECS 132\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["EECS 233"]/*[[".cells.staticTexts[\"EECS 233\"]",".staticTexts[\"EECS 233\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["EECS 281"]/*[[".cells.staticTexts[\"EECS 281\"]",".staticTexts[\"EECS 281\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["EECS 302"]/*[[".cells.staticTexts[\"EECS 302\"]",".staticTexts[\"EECS 302\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["EECS 340"]/*[[".cells.staticTexts[\"EECS 340\"]",".staticTexts[\"EECS 340\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() let doneButton = tablesQuery.buttons["Done"] doneButton.tap() let pickerWheel = app/*@START_MENU_TOKEN@*/.pickerWheels["0"]/*[[".pickers.pickerWheels[\"0\"]",".pickerWheels[\"0\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/ pickerWheel/*@START_MENU_TOKEN@*/.press(forDuration: 1.6);/*[[".tap()",".press(forDuration: 1.6);"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/ confirmButton.tap() pickerWheel/*@START_MENU_TOKEN@*/.press(forDuration: 0.6);/*[[".tap()",".press(forDuration: 0.6);"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/ confirmButton.tap() app.pickerWheels["Bachelor of Science"].swipeDown(); confirmButton.tap() selectButton.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["MATH 121"]/*[[".cells.staticTexts[\"MATH 121\"]",".staticTexts[\"MATH 121\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["MATH 122 or MATH 124"]/*[[".cells.staticTexts[\"MATH 122 or MATH 124\"]",".staticTexts[\"MATH 122 or MATH 124\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["MATH 223 or MATH 227"]/*[[".cells.staticTexts[\"MATH 223 or MATH 227\"]",".staticTexts[\"MATH 223 or MATH 227\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["MATH 201 or MATH 307"]/*[[".cells.staticTexts[\"MATH 201 or MATH 307\"]",".staticTexts[\"MATH 201 or MATH 307\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["CHEM 111"]/*[[".cells.staticTexts[\"CHEM 111\"]",".staticTexts[\"CHEM 111\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["ENGR 145"]/*[[".cells.staticTexts[\"ENGR 145\"]",".staticTexts[\"ENGR 145\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["PHYS 121 or PHYS 123"]/*[[".cells.staticTexts[\"PHYS 121 or PHYS 123\"]",".staticTexts[\"PHYS 121 or PHYS 123\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() tablesQuery/*@START_MENU_TOKEN@*/.staticTexts["PHYS 122 or PHYS 124"]/*[[".cells.staticTexts[\"PHYS 122 or PHYS 124\"]",".staticTexts[\"PHYS 122 or PHYS 124\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() doneButton.tap() pickerWheel.swipeUp(); confirmButton.tap() } }
70.146552
216
0.594445
b9c20bdc9998b8a3dddb45c5bd2c6568e128664b
624
// // InternetManager.swift // mAARE // // Created by Dimitri Suter on 29.07.20. // Copyright © 2020 Dimitri Suter. All rights reserved. // import Foundation import Network import Combine class InternetManager: ObservableObject { @Published var hasInternet = true; public static let shared: InternetManager = InternetManager(); let monitor = NWPathMonitor() public func checkConnection() { monitor.pathUpdateHandler = { path in if path.status == .satisfied { self.hasInternet = true; print("We're connected!") } else { self.hasInternet = false; print("No connection.") } } } }
19.5
63
0.6875
08ddbec613a8f675ea4663e3970c115893434f10
8,179
// // CircleCache.swift // Circle // // Created by Ravi Rani on 2/15/15. // Copyright (c) 2015 RH Labs Inc. All rights reserved. // import Foundation import ProtobufRegistry import RealmSwift /** CircleCache is a simple key, value disk cache. It can be used to store app level settings and other client specific data. It internally uses NSUserDefaults at this time but the underlying implementation is abstracted such that it can be updated without impact on the application code. */ class CircleCache { struct Keys { static let RecentProfileVisits = "cache_recent_profile_visits" static let Integration = "cache_org_integration_%d" private static let KeyValidationTimers = "cache_key_validation_timers" } // Key Name - (Time of entry, number of seconds valid) private var timeForKeys = [String: AnyObject]() /** A shared instance of `CircleCache`. */ class var sharedInstance: CircleCache { struct Singleton { static let instance = CircleCache() } return Singleton.instance } func setObject(object: AnyObject, forKey key: String, forTimeInSeconds timeInSeconds: Int) { setObject(object, forKey: key) _setValidationTimer(timeInSeconds, forKey: key) } func setObject(object: AnyObject, forKey key: String) { _setObject(object, forKey: key) } func objectForKey(key: String) -> AnyObject? { if let object: AnyObject = _objectForKey(key) { if _isKeyValueValid(key) { return object } } return nil } func removeObjectForKey(key: String) { _removeObjectForKey(key) } func clearCache() { let keys = NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys for key in keys { if key.hasPrefix("cache_") { removeObjectForKey(key) } } // Remove entries from the persistent store // ASSUMPTION: We will be only using it as a cache for now dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in do { let realm = try Realm() try realm.write { realm.deleteAll() } } catch { print("Error: \(error)") } }) } private func _setValidationTimer(timeInSeconds: Int, forKey key: String) { var validationTimerForKeys = [String: AnyObject]() if let timeForKeys = objectForKey(CircleCache.Keys.KeyValidationTimers) as? Dictionary<String, AnyObject> { validationTimerForKeys = timeForKeys } validationTimerForKeys[key] = ["time_of_entry": NSDate().timeIntervalSince1970, "expires_in_time": timeInSeconds] setObject(validationTimerForKeys, forKey: CircleCache.Keys.KeyValidationTimers) } private func _isKeyValueValid(key: String) -> Bool { if let timeForKeys = _objectForKey(CircleCache.Keys.KeyValidationTimers) as? Dictionary<String, AnyObject>, timeValues: AnyObject = timeForKeys[key] { if Int((timeValues["time_of_entry"] as! NSTimeInterval) - NSDate().timeIntervalSince1970) > (timeValues["expires_in_time"] as! Int) { return false } } return true } private func _setObject(object: AnyObject, forKey key: String) { NSUserDefaults.standardUserDefaults().setObject(object, forKey: key) NSUserDefaults.standardUserDefaults().synchronize() } private func _objectForKey(key: String) -> AnyObject? { return NSUserDefaults.standardUserDefaults().objectForKey(key) } private func _removeObjectForKey(key: String) { NSUserDefaults.standardUserDefaults().removeObjectForKey(key) NSUserDefaults.standardUserDefaults().synchronize() } } extension CircleCache { static func recordProfileVisit(profile: Services.Profile.Containers.ProfileV1) { var existingProfilesIDs = CircleCache.sharedInstance.objectForKey(CircleCache.Keys.RecentProfileVisits) as! [String]? ?? [String]() let uniqueProfileIDs = NSMutableOrderedSet(array: existingProfilesIDs) uniqueProfileIDs.insertObject(profile.id, atIndex: 0) let maxRecords: Int = min(uniqueProfileIDs.count, 5) existingProfilesIDs = uniqueProfileIDs.array as! [String] existingProfilesIDs = Array(existingProfilesIDs[0..<maxRecords]) CircleCache.sharedInstance.setObject(existingProfilesIDs, forKey: CircleCache.Keys.RecentProfileVisits) } static func recordProfileSearchResult(profile: Services.Profile.Containers.ProfileV1) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in let recentSearchResult = RecentSearchResult() recentSearchResult.id = profile.id recentSearchResult.object = profile.data() recentSearchResult.type = RecentSearchResult.ResultType.Profile.rawValue RecentSearchResult.createOrUpdate(recentSearchResult) }) } static func updateCachedDataInRecordedSearchResultsForProfile(profile: Services.Profile.Containers.ProfileV1) { do { let recordedSearchResultsForProfile = try Realm().objects(RecentSearchResult).filter("id = %@ AND type = %d", profile.id, RecentSearchResult.ResultType.Profile.rawValue) for searchResult in recordedSearchResultsForProfile { try Realm().write({ () -> Void in searchResult.object = profile.data() }) } } catch { print("Error: \(error)") } } static func recordTeamSearchResult(team: Services.Organization.Containers.TeamV1) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in let recentSearchResult = RecentSearchResult() recentSearchResult.id = team.id recentSearchResult.object = team.data() recentSearchResult.type = RecentSearchResult.ResultType.Team.rawValue RecentSearchResult.createOrUpdate(recentSearchResult) }) } static func recordLocationSearchResult(location: Services.Organization.Containers.LocationV1) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in let recentSearchResult = RecentSearchResult() recentSearchResult.id = location.id recentSearchResult.object = location.data() recentSearchResult.type = RecentSearchResult.ResultType.Location.rawValue RecentSearchResult.createOrUpdate(recentSearchResult) }) } static func recordPostSearchResult(post: Services.Post.Containers.PostV1) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in let recentSearchResult = RecentSearchResult() recentSearchResult.id = post.id recentSearchResult.object = post.data() recentSearchResult.type = RecentSearchResult.ResultType.Post.rawValue RecentSearchResult.createOrUpdate(recentSearchResult) }) } static func getRecordedSearchResults(limit: Int) -> [AnyObject] { var searchResults = [AnyObject]() do { let recordedResults = try Realm().objects(RecentSearchResult).sorted("updated", ascending: false) var counter: Int = 0 for result in recordedResults { if counter >= limit { break } if let resultObject: AnyObject = RecentSearchResult.getObjectFromResult(result) { searchResults.append(resultObject) counter++ } } } catch { print("Error: \(error)") } return searchResults } }
38.399061
181
0.643844
efed97feb1f3464f506ecb871991d6d3be0a3add
7,986
// // HtmlParser.swift // Hackers // // Created by Weiran Zhang on 02/06/2020. // Copyright © 2020 Weiran Zhang. All rights reserved. // import Foundation import SwiftSoup enum HtmlParser { static func posts(from tableElement: Element, type: PostType) throws -> [Post] { if tableElement.hasClass("fatitem") { // single post let postElements = try tableElement.select("tr") let post = try self.post(from: postElements, type: type) post.text = self.postText(from: tableElement) return [post] } else if tableElement.hasClass("itemlist") { // post list let titleElements = try tableElement.select("tr.athing") let posts = try titleElements.compactMap { titleElement -> Post? in guard let metadataElement = try titleElement.nextElementSibling() else { return nil } let postElements = Elements([titleElement, metadataElement]) return try? self.post(from: postElements, type: type) } return posts } throw Exception.Error(type: .SelectorParseException, Message: "Couldn't find post elements") } static func post(from elements: Elements, type: PostType) throws -> Post { let rows = try elements.select("tr") guard let postElement: Element = safeGet(rows, index: 0), let metadataElement: Element = safeGet(rows, index: 1) else { throw Exception.Error(type: .SelectorParseException, Message: "Coldn't find post elements") } guard let id = Int(try postElement.attr("id")) else { throw Exception.Error(type: .SelectorParseException, Message: "Couldn't parse post ID") } let title = try postElement.select(".storylink").text() let urlString = try postElement.select(".storylink").attr("href") guard let url = URL(string: urlString) else { throw Exception.Error(type: .SelectorParseException, Message: "Couldn't parse post URL") } let by = try metadataElement.select(".hnuser").text() let score = try self.score(from: metadataElement) let age = try metadataElement.select(".age").text() let commentsCount = try self.commentsCount(from: metadataElement) var upvoted = false let voteLink = try? postElement.select(".votelinks a").first { $0.hasAttr("id") } if let voteLink = voteLink { let hasUnvote = try voteLink.attr("id").starts(with: "un_") let hasUpvote = try voteLink.attr("id").starts(with: "up_") let hasNosee = try voteLink.classNames().contains("nosee") upvoted = hasUnvote || (hasUpvote && hasNosee) } return Post( id: id, url: url, title: title, age: age, commentsCount: commentsCount, by: by, score: score, postType: type, upvoted: upvoted ) } static func postsTableElement(from html: String) throws -> Element { let document = try SwiftSoup.parse(html) guard let parentTable = try document .select("table.itemlist, table.fatitem") .first() else { throw Exception.Error(type: .SelectorParseException, Message: "Couldn't find post element") } return parentTable } static func commentElements(from html: String) throws -> Elements { let document = try SwiftSoup.parse(html) return try document.select(".comtr") } static func comment(from element: Element) throws -> Comment { let text = try commentText(from: element.select(".commtext")) let age = try element.select(".age").text() let user = try element.select(".hnuser").text() guard let id = try Int(element.select(".comtr").attr("id")) else { throw Exception.Error(type: .SelectorParseException, Message: "Couldn't parse comment id") } guard let indentWidth = try Int(element.select(".ind img").attr("width")) else { throw Exception.Error(type: .SelectorParseException, Message: "Couldn't parse comment indent width") } let level = indentWidth / 40 let upvoteLink = try element.select(".votelinks a").attr("href") var upvoted = false let voteLinks = try? element.select("a").filter { $0.hasAttr("id") } if let voteLinks = voteLinks { let hasUnvote = try voteLinks.first { try $0.attr("id").starts(with: "un_") } != nil upvoted = hasUnvote } let comment = Comment(id: id, age: age, text: text, by: user, level: level, upvoted: upvoted) comment.upvoteLink = upvoteLink return comment } private static func commentsCount(from metadataElement: Element) throws -> Int { let linkElements = try metadataElement.select("a") let commentLinkElement = try linkElements.first { try $0.text().contains("comment") } guard let commentLinkText = try commentLinkElement?.text(), let commentsCountString = commentLinkText.components(separatedBy: " ").first, let commentsCount = Int(String(commentsCountString)) else { return 0 } return commentsCount } private static func score(from metadataElement: Element) throws -> Int { let scoreString = try metadataElement.select(".score").text() guard let scoreNumberString = scoreString.components(separatedBy: " ").first, let score = Int(String(scoreNumberString)) else { return 0 } return score } private static func commentText(from elements: Elements) throws -> String { // clear reply link from text if let replyElement = try? elements.select(".reply") { try replyElement.html("") } // parse links from href attribute rather than truncated text if let links = try? elements.select("a") { try links.forEach { link in if let url = try? link.attr("href") { try link.html(url) } } } return try elements.html() } /// Returns any text content in the post, or otherwise nil private static func postText(from element: Element) -> String? { do { guard element.hasClass("fatitem") else { return nil } // go from the bottow row up to find the text guard let rowElements = try? element.select("tr"), var rowElement = rowElements.last() else { return nil } // if it contains a row, then check 2 rows up for text row // this happens because the user is logged in if try !rowElement.select("form").isEmpty() { let newIndex = rowElements.count - 3 guard let backThreeElement = safeGet(rowElements, index: newIndex) else { return nil } rowElement = backThreeElement } // if the row has a subtext column, that means there isn't // any post text guard try rowElement.select("td.subtext").isEmpty() else { return nil } // if we trim empty chars and the text is still empty then // return nil guard let text = try? rowElement.html(), !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil } return text } catch { return nil } } private static func safeGet(_ elements: Elements, index: Int) -> Element? { return elements.indices.contains(index) ? elements.get(index) : nil } }
38.956098
112
0.583146
1aeb8946c64570f3c22db11a133a7ea2eb3033b8
2,206
// // DogWebAPI.swift // CombineCollection // // import Combine import Foundation final class DogWebAPI { let baseURL = URL(string: "https://dog.ceo/api")! let client: HTTPClient let queue = DispatchQueue(label: "DogWebAPI") init(client: HTTPClient) { self.client = client } var breedListLoader: BreedListLoader { struct BreedListAPIModel: Decodable { let message: [String: [String]] let status: String } func convert(from model: BreedListAPIModel) -> [Breed] { let messages = model.message return messages.map { message in Breed(name: message.key, subBreeds: message.value .map { Breed(name: $0, subBreeds: []) }) } } return BreedListLoader { [self] in let request = URLRequest(url: baseURL.appendingPathComponent("breeds/list/all")) return client.send(request: request) .subscribe(on: queue) .decode(type: BreedListAPIModel.self, decoder: JSONDecoder()) .map(convert(from:)) .eraseToAnyPublisher() } } var dogImageListLoader: DogImageListLoader { struct DogImageListAPIModel: Decodable { let message: [String] let status: String } func convert(from model: DogImageListAPIModel) -> [DogImage] { let urlStrings = model.message let dogImages = urlStrings.compactMap { urlString -> DogImage? in guard let url = URL(string: urlString) else { return nil } return DogImage(imageURL: url) } return dogImages } return DogImageListLoader { [self] breedType in let request = URLRequest(url: baseURL.appendingPathComponent("/breed/\(breedType)/images")) return client.send(request: request) .subscribe(on: queue) .decode(type: DogImageListAPIModel.self, decoder: JSONDecoder()) .map(convert(from:)) .eraseToAnyPublisher() } } }
31.514286
103
0.55757
23a19b38592a8a74ce8dd7d40b95676b1fb53e2b
21,776
// // PetAPI.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Alamofire import RxSwift public class PetAPI: APIBase { /** Add a new pet to the store - parameter body: (body) Pet object that needs to be added to the store (optional) - parameter completion: completion handler to receive the data and the error objects */ public class func addPet(body body: Pet? = nil, completion: ((error: ErrorType?) -> Void)) { addPetWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(error: error); } } /** Add a new pet to the store - parameter body: (body) Pet object that needs to be added to the store (optional) - returns: Observable<Void> */ public class func addPet(body body: Pet? = nil) -> Observable<Void> { return Observable.create { observer -> Disposable in addPet(body: body) { error in if let error = error { observer.on(.Error(error as ErrorType)) } else { observer.on(.Next()) } observer.on(.Completed) } return NopDisposable.instance } } /** Add a new pet to the store - POST /pet - - OAuth: - type: oauth2 - name: petstore_auth - parameter body: (body) Pet object that needs to be added to the store (optional) - returns: RequestBuilder<Void> */ public class func addPetWithRequestBuilder(body body: Pet? = nil) -> RequestBuilder<Void> { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } /** Deletes a pet - parameter petId: (path) Pet id to delete - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ public class func deletePet(petId petId: Int64, apiKey: String? = nil, completion: ((error: ErrorType?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in completion(error: error); } } /** Deletes a pet - parameter petId: (path) Pet id to delete - parameter apiKey: (header) (optional) - returns: Observable<Void> */ public class func deletePet(petId petId: Int64, apiKey: String? = nil) -> Observable<Void> { return Observable.create { observer -> Disposable in deletePet(petId: petId, apiKey: apiKey) { error in if let error = error { observer.on(.Error(error as ErrorType)) } else { observer.on(.Next()) } observer.on(.Completed) } return NopDisposable.instance } } /** Deletes a pet - DELETE /pet/{petId} - - OAuth: - type: oauth2 - name: petstore_auth - parameter petId: (path) Pet id to delete - parameter apiKey: (header) (optional) - returns: RequestBuilder<Void> */ public class func deletePetWithRequestBuilder(petId petId: Int64, apiKey: String? = nil) -> RequestBuilder<Void> { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) let convertedParameters = APIHelper.convertBoolToString(parameters) let nillableHeaders: [String: AnyObject?] = [ "api_key": apiKey ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true, headers: headerParameters) } /** Finds Pets by status - parameter status: (query) Status values that need to be considered for filter (optional, default to available) - parameter completion: completion handler to receive the data and the error objects */ public class func findPetsByStatus(status status: [String]? = nil, completion: ((data: [Pet]?, error: ErrorType?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute { (response, error) -> Void in completion(data: response?.body, error: error); } } /** Finds Pets by status - parameter status: (query) Status values that need to be considered for filter (optional, default to available) - returns: Observable<[Pet]> */ public class func findPetsByStatus(status status: [String]? = nil) -> Observable<[Pet]> { return Observable.create { observer -> Disposable in findPetsByStatus(status: status) { data, error in if let error = error { observer.on(.Error(error as ErrorType)) } else { observer.on(.Next(data!)) } observer.on(.Completed) } return NopDisposable.instance } } /** Finds Pets by status - GET /pet/findByStatus - Multiple status values can be provided with comma separated strings - OAuth: - type: oauth2 - name: petstore_auth - examples: [{contentType=application/json, example={ "name" : "Puma", "type" : "Dog", "color" : "Black", "gender" : "Female", "breed" : "Mixed" }}] - parameter status: (query) Status values that need to be considered for filter (optional, default to available) - returns: RequestBuilder<[Pet]> */ public class func findPetsByStatusWithRequestBuilder(status status: [String]? = nil) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [ "status": status ] let parameters = APIHelper.rejectNil(nillableParameters) let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** Finds Pets by tags - parameter tags: (query) Tags to filter by (optional) - parameter completion: completion handler to receive the data and the error objects */ public class func findPetsByTags(tags tags: [String]? = nil, completion: ((data: [Pet]?, error: ErrorType?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute { (response, error) -> Void in completion(data: response?.body, error: error); } } /** Finds Pets by tags - parameter tags: (query) Tags to filter by (optional) - returns: Observable<[Pet]> */ public class func findPetsByTags(tags tags: [String]? = nil) -> Observable<[Pet]> { return Observable.create { observer -> Disposable in findPetsByTags(tags: tags) { data, error in if let error = error { observer.on(.Error(error as ErrorType)) } else { observer.on(.Next(data!)) } observer.on(.Completed) } return NopDisposable.instance } } /** Finds Pets by tags - GET /pet/findByTags - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - OAuth: - type: oauth2 - name: petstore_auth - examples: [{contentType=application/json, example=[ { "photoUrls" : [ "photoUrls", "photoUrls" ], "name" : "doggie", "id" : 0, "category" : { "name" : "name", "id" : 6 }, "tags" : [ { "name" : "name", "id" : 1 }, { "name" : "name", "id" : 1 } ], "status" : "available" }, { "photoUrls" : [ "photoUrls", "photoUrls" ], "name" : "doggie", "id" : 0, "category" : { "name" : "name", "id" : 6 }, "tags" : [ { "name" : "name", "id" : 1 }, { "name" : "name", "id" : 1 } ], "status" : "available" } ]}, {contentType=application/xml, example=<Pet> <id>123456789</id> <name>doggie</name> <photoUrls> <photoUrls>aeiou</photoUrls> </photoUrls> <tags> </tags> <status>aeiou</status> </Pet>}] - examples: [{contentType=application/json, example=[ { "photoUrls" : [ "photoUrls", "photoUrls" ], "name" : "doggie", "id" : 0, "category" : { "name" : "name", "id" : 6 }, "tags" : [ { "name" : "name", "id" : 1 }, { "name" : "name", "id" : 1 } ], "status" : "available" }, { "photoUrls" : [ "photoUrls", "photoUrls" ], "name" : "doggie", "id" : 0, "category" : { "name" : "name", "id" : 6 }, "tags" : [ { "name" : "name", "id" : 1 }, { "name" : "name", "id" : 1 } ], "status" : "available" } ]}, {contentType=application/xml, example=<Pet> <id>123456789</id> <name>doggie</name> <photoUrls> <photoUrls>aeiou</photoUrls> </photoUrls> <tags> </tags> <status>aeiou</status> </Pet>}] - parameter tags: (query) Tags to filter by (optional) - returns: RequestBuilder<[Pet]> */ public class func findPetsByTagsWithRequestBuilder(tags tags: [String]? = nil) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [ "tags": tags ] let parameters = APIHelper.rejectNil(nillableParameters) let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** Find pet by ID - parameter petId: (path) ID of pet that needs to be fetched - parameter completion: completion handler to receive the data and the error objects */ public class func getPetById(petId petId: Int64, completion: ((data: Pet?, error: ErrorType?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute { (response, error) -> Void in completion(data: response?.body, error: error); } } /** Find pet by ID - parameter petId: (path) ID of pet that needs to be fetched - returns: Observable<Pet> */ public class func getPetById(petId petId: Int64) -> Observable<Pet> { return Observable.create { observer -> Disposable in getPetById(petId: petId) { data, error in if let error = error { observer.on(.Error(error as ErrorType)) } else { observer.on(.Next(data!)) } observer.on(.Completed) } return NopDisposable.instance } } /** Find pet by ID - GET /pet/{petId} - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - API Key: - type: apiKey api_key - name: api_key - OAuth: - type: oauth2 - name: petstore_auth - examples: [{contentType=application/json, example={ "photoUrls" : [ "photoUrls", "photoUrls" ], "name" : "doggie", "id" : 0, "category" : { "name" : "name", "id" : 6 }, "tags" : [ { "name" : "name", "id" : 1 }, { "name" : "name", "id" : 1 } ], "status" : "available" }}, {contentType=application/xml, example=<Pet> <id>123456789</id> <name>doggie</name> <photoUrls> <photoUrls>aeiou</photoUrls> </photoUrls> <tags> </tags> <status>aeiou</status> </Pet>}] - examples: [{contentType=application/json, example={ "photoUrls" : [ "photoUrls", "photoUrls" ], "name" : "doggie", "id" : 0, "category" : { "name" : "name", "id" : 6 }, "tags" : [ { "name" : "name", "id" : 1 }, { "name" : "name", "id" : 1 } ], "status" : "available" }}, {contentType=application/xml, example=<Pet> <id>123456789</id> <name>doggie</name> <photoUrls> <photoUrls>aeiou</photoUrls> </photoUrls> <tags> </tags> <status>aeiou</status> </Pet>}] - parameter petId: (path) ID of pet that needs to be fetched - returns: RequestBuilder<Pet> */ public class func getPetByIdWithRequestBuilder(petId petId: Int64) -> RequestBuilder<Pet> { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<Pet>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** Update an existing pet - parameter body: (body) Pet object that needs to be added to the store (optional) - parameter completion: completion handler to receive the data and the error objects */ public class func updatePet(body body: Pet? = nil, completion: ((error: ErrorType?) -> Void)) { updatePetWithRequestBuilder(body: body).execute { (response, error) -> Void in completion(error: error); } } /** Update an existing pet - parameter body: (body) Pet object that needs to be added to the store (optional) - returns: Observable<Void> */ public class func updatePet(body body: Pet? = nil) -> Observable<Void> { return Observable.create { observer -> Disposable in updatePet(body: body) { error in if let error = error { observer.on(.Error(error as ErrorType)) } else { observer.on(.Next()) } observer.on(.Completed) } return NopDisposable.instance } } /** Update an existing pet - PUT /pet - - OAuth: - type: oauth2 - name: petstore_auth - parameter body: (body) Pet object that needs to be added to the store (optional) - returns: RequestBuilder<Void> */ public class func updatePetWithRequestBuilder(body body: Pet? = nil) -> RequestBuilder<Void> { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) } /** Updates a pet in the store with form data - parameter petId: (path) ID of pet that needs to be updated - parameter name: (form) Updated name of the pet (optional) - parameter status: (form) Updated status of the pet (optional) - parameter completion: completion handler to receive the data and the error objects */ public class func updatePetWithForm(petId petId: String, name: String? = nil, status: String? = nil, completion: ((error: ErrorType?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute { (response, error) -> Void in completion(error: error); } } /** Updates a pet in the store with form data - parameter petId: (path) ID of pet that needs to be updated - parameter name: (form) Updated name of the pet (optional) - parameter status: (form) Updated status of the pet (optional) - returns: Observable<Void> */ public class func updatePetWithForm(petId petId: String, name: String? = nil, status: String? = nil) -> Observable<Void> { return Observable.create { observer -> Disposable in updatePetWithForm(petId: petId, name: name, status: status) { error in if let error = error { observer.on(.Error(error as ErrorType)) } else { observer.on(.Next()) } observer.on(.Completed) } return NopDisposable.instance } } /** Updates a pet in the store with form data - POST /pet/{petId} - - OAuth: - type: oauth2 - name: petstore_auth - parameter petId: (path) ID of pet that needs to be updated - parameter name: (form) Updated name of the pet (optional) - parameter status: (form) Updated status of the pet (optional) - returns: RequestBuilder<Void> */ public class func updatePetWithFormWithRequestBuilder(petId petId: String, name: String? = nil, status: String? = nil) -> RequestBuilder<Void> { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [ "name": name, "status": status ] let parameters = APIHelper.rejectNil(nillableParameters) let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) } /** uploads an image - parameter petId: (path) ID of pet to update - parameter additionalMetadata: (form) Additional data to pass to server (optional) - parameter file: (form) file to upload (optional) - parameter completion: completion handler to receive the data and the error objects */ public class func uploadFile(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil, completion: ((error: ErrorType?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute { (response, error) -> Void in completion(error: error); } } /** uploads an image - parameter petId: (path) ID of pet to update - parameter additionalMetadata: (form) Additional data to pass to server (optional) - parameter file: (form) file to upload (optional) - returns: Observable<Void> */ public class func uploadFile(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil) -> Observable<Void> { return Observable.create { observer -> Disposable in uploadFile(petId: petId, additionalMetadata: additionalMetadata, file: file) { error in if let error = error { observer.on(.Error(error as ErrorType)) } else { observer.on(.Next()) } observer.on(.Completed) } return NopDisposable.instance } } /** uploads an image - POST /pet/{petId}/uploadImage - - OAuth: - type: oauth2 - name: petstore_auth - parameter petId: (path) ID of pet to update - parameter additionalMetadata: (form) Additional data to pass to server (optional) - parameter file: (form) file to upload (optional) - returns: RequestBuilder<Void> */ public class func uploadFileWithRequestBuilder(petId petId: Int64, additionalMetadata: String? = nil, file: NSURL? = nil) -> RequestBuilder<Void> { var path = "/pet/{petId}/uploadImage" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [ "additionalMetadata": additionalMetadata, "file": file ] let parameters = APIHelper.rejectNil(nillableParameters) let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) } }
32.993939
152
0.602636
793a5afcc96132529b8ca680cd75fbb4f8ef1e8d
2,223
// // SearchSection.swift // MovieDemo // // Created by Oscar Vernis on 15/10/20. // Copyright © 2020 Oscar Vernis. All rights reserved. // import UIKit class SearchSection: FetchableSection { var dataProvider = SearchDataProvider() init() { self.dataProvider.didUpdate = { error in self.didUpdate?(error) } } var isLastPage: Bool { return dataProvider.isLastPage } var didUpdate: ((Error?) -> Void)? func refresh() { dataProvider.refresh() } func fetchNextPage() { dataProvider.fetchNextPage() } var itemCount: Int { dataProvider.itemCount } func registerReusableViews(withCollectionView collectionView: UICollectionView) { MovieInfoListCell.register(withCollectionView: collectionView) CreditPhotoListCell.register(withCollectionView: collectionView) } func sectionLayout() -> NSCollectionLayoutSection { let sectionBuilder = MoviesCompositionalLayoutBuilder() let section = sectionBuilder.createListSection() section.contentInsets.bottom = 30 return section } func cell(withCollectionView collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell { let item = dataProvider.item(atIndex: indexPath.row) let cell: UICollectionViewCell switch item { case let movie as Movie: let movieCell = collectionView.dequeueReusableCell(withReuseIdentifier: MovieInfoListCell.reuseIdentifier, for: indexPath) as! MovieInfoListCell MovieInfoCellConfigurator().configure(cell: movieCell, with: MovieViewModel(movie: movie)) cell = movieCell case let person as Person: let personCell = collectionView.dequeueReusableCell(withReuseIdentifier: CreditPhotoListCell.reuseIdentifier, for: indexPath) as! CreditPhotoListCell PersonCreditPhotoListConfigurator().configure(cell: personCell, person: PersonViewModel(person: person)) cell = personCell default: fatalError() } return cell } }
30.040541
161
0.654071
5d84e9081029b6472669d645d31158100e68533b
1,738
// // FaceDetectionUtility.swift // CardScanner // // Created by Hassan Shahbazi on 12/5/18. // Copyright © 2018 Hassan Shahbazi. All rights reserved. // import UIKit import CoreML import Vision protocol FaceDetectionUtilityDelegate { func didDetectFaceImage(_ image: CIImage, at rect: CGRect) } class FaceDetectionUtility: DetectionUtility { public var delegate: FaceDetectionUtilityDelegate? private var faceQueue: DispatchQueue! private lazy var facesRequest: VNDetectFaceRectanglesRequest = { return VNDetectFaceRectanglesRequest(completionHandler: self.handleRequest) }() override init() { super.init() faceQueue = DispatchQueue(label: "face_detection_queue", qos: .background, attributes: [], autoreleaseFrequency: .workItem, target: queueTarget) } override func detect(_ liveImage: CIImage) { self.inputImage = liveImage let handler = VNImageRequestHandler(ciImage: inputImage, orientation: .up) faceQueue.async { try? handler.perform([self.facesRequest]) } } override func handleRequest(request: VNRequest, error: Error?) { guard let observations = request.results as? [VNFaceObservation] else { return } guard let detectedFace = observations.first else { return } let imageSize = inputImage.extent.size let boundingBox = detectedFace.boundingBox.scaled(to: imageSize) let correctedImage = inputImage.cropped(to: boundingBox).oriented(forExifOrientation: Int32(CGImagePropertyOrientation.up.rawValue)) DispatchQueue.main.async { self.delegate?.didDetectFaceImage(correctedImage, at: boundingBox) } } }
34.76
152
0.697353
f7f3ec5263602ea758a3495399545f753ec819d3
486
// // DataManager.swift // Pocket USA // // Created by Wei Huang on 3/2/17. // Copyright © 2017 Wei Huang. All rights reserved. // import Foundation // Source feed in the JSON public struct SourceFeed: Decodable { public let orgName: String? public init?(json: JSON) { guard let sourceFeed: JSON = "source" <~~ json, let orgName: String = "org" <~~ sourceFeed else { return nil } self.orgName = orgName } }
21.130435
61
0.584362
d9402ccad4376f76633b971d5826c1e1b29d28e7
819
//: [Previous](@previous) import Foundation import Peppermint /*: ## `KeyPathConstraint` In the following example we use a `KeyPathConstraint` to evaluate that the `.email` property of the `LoginData` type is a valid email address. */ struct LoginData { enum Error: Swift.Error { case email case password } var email: String var password: String } let constraint = KeyPathConstraint<LoginData, String, LoginData.Error>(\.email) { PredicateConstraint(EmailPredicate(), error: .email) } let data = LoginData(email: "[email protected]", password: "p@ssW0rd") let result = constraint.evaluate(with: data) switch result { case .success: print("You got 📬!") case .failure(let summary): print(summary.errors.map({$0.localizedDescription})) } //: [Next](@next)
21.552632
143
0.684982
768a459dc9e78e8f980603e4615265e6995b4be6
5,833
// Copyright © 2018 Stormbird PTE. LTD. import Foundation import UIKit import BigInt struct EthTokenViewCellViewModel { private let shortFormatter = EtherNumberFormatter.short private let token: TokenObject private let currencyAmount: Double? private let ticker: CoinTicker? private let assetDefinitionStore: AssetDefinitionStore private let isVisible: Bool init( token: TokenObject, ticker: CoinTicker?, currencyAmount: Double?, assetDefinitionStore: AssetDefinitionStore, isVisible: Bool = true ) { self.token = token self.ticker = ticker self.currencyAmount = currencyAmount self.assetDefinitionStore = assetDefinitionStore self.isVisible = isVisible } private var amount: String { return shortFormatter.string(from: BigInt(token.value) ?? BigInt(), decimals: token.decimals) } private var title: String { return token.shortTitleInPluralForm(withAssetDefinitionStore: assetDefinitionStore) } var backgroundColor: UIColor { return Screen.TokenCard.Color.background } var contentsBackgroundColor: UIColor { return Screen.TokenCard.Color.background } var titleAttributedString: NSAttributedString { return NSAttributedString(string: title, attributes: [ .foregroundColor: Screen.TokenCard.Color.title, .font: Screen.TokenCard.Font.title ]) } var cryptoValueAttributedString: NSAttributedString { return NSAttributedString(string: amount + " " + token.symbolInPluralForm(withAssetDefinitionStore: assetDefinitionStore), attributes: [ .foregroundColor: Screen.TokenCard.Color.subtitle, .font: Screen.TokenCard.Font.subtitle ]) } private var valuePercentageChangeColor: UIColor { return Screen.TokenCard.Color.valueChangeValue(ticker: ticker) } private var apprecation24hoursBackgroundColor: UIColor { valuePercentageChangeColor.withAlphaComponent(0.07) } private var apprecation24hoursImage: UIImage? { switch EthCurrencyHelper(ticker: ticker).change24h { case .appreciate: return R.image.price_up() case .depreciate: return R.image.price_down() case .none: return .none } } private var apprecation24hoursAttributedString: NSAttributedString { let valuePercentageChangeValue: String = { switch EthCurrencyHelper(ticker: ticker).change24h { case .appreciate(let percentageChange24h): return "\(percentageChange24h)%" case .depreciate(let percentageChange24h): return "\(percentageChange24h)%" case .none: return "-" } }() return NSAttributedString(string: valuePercentageChangeValue, attributes: [ .foregroundColor: valuePercentageChangeColor, .font: Screen.TokenCard.Font.valueChangeLabel ]) } private var priceChangeUSDValue: String { if let result = EthCurrencyHelper(ticker: ticker).valueChanged24h(value: token.optionalDecimalValue) { return NumberFormatter.usd(format: .priceChangeFormat).string(from: result) ?? "-" } else { return "-" } } var priceChangeUSDValueAttributedString: NSAttributedString { return NSAttributedString(string: priceChangeUSDValue, attributes: [ .foregroundColor: valuePercentageChangeColor, .font: Screen.TokenCard.Font.valueChangeLabel ]) } private var amountAccordingRPCServer: String? { if token.server.isTestnet { return nil } else { return currencyAmount.flatMap { NumberFormatter.usd(format: .fiatFormat).string(from: $0) ?? "-" } } } var fiatValueAttributedString: NSAttributedString { return NSAttributedString(string: amountAccordingRPCServer ?? "-", attributes: [ .foregroundColor: Screen.TokenCard.Color.title, .font: Screen.TokenCard.Font.valueChangeValue ]) } var alpha: CGFloat { return isVisible ? 1.0 : 0.4 } var iconImage: Subscribable<TokenImage> { token.icon } var blockChainTagViewModel: BlockchainTagLabelViewModel { return .init(server: token.server) } private func amountAccordingRPCServer(currencyAmount: String?) -> String? { if token.server.isTestnet { return nil } else { return currencyAmount } } func fiatValueAttributedString(currencyAmount: String?) -> NSAttributedString { return NSAttributedString(string: amountAccordingRPCServer(currencyAmount: currencyAmount) ?? "-", attributes: [ .foregroundColor: Screen.TokenCard.Color.title, .font: Screen.TokenCard.Font.valueChangeValue ]) } private func priceChangeUSDValue(ticker: CoinTicker?) -> String { if let result = EthCurrencyHelper(ticker: ticker).valueChanged24h(value: token.optionalDecimalValue) { return NumberFormatter.usd.string(from: result) ?? "-" } else { return "-" } } func apprecation24hoursBackgroundColor(ticker: CoinTicker?) -> UIColor { valuePercentageChangeColor(ticker: ticker).withAlphaComponent(0.07) } var apprecationViewModel: ApprecationViewModel { .init(icon: apprecation24hoursImage, valueAttributedString: apprecation24hoursAttributedString, backgroundColor: apprecation24hoursBackgroundColor) } private func valuePercentageChangeColor(ticker: CoinTicker?) -> UIColor { return Screen.TokenCard.Color.valueChangeValue(ticker: ticker) } }
33.912791
155
0.664495
71c5d5a8fc9f9d9887eee4b5fecff818e46e3b2c
1,316
// // AppDelegate.swift // iOS Example // // Copyright © 2017 Andrew Simvolokov. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? }
38.705882
81
0.75304
fb052039332bb4c54676974f7ac9e5b02ad909fb
2,794
// // RightMenuVC.swift // FAPanels // // Created by Fahid Attique on 17/06/2017. // Copyright © 2017 Fahid Attique. All rights reserved. // import UIKit class RightMenuVC: UIViewController { @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. viewConfigurations() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ private func viewConfigurations() { tableView.register(UINib.init(nibName: "RightMenuCell", bundle: nil), forCellReuseIdentifier: "RightMenuCell") } } extension RightMenuVC: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 8 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "RightMenuCell") as! RightMenuCell cell.menuOption.image = UIImage(named: "right_menu_" + String(indexPath.row + 1)) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) var identifier = "" if indexPath.row % 2 == 0 { identifier = "CenterVC1" } else{ identifier = "CenterVC2" } let centerVC: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: identifier) let centerNavVC = UINavigationController(rootViewController: centerVC) panel!.configs.bounceOnCenterPanelChange = true /* // Simple way of changing center PanelVC _ = panel!.center(centerNavVC) */ /* New Feature Added, You can change the center panelVC and after completion of the animations you can execute a closure */ panel!.center(centerNavVC, afterThat: { print("Executing block after changing center panelVC From Right Menu") }) } }
29.104167
126
0.634932
e929ee24fcbc946e1a4e1dda2483e4f4cc29ce5d
3,403
// // VGSCardScanHandler.swift // VGSCardScanCollector // // Created by Dima on 18.08.2020. // Copyright © 2020 VGS. All rights reserved. // import Foundation import CardScan #if !COCOAPODS import VGSCollectSDK #endif internal class VGSCardScanHandler: NSObject, VGSScanHandlerProtocol { weak var delegate: VGSCardScanControllerDelegate? weak var view: UIViewController? required init(apiKey: String) { super.init() ScanViewController.configure(apiKey: apiKey) } func presentScanVC(on viewController: UIViewController, animated: Bool, completion: (() -> Void)?) { guard let vc = ScanViewController.createViewController(withDelegate: self) else { print("This device is incompatible with CardScan") return } self.view = vc vc.scanDelegate = self viewController.present(vc, animated: true) } func dismissScanVC(animated: Bool, completion: (() -> Void)?) { view?.dismiss(animated: animated, completion: completion) } static func isCompatible() -> Bool { return ScanViewController.isCompatible() } } /// :nodoc: extension VGSCardScanHandler: ScanDelegate { func userDidCancel(_ scanViewController: ScanViewController) { VGSAnalyticsClient.shared.trackEvent(.scan, status: .cancel, extraData: [ "scannerType": "Bouncer"]) delegate?.userDidCancelScan() } /// :nodoc: func userDidScanCard(_ scanViewController: ScanViewController, creditCard: CreditCard) { guard let cardScanDelegate = delegate else { return } if !creditCard.number.isEmpty, let textfield = cardScanDelegate.textFieldForScannedData(type: .cardNumber) { if let form = textfield.configuration?.vgsCollector { VGSAnalyticsClient.shared.trackFormEvent(form.formAnalyticsDetails, type: .scan, status: .success, extraData: [ "scannerType": "Bouncer"]) } textfield.setText(creditCard.number) } if let name = creditCard.name, !name.isEmpty, let textfield = cardScanDelegate.textFieldForScannedData(type: .name) { textfield.setText(name) } if let month = Int(creditCard.expiryMonth ?? ""), 1...12 ~= month, let year = Int(creditCard.expiryYear ?? ""), year >= VGSCalendarUtils.currentYearShort { if let textfield = cardScanDelegate.textFieldForScannedData(type: .expirationDate) { textfield.setText("\(month)\(year)") } if let textfield = cardScanDelegate.textFieldForScannedData(type: .expirationDateLong) { let longYear = "20\(year)" textfield.setText("\(month)\(longYear)") } } if let month = Int(creditCard.expiryMonth ?? ""), 1...12 ~= month, let textfield = cardScanDelegate.textFieldForScannedData(type: .expirationMonth) { textfield.setText("\(month)") } if let year = Int(creditCard.expiryYear ?? ""), year >= VGSCalendarUtils.currentYear { if let textfield = cardScanDelegate.textFieldForScannedData(type: .expirationYear) { textfield.setText("\(year)") } if let textfield = cardScanDelegate.textFieldForScannedData(type: .expirationYearLong) { let longYear = "20\(year)" textfield.setText("\(longYear)") } } cardScanDelegate.userDidFinishScan() } /// :nodoc: func userDidSkip(_ scanViewController: ScanViewController) { delegate?.userDidCancelScan() } }
35.082474
159
0.683808
3867b3000af4a9dec9df34140fc80e4a1e07cebd
971
// // KNNViewController+CollectionView.swift // MLDemos // // Created by developer on 4/9/19. // Copyright © 2019 iosdevlog. All rights reserved. // import UIKit extension KNNViewController: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imagesNamed.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KMeansCollectionViewCell.identifier, for: indexPath) as! KMeansCollectionViewCell cell.imageView.image = UIImage(named: imagesNamed[indexPath.row]) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { currentType = Geometry2DType(rawValue: indexPath.row)! } }
34.678571
156
0.741504
1830b7408ba9356bb0adc5991defc682753f8bdc
2,624
// // IntegrationCashRecordController.swift // ThinkSNS + // // Created by GorCat on 2018/1/24. // Copyright © 2018年 ZhiYiCX. All rights reserved. // // 提现明细 import UIKit class IntegrationCashRecordController: TSLabelViewController { // 充值记录 let rechargeTable = IntegrationRecordTable(frame: CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 64) ), tableIdentifier: "recharge") // 提取记录 let cashTable = IntegrationRecordTable(frame: CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 64) ), tableIdentifier: "cash") var selectedIndex: Int init(selectedIndex index: Int) { let height = UIScreen.main.bounds.height - 64 selectedIndex = index super.init(labelTitleArray: ["充值记录"], scrollViewFrame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: height)) blueLine.isHidden = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setUI() } func setUI() { rechargeTable.refreshDelegate = self cashTable.refreshDelegate = self add(childView: rechargeTable, at: 0) add(childView: cashTable, at: 1) rechargeTable.mj_header.beginRefreshing() cashTable.mj_header.beginRefreshing() setSelectedAt(selectedIndex) } } extension IntegrationCashRecordController: IntegrationRecordTableRefreshDelegate { /// 下拉刷新 func integrationRecordTable(_ view: IntegrationRecordTable, didRefreshWithIdentidier identifier: String) { IntegrationNetworkManager.getOrders(after: nil, action: identifier) { (models, message, status) in var cellModels: [IntegrationRecordCellModel]? if let datas = models { cellModels = datas.map { IntegrationRecordCellModel(model: $0) } } view.processRefresh(newDatas: cellModels, errorMessage: message) } } // 上拉加载更多 func integrationRecordTable(_ view: IntegrationRecordTable, didLoadMoreWithIdentidier identifier: String) { IntegrationNetworkManager.getOrders(after: view.datas.last?.id, action: identifier) { (models, message, status) in var cellModels: [IntegrationRecordCellModel]? if let datas = models { cellModels = datas.map { IntegrationRecordCellModel(model: $0) } } view.processLoadMore(newDatas: cellModels, errorMessage: message) } } }
34.986667
197
0.682165
900bd46eafda0ca6857a636121fae6b388390e73
3,550
import XCTest import ReactiveSwift import UIKit.UIActivity import ReactiveExtensions import ReactiveExtensions_TestHelpers import Result @testable import KsApi @testable import Library import Prelude final class ActivityFriendFollowCellViewModelTests: TestCase { let vm: ActivityFriendFollowCellViewModel = ActivityFriendFollowCellViewModel() let hideFollowButton = TestObserver<Bool, NoError>() let friendImageURL = TestObserver<String?, NoError>() let title = TestObserver<String, NoError>() override func setUp() { super.setUp() vm.outputs.hideFollowButton.observe(hideFollowButton.observer) vm.outputs.friendImageURL.map { $0?.absoluteString }.observe(friendImageURL.observer) vm.outputs.title.map { $0.string }.observe(title.observer) } func testFriendDetails_Complete() { let user = User.template |> \.avatar.small .~ "http://coolpic.com/cool.jpg" |> \.name .~ "Squiggles McTwiddle" let activity = Activity.template |> Activity.lens.user .~ user friendImageURL.assertValueCount(0) title.assertValueCount(0) vm.inputs.configureWith(activity: activity) friendImageURL.assertValues(["http://coolpic.com/cool.jpg"]) title.assertValues(["Squiggles McTwiddle is now following you!"]) } func testFriendDetails_Incomplete() { let user = User.template |> \.name .~ "Squiggles McTwiddle" let activity = Activity.template |> Activity.lens.user .~ user friendImageURL.assertValueCount(0) title.assertValueCount(0) vm.inputs.configureWith(activity: activity) friendImageURL.assertValueCount(1) title.assertValues(["Squiggles McTwiddle is now following you!"]) } func testFriendFollowing_Friend() { let user = User.template |> \.avatar.small .~ "http://coolpic.com/cool.jpg" |> \.isFriend .~ true |> \.name .~ "Squiggles McTwiddle" let activity = Activity.template |> Activity.lens.user .~ user hideFollowButton.assertValueCount(0) XCTAssertEqual([], self.trackingClient.events) vm.inputs.configureWith(activity: activity) hideFollowButton.assertValues([true], "Hide Follow Button") XCTAssertEqual([], self.trackingClient.events) } func testFriendFollowing_NonFriend() { let user = User.template |> \.avatar.medium .~ "http://coolpic.com/cool.jpg" |> \.isFriend .~ false |> \.name .~ "Squiggles McTwiddle" let activity = Activity.template |> Activity.lens.user .~ user hideFollowButton.assertValueCount(0) XCTAssertEqual([], self.trackingClient.events) vm.inputs.configureWith(activity: activity) hideFollowButton.assertValues([false], "Show Follow Button") vm.inputs.followButtonTapped() hideFollowButton.assertValues([false], "Follow Button does not change") XCTAssertEqual(["Facebook Friend Follow", "Followed Facebook Friend"], self.trackingClient.events) XCTAssertEqual(["activity", "activity"], self.trackingClient.properties(forKey: "source", as: String.self)) } func testRetainFriendStatusOnReuse_After_Following() { let user = User.template |> \.avatar.small .~ "http://coolpic.com/cool.jpg" |> \.isFriend .~ false |> \.name .~ "Squiggles McTwiddle" let activity = Activity.template |> Activity.lens.user .~ user hideFollowButton.assertValueCount(0) vm.inputs.configureWith(activity: activity) hideFollowButton.assertValues([false], "Show Follow Button") vm.inputs.followButtonTapped() scheduler.advance() } }
29.831933
102
0.709577
eb35cfec44bcaaec789fdb72f793a2399b6f8ce4
959
// // UIViewController+Extensions.swift // DiscourseClient // // Created by Roberto Garrido on 08/02/2020. // Copyright © 2020 Roberto Garrido. All rights reserved. // import UIKit extension UIViewController { /// Muestra un alertcontroller con una única acción /// - Parameters: /// - alertMessage: Mensaje del alert /// - alertTitle: Título del alert /// - alertActionTitle: Título de la acción func showAlert(_ alertMessage: String, alertTitle: String = NSLocalizedString("Error", comment: ""), _ alertActionTitle: String = NSLocalizedString("OK", comment: "")) { let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: alertActionTitle, style: .default, handler: nil)) present(alertController, animated: true, completion: nil) } }
36.884615
113
0.661105
8fdacc245ec4635fcbbcd18d70983ffc5579431e
307,460
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest @testable import TensorFlow fileprivate struct Sigmoid<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { typealias TangentVector = EmptyTangentVector @differentiable(reverse) func callAsFunction(_ input: Tensor<Scalar>) -> Tensor<Scalar> { sigmoid(input) } } final class LayerTests: XCTestCase { func testConv1D() { let filter = Tensor<Float>(ones: [3, 1, 2]) * Tensor<Float>([[[0.5, 1]]]) let bias = Tensor<Float>([0, 1]) let layer = Conv1D<Float>( filter: filter, bias: bias, activation: identity, stride: 1, padding: .valid) let input = Tensor<Float>([[0, 1, 2, 3, 4], [10, 11, 12, 13, 14]]).expandingShape(at: 2) let output = layer.inferring(from: input) let expected = Tensor<Float>( shape: [2, 3, 2], scalars: [1.5, 4, 3, 7, 4.5, 10, 16.5, 34, 18, 37, 19.5, 40]) XCTAssertEqual(output, expected) let layerNoBias = Conv1D<Float>( filter: filter, bias: nil, activation: identity, stride: 1, padding: .valid) let outputNoBias = layerNoBias.inferring(from: input) let expectedNoBias = Tensor<Float>( shape: [2, 3, 2], scalars: [1.5, 3, 3, 6, 4.5, 9, 16.5, 33, 18, 36, 19.5, 39]) XCTAssertEqual(outputNoBias, expectedNoBias) } func testConv1DDilation() { // Filter shapes. let width = 3 let inputChannels = 1 let outputChannels = 2 // Input shapes. let inputHeight = 2 let inputWidth = 5 let filter = Tensor<Float>( shape: [width, inputChannels, outputChannels], scalars: [2, 3, 4, 1, 2, 3]) let bias = Tensor<Float>([0]) let layer = Conv1D<Float>( filter: filter, bias: bias, activation: identity, stride: 1, padding: .valid, dilation: 2) let input = Tensor<Float>( shape: [inputHeight, inputWidth, 1], scalars: [0, 1, 2, 3, 4, 10, 11, 12, 13, 14]) let output = layer.inferring(from: input) let expected = Tensor<Float>(shape: [2, 1, 2], scalars: [16, 14, 96, 84]) XCTAssertEqual(output, expected) } func testConv2D() { let filter = Tensor(shape: [1, 2, 2, 1], scalars: (0..<4).map(Float.init)) let bias = Tensor<Float>([1, 2]) let layer = Conv2D<Float>( filter: filter, bias: bias, activation: identity, strides: (2, 2), padding: .valid) let input = Tensor(shape: [2, 2, 2, 2], scalars: (0..<16).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>( shape: [2, 1, 1, 2], scalars: [15, 16, 63, 64]) XCTAssertEqual(output, expected) let layerNoBias = Conv2D<Float>( filter: filter, bias: nil, activation: identity, strides: (2, 2), padding: .valid) let outputNoBias = layerNoBias.inferring(from: input) let expectedNoBias = Tensor<Float>( shape: [2, 1, 1, 1], scalars: [14, 62]) XCTAssertEqual(outputNoBias, expectedNoBias) } func testConv2DGradient() { let filter = Tensor(shape: [3, 3, 2, 4], scalars: (0..<72).map(Float.init)) let bias = Tensor<Float>(zeros: [4]) let layer = Conv2D<Float>( filter: filter, bias: bias, activation: identity, strides: (2, 2), padding: .valid) let input = Tensor(shape: [2, 4, 4, 2], scalars: (0..<64).map(Float.init)) let grads = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // x = tf.reshape(tf.range(64, dtype=tf.float32), [2, 4, 4, 2]) // filter = tf.reshape(tf.range(72, dtype=tf.float32), [3, 3, 2, 4]) // bias = tf.zeros([4]) // with tf.GradientTape() as tape: // tape.watch([x, filter, bias]) // y = tf.math.reduce_sum(tf.nn.conv2d(input=x, // filters=filter, // strides=[1, 2, 2, 1], // data_format="NHWC", // padding="VALID") + bias) // print(tape.gradient(y, [x, filter, bias])) // ``` XCTAssertEqual( grads.0, [ [ [[6, 22], [38, 54], [70, 86], [0, 0]], [[102, 118], [134, 150], [166, 182], [0, 0]], [[198, 214], [230, 246], [262, 278], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]], ], [ [[6, 22], [38, 54], [70, 86], [0, 0]], [[102, 118], [134, 150], [166, 182], [0, 0]], [[198, 214], [230, 246], [262, 278], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0]], ], ]) XCTAssertEqual( grads.1.filter, [ [ [[32, 32, 32, 32], [34, 34, 34, 34]], [[36, 36, 36, 36], [38, 38, 38, 38]], [[40, 40, 40, 40], [42, 42, 42, 42]], ], [ [[48, 48, 48, 48], [50, 50, 50, 50]], [[52, 52, 52, 52], [54, 54, 54, 54]], [[56, 56, 56, 56], [58, 58, 58, 58]], ], [ [[64, 64, 64, 64], [66, 66, 66, 66]], [[68, 68, 68, 68], [70, 70, 70, 70]], [[72, 72, 72, 72], [74, 74, 74, 74]], ], ]) XCTAssertEqual(grads.1.bias, [2, 2, 2, 2]) } func testConv2DDilation() { // Input shapes. (Data format = NHWC) let batchSize = 2 let inputHeight = 4 let inputWidth = 4 let inputChannels = 1 let inputSize = batchSize * inputHeight * inputWidth * inputChannels // Filter shapes. let filterHeight = 2 let filterWidth = 2 let outputChannels = 1 let filterSize = filterHeight * filterWidth * inputChannels * outputChannels // Testing. let filter = Tensor<Float>( shape: [filterHeight, filterWidth, inputChannels, outputChannels], scalars: (0..<filterSize).map(Float.init)) let bias = Tensor<Float>([0]) let layer = Conv2D<Float>( filter: filter, bias: bias, activation: identity, strides: (1, 1), padding: .valid, dilations: (2, 2)) let input = Tensor<Float>( shape: [batchSize, inputHeight, inputWidth, inputChannels], scalars: (0..<inputSize).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>( shape: [2, 2, 2, 1], scalars: [48, 54, 72, 78, 144, 150, 168, 174]) XCTAssertEqual(output, expected) } func testConv3D() { let filter = Tensor(shape: [1, 2, 2, 2, 1], scalars: (0..<8).map(Float.init)) let bias = Tensor<Float>([-1, 1]) let layer = Conv3D<Float>( filter: filter, bias: bias, activation: identity, strides: (1, 2, 1), padding: .valid, dilations: (1, 1, 1)) let input = Tensor(shape: [2, 2, 2, 2, 2], scalars: (0..<32).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>( shape: [2, 2, 1, 1, 2], scalars: [139, 141, 363, 365, 587, 589, 811, 813]) XCTAssertEqual(output, expected) let layerNoBias = Conv3D<Float>( filter: filter, bias: nil, activation: identity, strides: (1, 2, 1), padding: .valid, dilations: (1, 1, 1)) let outputNoBias = layerNoBias.inferring(from: input) let expectedNoBias = Tensor<Float>( shape: [2, 2, 1, 1, 1], scalars: [140, 364, 588, 812]) XCTAssertEqual(outputNoBias, expectedNoBias) } func testConv3DGradient() { let filter = Tensor(shape: [1, 4, 4, 1, 1], scalars: (0..<16).map(Float.init)) let bias = Tensor<Float>(ones: [2]) let layer = Conv3D( filter: filter, bias: bias, activation: identity, strides: (2, 2, 2), padding: .same) let input = Tensor(shape: [1, 4, 4, 4, 1], scalars: (0..<64).map(Float.init)) let grads = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // x = tf.reshape(tf.range(64, dtype=tf.float32), [1, 4, 4, 4, 1]) // filter = tf.reshape(tf.range(72, dtype=tf.float32), [1, 4, 4, 1, 1]) // bias = tf.ones([2]) // with tf.GradientTape() as tape: // tape.watch([x, filter, bias]) // y = tf.math.reduce_sum(tf.nn.conv3d(input=x, // filters=filter, // strides=[1, 2, 2, 2, 1], // padding="SAME") + bias) // print(tape.gradient(y, [x, filter, bias])) // ``` XCTAssertEqual( grads.0, [ [ [ [[10.0], [20.0], [24.0], [12.0]], [[20.0], [40.0], [48.0], [24.0]], [[36.0], [72.0], [80.0], [40.0]], [[18.0], [36.0], [40.0], [20.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.0], [0.0]], ], [ [[10.0], [20.0], [24.0], [12.0]], [[20.0], [40.0], [48.0], [24.0]], [[36.0], [72.0], [80.0], [40.0]], [[18.0], [36.0], [40.0], [20.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.0], [0.0]], ], ] ]) XCTAssertEqual( grads.1.filter, [ [ [[[84.0]], [[168.0]], [[176.0]], [[88.0]]], [[[168.0]], [[336.0]], [[352.0]], [[176.0]]], [[[200.0]], [[400.0]], [[416.0]], [[208.0]]], [[[100.0]], [[200.0]], [[208.0]], [[104.0]]], ] ]) XCTAssertEqual(grads.1.bias, [8.0, 8.0]) } func testDepthwiseConv2D() { let filter = Tensor(shape: [2, 2, 2, 2], scalars: (0..<16).map(Float.init)) let bias = Tensor<Float>([1, 2, 3, 4]) let layer = DepthwiseConv2D<Float>( filter: filter, bias: bias, activation: identity, strides: (2, 2), padding: .same) let input = Tensor(shape: [1, 1, 8, 2], scalars: (0..<16).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>( shape: [1, 1, 4, 4], scalars: [ 9, 12, 23, 28, 25, 36, 55, 68, 41, 60, 87, 108, 57, 84, 119, 148, ]) XCTAssertEqual(output, expected) let channelMultiplier = 4 let multiplierLayer = DepthwiseConv2D<Float>( filterShape: (2, 2, input.shape[3], channelMultiplier), filterInitializer: glorotUniform(), biasInitializer: zeros()) let multiplierOutput = multiplierLayer.inferring(from: input) XCTAssertEqual(multiplierOutput.shape[3], input.shape[3] * channelMultiplier) } func testDepthwiseConv2DGradient() { let filter = Tensor(shape: [2, 1, 2, 2], scalars: (0..<8).map(Float.init)) let bias = Tensor<Float>(ones: [4]) let layer = DepthwiseConv2D<Float>( filter: filter, bias: bias, activation: identity, strides: (1, 1), padding: .same) let input = Tensor(shape: [2, 1, 2, 2], scalars: (0..<8).map(Float.init)) let grads = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // input = tf.reshape(tf.range(8, dtype=tf.float32), [2, 1, 2, 2]) // filter = tf.reshape(tf.range(8, dtype=tf.float32), [2, 1, 2, 2]) // bias = tf.ones([4]) // with tf.GradientTape() as tape: // tape.watch([x, filter, bias]) // y = tf.math.reduce_sum(tf.nn.depthwise_conv2d(input=x, // filters=filter, // strides=[1, 1, 1, 1], // data_format="NHWC", // padding="SAME") + bias) // print(tape.gradient(y, [x, filter, bias])) // ``` XCTAssertEqual( grads.0, [ [[[1, 5], [1, 5]]], [[[1, 5], [1, 5]]], ]) XCTAssertEqual( grads.1.filter, [ [[[12, 12], [16, 16]]], [[[0, 0], [0, 0]]], ]) XCTAssertEqual(grads.1.bias, [4, 4, 4, 4]) } func testTransposedConv1D() { let filter = Tensor(shape: [4, 1, 1], scalars: (0..<4).map(Float.init)) let bias = Tensor<Float>([8]) let layer = TransposedConv1D( filter: filter, bias: bias, activation: identity, stride: 1, padding: .same) let input = Tensor(shape: [1, 4, 1], scalars: (0..<4).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>( shape: [1, 1, 4, 1], scalars: [8, 9, 12, 18]) XCTAssertEqual(output, expected) let layerNoBias = TransposedConv1D( filter: filter, bias: nil, activation: identity, stride: 1, padding: .same) let outputNoBias = layerNoBias.inferring(from: input) let expectedNoBias = Tensor<Float>( shape: [1, 1, 4, 1], scalars: [0, 1, 4, 10]) XCTAssertEqual(outputNoBias, expectedNoBias) } func testTransposedConv2D() { let filter = Tensor(shape: [4, 2, 1, 1], scalars: (0..<8).map(Float.init)) let bias = Tensor<Float>([8]) let layer = TransposedConv2D( filter: filter, bias: bias, activation: identity, strides: (1, 1), padding: .same) let input = Tensor(shape: [1, 4, 2, 1], scalars: (0..<8).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>( shape: [1, 4, 2, 1], scalars: [8, 12, 12, 28, 24, 64, 48, 112]) XCTAssertEqual(output, expected) let layerNoBias = TransposedConv2D( filter: filter, bias: nil, activation: identity, strides: (1, 1), padding: .same) let outputNoBias = layerNoBias.inferring(from: input) let expectedNoBias = Tensor<Float>( shape: [1, 4, 2, 1], scalars: [0, 4, 4, 20, 16, 56, 40, 104]) XCTAssertEqual(outputNoBias, expectedNoBias) } func testTransposedConv2DGradient() { let filter = Tensor(shape: [3, 3, 2, 4], scalars: (0..<72).map(Float.init)) let bias = Tensor<Float>(zeros: [2]) let layer = TransposedConv2D<Float>( filter: filter, bias: bias, activation: identity, strides: (2, 2), padding: .same) let input = Tensor(shape: [2, 2, 2, 4], scalars: (0..<32).map(Float.init)) let grads = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // x = tf.reshape(tf.range(32, dtype=tf.float32), [2, 2, 2, 4]) // filter = tf.reshape(tf.range(72, dtype=tf.float32), [3, 3, 2, 4]) // bias = tf.zeros([2]) // with tf.GradientTape() as tape: // tape.watch([x, filter, bias]) // y = tf.math.reduce_sum(tf.nn.conv2d_transpose(input=x, // filters=filter, // output_shape=[2, 4, 4, 2], // strides=[1, 2, 2, 1], // data_format="NHWC", // padding="SAME") + bias) // print(tape.gradient(y, [x, filter, bias])) // ``` XCTAssertEqual( grads.0, [ [ [[612, 630, 648, 666], [360, 372, 384, 396]], [[264, 276, 288, 300], [144, 152, 160, 168]], ], [ [[612, 630, 648, 666], [360, 372, 384, 396]], [[264, 276, 288, 300], [144, 152, 160, 168]], ], ]) XCTAssertEqual( grads.1.filter, [ [ [[112, 120, 128, 136], [112, 120, 128, 136]], [[112, 120, 128, 136], [112, 120, 128, 136]], [[48, 52, 56, 60], [48, 52, 56, 60]], ], [ [[112, 120, 128, 136], [112, 120, 128, 136]], [[112, 120, 128, 136], [112, 120, 128, 136]], [[48, 52, 56, 60], [48, 52, 56, 60]], ], [ [[40, 44, 48, 52], [40, 44, 48, 52]], [[40, 44, 48, 52], [40, 44, 48, 52]], [[16, 18, 20, 22], [16, 18, 20, 22]], ], ]) XCTAssertEqual(grads.1.bias, [32, 32]) } func testTransposedConv3D() { let filter = Tensor(shape: [2, 2, 2, 1, 1], scalars: (0..<8).map(Float.init)) let bias = Tensor<Float>([8]) let layer = TransposedConv3D( filter: filter, bias: bias, activation: identity, strides: (1, 1, 1), padding: .same) let input = Tensor(shape: [1, 2, 2, 2, 1], scalars: (0..<8).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>( shape: [1, 2, 2, 2, 1], scalars: [8, 8, 8, 12, 8, 16, 24, 64]) XCTAssertEqual(output, expected) let layerNoBias = TransposedConv3D( filter: filter, bias: nil, activation: identity, strides: (1, 1, 1), padding: .same) let outputNoBias = layerNoBias.inferring(from: input) let expectedNoBias = Tensor<Float>( shape: [1, 2, 2, 2, 1], scalars: [0, 0, 0, 4, 0, 8, 16, 56]) XCTAssertEqual(outputNoBias, expectedNoBias) } func testSeparableConv1D() { let depthwiseFilter = Tensor(shape: [2, 2, 2], scalars: (0..<8).map(Float.init)) let pointwiseFilter = Tensor(shape: [1, 4, 1], scalars: (0..<4).map(Float.init)) let bias = Tensor<Float>([4]) let layer = SeparableConv1D<Float>( depthwiseFilter: depthwiseFilter, pointwiseFilter: pointwiseFilter, bias: bias, activation: identity, stride: 1, padding: .same) let input = Tensor(shape: [2, 2, 2], scalars: (0..<8).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>(shape: [2, 2, 1], scalars: [17, 45, 73, 101]) XCTAssertEqual(output, expected) let layerNoBias = SeparableConv1D<Float>( depthwiseFilter: depthwiseFilter, pointwiseFilter: pointwiseFilter, bias: nil, activation: identity, stride: 1, padding: .same) let outputNoBias = layerNoBias.inferring(from: input) let expectedNoBias = Tensor<Float>(shape: [2, 2, 1], scalars: [13, 41, 69, 97]) XCTAssertEqual(outputNoBias, expectedNoBias) } func testSeparableConv2D() { let depthwiseFilter = Tensor(shape: [2, 2, 2, 2], scalars: (0..<16).map(Float.init)) let pointwiseFilter = Tensor(shape: [1, 1, 4, 1], scalars: (0..<4).map(Float.init)) let bias = Tensor<Float>([4]) let layer = SeparableConv2D<Float>( depthwiseFilter: depthwiseFilter, pointwiseFilter: pointwiseFilter, bias: bias, activation: identity, strides: (2, 2), padding: .valid) let input = Tensor(shape: [2, 2, 2, 2], scalars: (0..<16).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>( shape: [2, 1, 1, 1], scalars: [1016, 2616]) XCTAssertEqual(output, expected) let layerNoBias = SeparableConv2D<Float>( depthwiseFilter: depthwiseFilter, pointwiseFilter: pointwiseFilter, bias: nil, activation: identity, strides: (2, 2), padding: .valid) let outputNoBias = layerNoBias.inferring(from: input) let expectedNoBias = Tensor<Float>( shape: [2, 1, 1, 1], scalars: [1012, 2612]) XCTAssertEqual(outputNoBias, expectedNoBias) } func testSeparableConv2DGradient() { let depthwiseFilter = Tensor(shape: [2, 1, 2, 2], scalars: (0..<8).map(Float.init)) let pointwiseFilter = Tensor(shape: [1, 1, 4, 1], scalars: (0..<4).map(Float.init)) let bias = Tensor<Float>([1, 1]) let layer = SeparableConv2D<Float>( depthwiseFilter: depthwiseFilter, pointwiseFilter: pointwiseFilter, bias: bias, activation: identity, strides: (1, 1), padding: .same) let input = Tensor(shape: [2, 1, 2, 2], scalars: (0..<8).map(Float.init)) let grads = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // x = tf.reshape(tf.range(8, dtype=tf.float32), [2, 1, 2, 2]) // depthwiseFilter = tf.reshape(tf.range(8, dtype=tf.float32), [2, 1, 2, 2]) // pointwiseFilter = tf.reshape(tf.range(4, dtype=tf.float32), [1, 1, 4, 1]) // bias = tf.ones([2]) // with tf.GradientTape() as tape: // tape.watch([x, depthwiseFilter, pointwiseFilter, bias]) // y = tf.math.reduce_sum(tf.nn.separable_conv2D(input, // depthwiseFilter, // pointwiseFilter // strides=[1, 1, 1, 1], // padding="SAME") + bias) // print(tape.gradient(y, [x, depthwiseFilter, pointwiseFilter, bias]) // ``` XCTAssertEqual( grads.0, [ [[[2.0, 26.0], [2.0, 26.0]]], [[[2.0, 26.0], [2.0, 26.0]]], ]) XCTAssertEqual( grads.1.depthwiseFilter, [ [[[0.0, 24.0], [64.0, 96.0]]], [[[0.0, 0.0], [0.0, 0.0]]], ]) XCTAssertEqual(grads.1.bias, [4.0, 4.0]) } func testZeroPadding1D() { let input = Tensor<Float>(shape: [1, 3, 1], scalars: [0.0, 1.0, 2.0]) let layer = ZeroPadding1D<Float>(padding: 2) let output = layer.inferring(from: input) let expected = Tensor<Float>( shape: [1, 7, 1], scalars: [0.0, 0.0, 0.0, 1.0, 2.0, 0.0, 0.0]) XCTAssertEqual(output, expected) } func testZeroPadding1DGradient() { let x = Tensor<Float>(shape: [1, 3, 1], scalars: [0.0, 1.0, 2.0]) let layer = ZeroPadding1D<Float>(padding: 2) let computedGradient = gradient(at: x, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // x = tf.reshape(tf.constant([0.0, 1.0, 2.0]), [1, 3, 1]) // layer = tf.keras.layers.ZeroPadding1D(2) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.reduce_sum(layer(x)) // print(tape.gradient(y, x)) // ``` let expectedGradient = Tensor<Float>(onesLike: x) XCTAssertEqual(computedGradient.0, expectedGradient) } func testZeroPadding2D() { let input = Tensor<Float>(shape: [1, 3, 1, 1], scalars: [0.0, 1.0, 2.0]) let layer = ZeroPadding2D<Float>(padding: ((0, 0), (0, 1))) let output = layer.inferring(from: input) let expected = Tensor<Float>( shape: [1, 3, 2, 1], scalars: [0.0, 0.0, 1.0, 0.0, 2.0, 0.0]) XCTAssertEqual(output, expected) } func testZeroPadding2DGradient() { let x = Tensor<Float>(shape: [1, 3, 1, 1], scalars: [0.0, 1.0, 2.0]) let layer = ZeroPadding2D<Float>(padding: ((0, 0), (0, 1))) let computedGradient = gradient(at: x, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // x = tf.reshape(tf.constant([0.0, 1.0, 2.0]), [1, 3, 1, 1]) // layer = tf.keras.layers.ZeroPadding2D(((0, 0), (0, 1))) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.reduce_sum(layer(x)) // print(tape.gradient(y, x)) // ``` let expectedGradient = Tensor<Float>(onesLike: x) XCTAssertEqual(computedGradient.0, expectedGradient) } func testZeroPadding3D() { let input = Tensor<Float>(shape: [1, 3, 1, 1, 1], scalars: [0.0, 1.0, 2.0]) let layer = ZeroPadding3D<Float>(padding: ((0, 0), (0, 1), (0, 0))) let output = layer.inferring(from: input) let expected = Tensor<Float>(shape: [1, 3, 2, 1, 1], scalars: [0, 0, 1, 0, 2, 0]) XCTAssertEqual(output, expected) } func testZeroPadding3DGradient() { let x = Tensor<Float>(shape: [1, 3, 1, 1, 1], scalars: [0.0, 1.0, 2.0]) let layer = ZeroPadding3D<Float>(padding: ((0, 0), (0, 1), (0, 0))) let computedGradient = gradient(at: x, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // x = tf.reshape(tf.constant([0.0, 1.0, 2.0]), [1, 3, 1, 1, 1]) // layer = tf.keras.layers.ZeroPadding3D(((0, 0), (0, 1), (0, 0))) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.reduce_sum(layer(x)) // print(tape.gradient(y, x)) // ``` let expectedGradient = Tensor<Float>(onesLike: x) XCTAssertEqual(computedGradient.0, expectedGradient) } func testMaxPool1D() { let layer = MaxPool1D<Float>(poolSize: 3, stride: 1, padding: .valid) let input = Tensor<Float>([[0, 1, 2, 3, 4], [10, 11, 12, 13, 14]]).expandingShape(at: 2) let output = layer.inferring(from: input) let expected = Tensor<Float>([[[2], [3], [4]], [[12], [13], [14]]]) XCTAssertEqual(output, expected) } func testMaxPool1DGradient() { let layer = MaxPool1D<Float>(poolSize: 2, stride: 1, padding: .valid) let x = Tensor<Float>(shape: [1, 4, 4], scalars: (0..<16).map(Float.init)) let computedGradient = gradient(at: x, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // maxpool1D = tf.keras.layers.MaxPool1D() // x = tf.reshape(tf.range(16, dtype=tf.float32), [1, 4, 4]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(maxpool1D(x)) // print(tape.gradient(y, x)) // ``` let expectedGradient = Tensor<Float>([ [ [0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], ] ]) XCTAssertEqual(computedGradient.0, expectedGradient) } func testMaxPool2D() { let layer = MaxPool2D<Float>(poolSize: (2, 2), strides: (1, 1), padding: .valid) let input = Tensor(shape: [1, 2, 2, 1], scalars: (0..<4).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>([[[[3]]]]) XCTAssertEqual(output, expected) } func testMaxPool2DGradient() { let layer = MaxPool2D<Float>(poolSize: (2, 2), strides: (2, 2), padding: .valid) let x = Tensor(shape: [1, 4, 4, 1], scalars: (0..<16).map(Float.init)) let computedGradient = gradient(at: x, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // maxpool2D = tf.keras.layers.MaxPool2D(strides=(2, 2)) // x = tf.reshape(tf.range(16, dtype=tf.float32), [1, 4, 4, 1]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(maxpool2D(x)) // print(tape.gradient(y, x)) // ``` let expectedGradient = Tensor<Float>([ [ [[0], [0], [0], [0]], [[0], [1], [0], [1]], [[0], [0], [0], [0]], [[0], [1], [0], [1]], ] ]) XCTAssertEqual(computedGradient.0, expectedGradient) } func testMaxPool3D() { let layer = MaxPool3D<Float>(poolSize: (2, 2, 2), strides: (1, 1, 1), padding: .valid) let input = Tensor(shape: [1, 2, 2, 2, 1], scalars: (0..<8).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>([[[[[7]]]]]) XCTAssertEqual(output, expected) } func testMaxPool3DGradient() { let layer = MaxPool3D<Float>(poolSize: (2, 2, 2), strides: (1, 1, 1), padding: .valid) let x = Tensor(shape: [1, 2, 2, 2, 1], scalars: (0..<8).map(Float.init)) let computedGradient = gradient(at: x, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // maxpool3D = tf.keras.layers.MaxPool3D(strides=(1, 1, 1)) // x = tf.reshape(tf.range(8, dtype=tf.float32), [1, 2, 2, 2, 1]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(maxpool3D(x)) // print(tape.gradient(y, x)) // ``` let expectedGradient = Tensor<Float>([ [ [ [[0], [0]], [[0], [0]], ], [ [[0], [0]], [[0], [1]], ], ] ]) XCTAssertEqual(computedGradient.0, expectedGradient) } func testAvgPool1D() { let layer = AvgPool1D<Float>(poolSize: 3, stride: 1, padding: .valid) let input = Tensor<Float>([[0, 1, 2, 3, 4], [10, 11, 12, 13, 14]]).expandingShape(at: 2) let output = layer.inferring(from: input) let expected = Tensor<Float>([[[1], [2], [3]], [[11], [12], [13]]]) XCTAssertEqual(output, expected) } func testAvgPool1DGradient() { let layer = AvgPool1D<Float>(poolSize: 2, stride: 1, padding: .valid) let x = Tensor(shape: [1, 4, 4], scalars: (0..<16).map(Float.init)) let computedGradient = gradient(at: x, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // avgpool1D = tf.keras.layers.AvgPool1D(strides=1) // x = tf.reshape(tf.range(16, dtype=tf.float32), [1, 4, 4]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(avgpool1D(x)) // print(tape.gradient(y, x)) // ``` let expectedGradient = Tensor<Float>([ [ [0.5, 0.5, 0.5, 0.5], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.5, 0.5, 0.5, 0.5], ] ]) XCTAssertEqual(computedGradient.0, expectedGradient) } func testAvgPool2D() { let layer = AvgPool2D<Float>(poolSize: (2, 5), strides: (1, 1), padding: .valid) let input = Tensor(shape: [1, 2, 5, 1], scalars: (0..<10).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>([[[[4.5]]]]) XCTAssertEqual(output, expected) } func testAvgPool2DGradient() { let layer = AvgPool2D<Float>(poolSize: (2, 2), strides: (1, 1), padding: .valid) let x = Tensor(shape: [1, 4, 4, 2], scalars: (0..<32).map(Float.init)) let computedGradient = gradient(at: x, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // avgpool2D = tf.keras.layers.AvgPool2D(strides=(1, 1)) // x = tf.reshape(tf.range(32, dtype=tf.float32), [1, 4, 4, 2]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(avgpool2D(x)) // print(tape.gradient(y, x)) // ``` let expectedGradient = Tensor<Float>([ [ [[0.25, 0.25], [0.50, 0.50], [0.50, 0.50], [0.25, 0.25]], [[0.50, 0.50], [1.00, 1.00], [1.00, 1.00], [0.50, 0.50]], [[0.50, 0.50], [1.00, 1.00], [1.00, 1.00], [0.50, 0.50]], [[0.25, 0.25], [0.50, 0.50], [0.50, 0.50], [0.25, 0.25]], ] ]) XCTAssertEqual(computedGradient.0, expectedGradient) } func testAvgPool3D() { let layer = AvgPool3D<Float>(poolSize: (2, 4, 5), strides: (1, 1, 1), padding: .valid) let input = Tensor(shape: [1, 2, 4, 5, 1], scalars: (0..<40).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>([[[[[19.5]]]]]) XCTAssertEqual(output, expected) } func testAvgPool3DGradient() { let layer = AvgPool3D<Float>(poolSize: (2, 2, 2), strides: (1, 1, 1), padding: .valid) let x = Tensor(shape: [1, 2, 2, 2, 1], scalars: (0..<8).map(Float.init)) let computedGradient = gradient(at: x, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // avgpool3D = tf.keras.layers.AvgPool3D(strides=(1, 1, 1)) // x = tf.reshape(tf.range(8, dtype=tf.float32), [1, 2, 2, 2, 1]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(avgpool3D(x)) // print(tape.gradient(y, x)) // ``` let expectedGradient = Tensor<Float>(repeating: 0.125, shape: [1, 2, 2, 2, 1]) XCTAssertEqual(computedGradient.0, expectedGradient) } func testGlobalAvgPool1D() { let layer = GlobalAvgPool1D<Float>() let input = Tensor(shape: [2, 5, 1], scalars: (0..<10).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>([[2], [7]]) XCTAssertEqual(output, expected) } func testGlobalAvgPool1DGradient() { let layer = GlobalAvgPool1D<Float>() let input = Tensor(shape: [2, 2, 2], scalars: (0..<8).map(Float.init)) let computedGradient = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // globalAvgPool1D = tf.keras.layers.GlobalAveragePooling1D() // x = tf.reshape(tf.range(8, dtype=tf.float32), [2, 2, 2]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(globalAvgPool1D(x)) // print(tape.gradient(y, x)) // ``` XCTAssertEqual( computedGradient.0, [ [ [0.5, 0.5], [0.5, 0.5], ], [ [0.5, 0.5], [0.5, 0.5], ], ]) } func testGlobalAvgPool2D() { let layer = GlobalAvgPool2D<Float>() let input = Tensor(shape: [2, 6, 2, 1], scalars: (0..<24).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>([[5.5], [17.5]]) XCTAssertEqual(output, expected) } func testGlobalAvgPool2DGradient() { let layer = GlobalAvgPool2D<Float>() let input = Tensor(shape: [2, 2, 2, 2], scalars: (0..<16).map(Float.init)) let computedGradient = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // globalAvgPool2D = tf.keras.layers.GlobalAveragePooling2D() // x = tf.reshape(tf.range(16, dtype=tf.float32), [2, 2, 2, 2]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(globalAvgPool2D(x)) // print(tape.gradient(y, x)) // ``` XCTAssertEqual( computedGradient.0, [ [ [[0.25, 0.25], [0.25, 0.25]], [[0.25, 0.25], [0.25, 0.25]], ], [ [[0.25, 0.25], [0.25, 0.25]], [[0.25, 0.25], [0.25, 0.25]], ], ]) } func testGlobalAvgPool3D() { let layer = GlobalAvgPool3D<Float>() let input = Tensor<Float>(shape: [2, 6, 2, 1, 1], scalars: (0..<24).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>([[5.5], [17.5]]) XCTAssertEqual(output, expected) } func testGlobalAvgPool3DGradient() { let layer = GlobalAvgPool3D<Float>() let input = Tensor(shape: [1, 3, 2, 3, 1], scalars: (0..<18).map(Float.init)) let computedGradient = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // globalAvgPool3D = tf.keras.layers.GlobalAveragePooling3D() // x = tf.reshape(tf.range(18, dtype=tf.float32), [1, 3, 2, 2, 1]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(globalAvgPool3D(x)) // print(tape.gradient(y, x)) // ``` XCTAssertEqual( computedGradient.0, [ [ [ [[0.055555556], [0.055555556], [0.055555556]], [[0.055555556], [0.055555556], [0.055555556]], ], [ [[0.055555556], [0.055555556], [0.055555556]], [[0.055555556], [0.055555556], [0.055555556]], ], [ [[0.055555556], [0.055555556], [0.055555556]], [[0.055555556], [0.055555556], [0.055555556]], ], ] ]) } func testGlobalMaxPool1D() { let layer = GlobalMaxPool1D<Float>() let input = Tensor(shape: [1, 10, 1], scalars: (0..<10).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>([[9]]) XCTAssertEqual(output, expected) } func testGlobalMaxPool1DGradient() { let layer = GlobalMaxPool1D<Float>() let input = Tensor(shape: [2, 2, 2], scalars: (0..<8).map(Float.init)) let computedGradient = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // globalMaxPool1D = tf.keras.layers.GlobalMaxPooling1D() // x = tf.reshape(tf.range(8, dtype=tf.float32), [2, 2, 2]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(globalMaxPool1D(x)) // print(tape.gradient(y, x)) // ``` XCTAssertEqual( computedGradient.0, [ [ [0.0, 0.0], [1.0, 1.0], ], [ [0.0, 0.0], [1.0, 1.0], ], ]) } func testGlobalMaxPool2D() { let layer = GlobalMaxPool2D<Float>() let input = Tensor(shape: [1, 2, 10, 1], scalars: (0..<20).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>([[19]]) XCTAssertEqual(output, expected) } func testGlobalMaxPool2DGradient() { let layer = GlobalMaxPool2D<Float>() let input = Tensor(shape: [2, 3, 3, 2], scalars: (0..<36).map(Float.init)) let computedGradient = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` //import tensorflow as tf // globalMaxPool2D = tf.keras.layers.GlobalMaxPooling2D() // x = tf.reshape(tf.range(36, dtype=tf.float32), [2, 3, 3, 2]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(globalMaxPool2D(x)) // print(tape.gradient(y, x)) // ``` XCTAssertEqual( computedGradient.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.0, 0.0], [1.0, 1.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.0, 0.0], [1.0, 1.0]], ], ]) } func testGlobalMaxPool3D() { let layer = GlobalMaxPool3D<Float>() let input = Tensor<Float>(shape: [1, 2, 3, 5, 1], scalars: (0..<30).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>([[29]]) XCTAssertEqual(output, expected) } func testGlobalMaxPool3DGradient() { let layer = GlobalMaxPool3D<Float>() let input = Tensor(shape: [2, 2, 2, 2, 2], scalars: (0..<32).map(Float.init)) let computedGradient = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // globalMaxPool3D = tf.keras.layers.GlobalMaxPooling3D() // x = tf.reshape(tf.range(32, dtype=tf.float32), [2, 2, 2, 2, 2]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(globalMaxPool3D(x)) // print(tape.gradient(y, x)) // ``` XCTAssertEqual( computedGradient.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.0, 1.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.0, 1.0]], ], ], ]) } func testFractionalMaxPool2D() { let layer = FractionalMaxPool2D<Float>(poolingRatio: (1.4, 1.5), pseudoRandom: false) let input = Tensor(shape: [1, 2, 2, 1], scalars: (0..<4).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>([[[[3]]]]) XCTAssertEqual(output, expected) } func testFractionalMaxPool2DGradient() { let layer = FractionalMaxPool2D<Float>(poolingRatio: (1.4, 1.5), pseudoRandom: false) let x = Tensor(shape: [1, 2, 2, 1], scalars: (0..<4).map(Float.init)) let computedGradient = gradient(at: x, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // x = tf.reshape(tf.range(4, dtype=tf.float32), [1, 2, 2, 1]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(tf.nn.fractional_max_pool(x, pooling_ratio=[1, 1.4, 1.5, 1], pseudo_random=False)[0]) // print(tape.gradient(y, x)) // ``` let expectedGradient = Tensor<Float>([ [ [ [0.0], [0.0], ], [ [0.0], [1.0], ], ] ]) XCTAssertEqual(computedGradient.0, expectedGradient) } func testUpSampling1D() { let size = 6 let layer = UpSampling1D<Float>(size: size) let input = Tensor<Float>(shape: [1, 10, 1], scalars: (0..<10).map(Float.init)) let output = layer.inferring(from: input) let expected = TensorShape([1, input.shape[1] * size, 1]) XCTAssertEqual(output.shape, expected) } func testUpSampling1DGradient() { let layer = UpSampling1D<Float>(size: 3) let input = Tensor(shape: [2, 2, 2], scalars: (0..<8).map(Float.init)) let computedGradient = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // upSampling1D = tf.keras.layers.UpSampling1D(size = 3) // x = tf.reshape(tf.range(8, dtype=tf.float32), [2, 2, 2]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(upSampling1D(x)) // print(tape.gradient(y, x)) // ``` XCTAssertEqual( computedGradient.0, [ [ [3.0, 3.0], [3.0, 3.0], ], [ [3.0, 3.0], [3.0, 3.0], ], ]) } func testUpSampling2D() { let size = 6 let layer = UpSampling2D<Float>(size: size) let input = Tensor<Float>(shape: [1, 3, 5, 1], scalars: (0..<15).map(Float.init)) let output = layer.inferring(from: input) let expected = TensorShape([1, input.shape[1] * size, input.shape[2] * size, 1]) XCTAssertEqual(output.shape, expected) } func testUpSampling2DGradient() { let layer = UpSampling2D<Float>(size: 3) let input = Tensor(shape: [1, 3, 4, 2], scalars: (0..<24).map(Float.init)) let computedGradient = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // upSampling2D = tf.keras.layers.UpSampling2D(size = 3) // x = tf.reshape(tf.range(24, dtype=tf.float32), [1, 3, 4, 2]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(upSampling2D(x)) // print(tape.gradient(y, x)) // ``` XCTAssertEqual( computedGradient.0, [ [ [[9.0, 9.0], [9.0, 9.0], [9.0, 9.0], [9.0, 9.0]], [[9.0, 9.0], [9.0, 9.0], [9.0, 9.0], [9.0, 9.0]], [[9.0, 9.0], [9.0, 9.0], [9.0, 9.0], [9.0, 9.0]], ] ]) } func testUpSampling3D() { let size = 6 let layer = UpSampling3D<Float>(size: size) let input = Tensor<Float>(shape: [1, 4, 3, 2, 1], scalars: (0..<24).map(Float.init)) let output = layer.inferring(from: input) let expected = TensorShape( [1, input.shape[1] * size, input.shape[2] * size, input.shape[3] * size, 1]) XCTAssertEqual(output.shape, expected) XCTAssertEqual(output.shape, expected) } func testUpSampling3DGradient() { let layer = UpSampling3D<Float>(size: 3) let input = Tensor(shape: [1, 2, 2, 2, 4], scalars: (0..<32).map(Float.init)) let computedGradient = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // upSampling3D = tf.keras.layers.UpSampling3D(size = 3) // x = tf.reshape(tf.range(32, dtype=tf.float32), [1, 2, 2, 2, 4]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(upSampling3D(x)) // print(tape.gradient(y, x)) // ``` XCTAssertEqual( computedGradient.0, [ [ [ [[27.0, 27.0, 27.0, 27.0], [27.0, 27.0, 27.0, 27.0]], [[27.0, 27.0, 27.0, 27.0], [27.0, 27.0, 27.0, 27.0]], ], [ [[27.0, 27.0, 27.0, 27.0], [27.0, 27.0, 27.0, 27.0]], [[27.0, 27.0, 27.0, 27.0], [27.0, 27.0, 27.0, 27.0]], ], ] ]) } func testReshape() { let layer = Reshape<Float>(shape: [10, 2, 1]) let input = Tensor(shape: [20, 1], scalars: (0..<20).map(Float.init)) let output = layer.inferring(from: input) let expected = TensorShape([10, 2, 1]) XCTAssertEqual(output.shape, expected) } func testReshapeGradient() { let layer = Reshape<Float>(shape: [10, 2, 1]) let input = Tensor(shape: [1, 5, 4], scalars: (0..<20).map(Float.init)) let computedGradient = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // reshape = tf.keras.layers.Reshape(target_shape = (10, 2, 1)) // x = tf.reshape(tf.range(20, dtype=tf.float32), [1, 5, 4]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(reshape(x)) // print(tape.gradient(y, x)) // ``` XCTAssertEqual( computedGradient.0, [ [ [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], ] ]) } func testFlatten() { let layer = Flatten<Float>() let input = Tensor(shape: [10, 2, 2], scalars: (0..<40).map(Float.init)) let output = layer.inferring(from: input) let expected = TensorShape([10, 4]) XCTAssertEqual(output.shape, expected) } func testFlattenGradient() { let layer = Flatten<Float>() let input = Tensor(shape: [1, 4, 4], scalars: (0..<16).map(Float.init)) let computedGradient = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // flatten = tf.keras.layers.Flatten() // x = tf.reshape(tf.range(16, dtype=tf.float32), [1, 4, 4]) // with tf.GradientTape() as tape: // tape.watch(x) // y = tf.math.reduce_sum(flatten(x)) // print(tape.gradient(y, x)) // ``` XCTAssertEqual( computedGradient.0, [ [ [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], ] ]) } func testEmbedding() { var layer = Embedding<Float>(vocabularySize: 3, embeddingSize: 5) var input = Tensor<Int32>(shape: [2, 3], scalars: [0, 1, 2, 1, 2, 2]) var output = layer(input) let expectedShape = TensorShape([2, 3, 5]) XCTAssertEqual(output.shape, expectedShape) let pretrained = Tensor<Float>(shape: [2, 2], scalars: [0.4, 0.3, 0.2, 0.1]) layer = Embedding<Float>(embeddings: pretrained) input = Tensor<Int32>(shape: [2, 2], scalars: [0, 1, 1, 1]) output = layer(input) let expected = Tensor<Float>([[[0.4, 0.3], [0.2, 0.1]], [[0.2, 0.1], [0.2, 0.1]]]) XCTAssertEqual(output, expected) } func testEmbeddingGradient() { let embeddings = Tensor<Float>([ [0.0, 0.2, 0.1], [0.1, 0.7, 0.5], [0.2, 0.4, 0.6], [0.3, 0.2, 0.3], ]) let layer = Embedding<Float>(embeddings: embeddings) let indices = Tensor<Int32>(shape: [2, 3], scalars: [0, 1, 2, 1, 2, 2]) let grad = gradient(at: layer) { $0(indices).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // import tensorflow as tf // indices = tf.constant([0, 1, 2, 1, 2, 2], dtype=tf.int32) // embeddings = tf.constant([ // [0.0, 0.2, 0.1], // [0.1, 0.7, 0.5], // [0.2, 0.4, 0.6], // [0.3, 0.2, 0.3]]) // layer = tf.keras.layers.Embedding(4, 3, weights=[embeddings]) // with tf.GradientTape() as tape: // tape.watch(layer.weights) // y = tf.reduce_sum(layer(indices)) // grad_slice = tape.gradient(y, layer.weights)[0] # IndexedSlice // grad = tf.zeros_like(embeddings).numpy() // for index in grad_slice.indices: // grad[index] += grad_slice.values[index].numpy() // print(grad) // ``` let expected = Tensor<Float>([ [1, 1, 1], [2, 2, 2], [3, 3, 3], [0, 0, 0], ]) XCTAssertEqual(grad.embeddings, expected) } func testBasicRNNCell() { #if !SR15884_WORKAROUND_1 let weight = Tensor<Float>(ones: [7, 5]) * Tensor<Float>([0.3333, 1, 0.3333, 1, 0.3333]) let bias = Tensor<Float>(ones: [5]) var cell = BasicRNNCell<Float>(inputSize: 2, hiddenSize: 5) cell.weight = weight cell.bias = bias let state = Tensor<Float>(ones: [1, 5]) * Tensor<Float>([1, 0.2, 0.5, 2, 0.6]) let input = Tensor<Float>(ones: [1, 2]) * Tensor<Float>([0.3, 0.7]) let output = cell(input: input, state: state).state let expected = Tensor<Float>([[0.9921227, 0.9999934, 0.9921227, 0.9999934, 0.9921227]]) assertEqual(output, expected, accuracy: 1e-6) #endif } func testDense() { let weight = Tensor<Float>(shape: [3, 2], scalars: (0..<6).map(Float.init)) let bias = Tensor<Float>([[1.0, 2.0]]) let layer = Dense<Float>(weight: weight, bias: bias, activation: identity) let input = Tensor<Float>(shape: [1, 3], scalars: (0..<3).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>([[11.0, 15.0]]) XCTAssertEqual(output, expected) XCTAssertFalse(layer.batched) let layerNoBias = Dense<Float>(weight: weight, bias: nil, activation: identity) let outputNoBias = layerNoBias.inferring(from: input) let expectedNoBias = Tensor<Float>([[10.0, 13.0]]) XCTAssertEqual(outputNoBias, expectedNoBias) XCTAssertFalse(layerNoBias.batched) let weightBatched = Tensor<Float>(shape: [2, 2, 3], scalars: (0..<12).map(Float.init)) let biasBatched = Tensor<Float>([[1.0, 2.0, 3.0]]) let layerBatched = Dense<Float>( weight: weightBatched, bias: biasBatched, activation: identity) let inputBatched = Tensor<Float>(shape: [2, 2], scalars: (0..<4).map(Float.init)) let outputBatched = layerBatched.inferring(from: inputBatched) let expectedBatched = Tensor<Float>([[4.0, 6.0, 8.0], [40.0, 46.0, 52.0]]) XCTAssertEqual(outputBatched, expectedBatched) XCTAssertTrue(layerBatched.batched) let layerBatchedNoBias = Dense<Float>( weight: weightBatched, bias: nil, activation: identity) let outputBatchedNoBias = layerBatchedNoBias.inferring(from: inputBatched) let expectedBatchedNoBias = Tensor<Float>([[3.0, 4.0, 5.0], [39.0, 44.0, 49.0]]) XCTAssertEqual(outputBatchedNoBias, expectedBatchedNoBias) XCTAssertTrue(layerBatchedNoBias.batched) } func testDenseGradient() { let weight = Tensor<Float>(shape: [4, 8], scalars: (0..<32).map(Float.init)) let bias = Tensor<Float>(shape: [1, 8], scalars: (0..<8).map(Float.init)) // Test `Dense.init` derivative. let denseInitPullback = pullback(at: weight) { weight in Dense(weight: weight, bias: bias, activation: identity) } let weightGrad = denseInitPullback(.init(weight: Tensor(100), bias: Tensor(1))) XCTAssertEqual(Tensor(100), weightGrad) // Test `Dense.callAsFunction` derivative. let layer = Dense<Float>(weight: weight, bias: bias, activation: identity) let x = Tensor<Float>(shape: [2, 4], scalars: (0..<8).map(Float.init)) let grad = gradient(at: x, layer) { $1($0).squared().sum() } let value = layer(x) // The expected values and gradients were computed using the following Python code: // ``` // import tensorflow as tf // x = tf.reshape(tf.range(8, dtype=tf.float32), [2, 4]) // kernel_value = np.arange(32.0).reshape([4, 8]) // bias_value = np.arange(8.0) // kernel_initializer = tf.compat.v2.constant_initializer(kernel_value) // bias_initializer = tf.compat.v2.constant_initializer(bias_value) // layer = tf.keras.layers.Dense(8, // kernel_initializer=kernel_initializer, // bias_initializer=bias_initializer) // with tf.GradientTape() as tape: // tape.watch(x) // y = layer(x) // z = tf.math.reduce_sum(tf.math.square(y)) // print(y, tape.gradient(z, [x] + layer.trainable_variables)) // ``` assertEqual( value, [ [112.0, 119.0, 126.0, 133.0, 140.0, 147.0, 154.0, 161.0], [304.0, 327.0, 350.0, 373.0, 396.0, 419.0, 442.0, 465.0], ], accuracy: 1e-5) assertEqual( grad.0, [ [8232.0, 25704.0, 43176.0, 60648.0], [23464.0, 72680.0, 121896.0, 171112.0], ], accuracy: 1e-5) assertEqual( grad.1.weight, [ [2432.0, 2616.0, 2800.0, 2984.0, 3168.0, 3352.0, 3536.0, 3720.0], [3264.0, 3508.0, 3752.0, 3996.0, 4240.0, 4484.0, 4728.0, 4972.0], [4096.0, 4400.0, 4704.0, 5008.0, 5312.0, 5616.0, 5920.0, 6224.0], [4928.0, 5292.0, 5656.0, 6020.0, 6384.0, 6748.0, 7112.0, 7476.0], ], accuracy: 1e-5) assertEqual( grad.1.bias, [[832.0, 892.0, 952.0, 1012.0, 1072.0, 1132.0, 1192.0, 1252.0]], accuracy: 1e-5) } // TODO(TF-507): Remove references to `BasicRNNCell.State` after SR-10697 is fixed. func testRNN() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/rnn.py". // BEGIN GENERATED CODE let kernel = Tensor<Float>( [[-0.3603096,-0.5082418,0.06129855,0.106101096], [-0.144324,0.5331736,-0.011734486,0.86278516], [0.34075528,-0.64887196,0.36341316,0.28131205], [0.12515205,-0.23425382,-0.1376664,0.22526532]] ) let recurrentKernel = Tensor<Float>( [[0.34720516,0.6280322,-0.6963875,-0.008289718], [-0.057777617,-0.7034996,-0.6661205,0.240902], [0.2612954,-0.2549268,-0.08859509,-0.9267621], [-0.89879644,0.21372059,-0.25195017,-0.2881138]] ) let bias = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.5279052,0.4159922,-0.02112794,0.6500738], [-0.16088444,-0.8408272,0.36293703,-0.23294312], [0.14004618,0.69427365,-0.637702,0.077886045], [0.3410867,-0.85888004,-0.23541403,0.1133005]]] ) let initialState = Tensor<Float>( [[-0.71174276,-0.39879853,0.7789655,-0.1812765]] ) let expectedSum = Tensor<Float>( -2.2336872 ) let expectedStates = Tensor<Float>( [[[0.33346513,-0.052190434,0.53956664,-0.30630472], [0.6689981,-0.4655246,-0.004116005,-0.8075811], [0.5551112,0.8539695,-0.19158833,0.5159598], [-0.40981215,-0.53569716,-0.813944,-0.47423384]]] ) let expectedFinalState = Tensor<Float>( [[-0.40981215,-0.53569716,-0.813944,-0.47423384]] ) let expectedGradKernel = Tensor<Float>( [[0.41519257,0.5748159,-0.07927984,0.35657609], [-0.8111099,-1.2970712,-1.4684451,-1.2794279], [-0.30848962,0.060518686,0.65190136,0.2506955], [-0.10142271,-0.49896276,-0.24145404,-0.19505012]] ) let expectedGradRecurrentKernel = Tensor<Float>( [[0.956356,0.9344623,0.03898424,0.2403388], [0.63330317,0.9714962,0.5893948,1.1109966], [-0.20000206,-0.56593496,0.32656404,-0.41654968], [0.11153888,0.5413084,0.492511,0.9971381]] ) let expectedGradBias = Tensor<Float>( [1.2097166,0.09570068,0.3972284,-0.23335484] ) let expectedGradX = Tensor<Float>( [[[0.4343156,-0.67581093,0.29182205,0.0771346], [-0.20495477,0.11982066,0.19146681,-0.14591387], [-0.15502127,-0.69844127,-0.21601494,0.025262251], [-0.5592608,0.92486906,0.16155839,0.06524551]]] ) let expectedGradInitialState = Tensor<Float>( [[-0.5194068,0.50558126,0.46355626,0.17153597]] ) // END GENERATED CODE withTensorLeakChecking { var rnn = BasicRNN<Float>( BasicRNNCell(inputSize: 4, hiddenSize: 4, seed: (0xFeed, 0xBeef)) ) rnn.cell.weight = Tensor(concatenating: [kernel, recurrentKernel]) rnn.cell.bias = bias let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialState = BasicRNNCell<Float>.State(initialState) let outputs = rnn( inputs, initialState: initialState ) assertEqual( Tensor(concatenating: outputs.map { $0 }), expectedStates, accuracy: 1e-6) assertEqual( outputs.last!, expectedFinalState, accuracy: 1e-6) let (outputSum, (gradRNN, gradInputs, gradInitialState)) = valueWithGradient(at: rnn, inputs, initialState) { rnn, inputs, initialState in rnn.lastOutput( from: inputs, initialState: initialState ).sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradRNN.cell.weight, Tensor(concatenating: [expectedGradKernel, expectedGradRecurrentKernel]), accuracy: 1e-6) assertEqual( gradRNN.cell.bias, expectedGradBias, accuracy: 1e-6) assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialState, expectedGradInitialState, accuracy: 1e-6) } #endif } func testBidirectionalBasicRNNSumMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_rnn.py --merge-mode sum". // BEGIN GENERATED CODE let kernelForward = Tensor<Float>( [[-0.3603096,-0.5082418,0.06129855,0.106101096], [-0.144324,0.5331736,-0.011734486,0.86278516], [0.34075528,-0.64887196,0.36341316,0.28131205], [0.12515205,-0.23425382,-0.1376664,0.22526532]] ) let recurrentKernelForward = Tensor<Float>( [[0.34720516,0.6280322,-0.6963875,-0.008289718], [-0.057777617,-0.7034996,-0.6661205,0.240902], [0.2612954,-0.2549268,-0.08859509,-0.9267621], [-0.89879644,0.21372059,-0.25195017,-0.2881138]] ) let biasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let kernelBackward = Tensor<Float>( [[-0.5279052,0.4159922,-0.02112794,0.6500738], [-0.16088444,-0.8408272,0.36293703,-0.23294312], [0.14004618,0.69427365,-0.637702,0.077886045], [0.3410867,-0.85888004,-0.23541403,0.1133005]] ) let recurrentKernelBackward = Tensor<Float>( [[0.67490876,-0.05608359,0.44851846,0.58325285], [0.6672334,0.4354152,-0.21524309,-0.56469786], [0.027053772,-0.4727077,0.6594652,-0.5838845], [-0.31395176,0.7640783,0.5635665,0.003379479]] ) let biasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.8425845,-0.7054219,-0.023461938,0.35520858], [-0.24800867,0.09574294,0.3316267,-0.13671225], [-0.5058244,-0.6568735,-0.31837505,-0.7905574], [-0.50511885,0.50999504,0.74102694,0.12891835]]] ) let initialForwardLayerState = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialBackwardLayerState = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let expectedSum = Tensor<Float>( -1.3748394 ) let expectedStates = Tensor<Float>( [[[0.039731443,0.30118462,-1.1362883,-0.6404417], [-0.36877188,0.23013103,0.053439736,0.29040766], [-0.7231241,0.4473409,-0.46913218,-0.64710104], [0.41570857,-1.500107,-0.20221666,-0.08822429]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those two and test it. // let expectedFinalStateForward = Tensor<Float>( // [[0.8125853,-0.5553411,0.27422628,0.73577887]] // ) // let expectedFinalStateBackward = Tensor<Float>( // [[0.7070243,0.29404274,-0.76932997,-0.51012546]] // ) let expectedGradKernelForward = Tensor<Float>( [[-0.25060007,0.44844362,0.017417982,-0.39773455], [0.08897984,1.4653344,1.0778612,0.13088357], [0.23334727,1.066688,0.9485493,0.37866586], [0.20101692,0.36850378,0.45986187,0.18827611]] ) let expectedGradRecurrentKernelForward = Tensor<Float>( [[-0.016110066,-0.50083566,-0.22681743,-0.17596911], [0.24926353,0.33903763,0.51411784,0.3097041], [-0.12677985,-0.19154882,-0.1418991,-0.20690772], [-0.14268747,-1.8729569,-1.4547974,-0.23180081]] ) let expectedGradBiasForward = Tensor<Float>( [0.3045485,0.011022985,0.25799057,0.6699498] ) let expectedGradKernelBackward = Tensor<Float>( [[-0.42555702,-0.054258525,-0.39045796,-0.16215265], [0.42966515,0.054782312,0.39422727,0.163718], [0.624307,0.07959915,0.5728154,0.23788358], [0.10861228,0.013848067,0.09965416,0.041385215]] ) let expectedGradRecurrentKernelBackward = Tensor<Float>( [[-0.82486856,-0.10517075,-0.7568351,-0.31430483], [-0.5736132,-0.07313569,-0.52630275,-0.21856743], [0.87171334,0.11114346,0.79981625,0.3321544], [-0.8984336,-0.1145503,-0.82433265,-0.3423358]] ) let expectedGradBiasBackward = Tensor<Float>( [0.8424889,0.107417345,0.77300215,0.32101882] ) let expectedGradX = Tensor<Float>( [[[0.29702687,-0.20684643,0.48203292,0.27731684], [-0.36015642,0.51716775,-0.49674046,-0.22718005], [0.40323955,-0.47796234,0.2614523,0.24429059], [-0.5762627,0.6844691,-0.14327642,-0.093995675]]] ) let expectedGradInitialStateForward = Tensor<Float>( [[-0.18421142,0.7250765,0.04656464,-0.31281057]] ) let expectedGradInitialStateBackward = Tensor<Float>( [[1.0965196,0.26124585,0.29434562,0.2542974]] ) // END GENERATED CODE withTensorLeakChecking { var rnn = BidirectionalBasicRNN<Float>( BasicRNNCell(inputSize: 4, hiddenSize: 4), mergeFunction: BasicRNNCell<Float>.State.sum ) rnn.forward.cell.weight = Tensor(concatenating: [kernelForward, recurrentKernelForward]) rnn.forward.cell.bias = biasForward rnn.backward.cell.weight = Tensor(concatenating: [kernelBackward, recurrentKernelBackward]) rnn.backward.cell.bias = biasBackward let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = BasicRNNCell<Float>.State(initialForwardLayerState) let initialBackwardLayerState = BasicRNNCell<Float>.State(initialBackwardLayerState) let outputs = rnn( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ) assertEqual( Tensor(concatenating: outputs), expectedStates, accuracy: 1e-6) let (outputSum, (gradRNN)) = valueWithGradient(at: rnn) { rnn in rnn.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradRNN.forward.cell.weight, Tensor(concatenating: [expectedGradKernelForward, expectedGradRecurrentKernelForward]), accuracy: 1e-6) assertEqual( gradRNN.forward.cell.bias, expectedGradBiasForward, accuracy: 1e-6) assertEqual( gradRNN.backward.cell.weight, Tensor(concatenating: [expectedGradKernelBackward, expectedGradRecurrentKernelBackward]), accuracy: 1e-6) assertEqual( gradRNN.backward.cell.bias, expectedGradBiasBackward, accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in rnn.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward, expectedGradInitialStateForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward, expectedGradInitialStateBackward, accuracy: 1e-6) } #endif } func testBidirectionalBasicRNNConcatenateMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_rnn.py --merge-mode concat". // BEGIN GENERATED CODE let kernelForward = Tensor<Float>( [[-0.3603096,-0.5082418,0.06129855,0.106101096], [-0.144324,0.5331736,-0.011734486,0.86278516], [0.34075528,-0.64887196,0.36341316,0.28131205], [0.12515205,-0.23425382,-0.1376664,0.22526532]] ) let recurrentKernelForward = Tensor<Float>( [[0.34720516,0.6280322,-0.6963875,-0.008289718], [-0.057777617,-0.7034996,-0.6661205,0.240902], [0.2612954,-0.2549268,-0.08859509,-0.9267621], [-0.89879644,0.21372059,-0.25195017,-0.2881138]] ) let biasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let kernelBackward = Tensor<Float>( [[-0.5279052,0.4159922,-0.02112794,0.6500738], [-0.16088444,-0.8408272,0.36293703,-0.23294312], [0.14004618,0.69427365,-0.637702,0.077886045], [0.3410867,-0.85888004,-0.23541403,0.1133005]] ) let recurrentKernelBackward = Tensor<Float>( [[0.67490876,-0.05608359,0.44851846,0.58325285], [0.6672334,0.4354152,-0.21524309,-0.56469786], [0.027053772,-0.4727077,0.6594652,-0.5838845], [-0.31395176,0.7640783,0.5635665,0.003379479]] ) let biasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.8425845,-0.7054219,-0.023461938,0.35520858], [-0.24800867,0.09574294,0.3316267,-0.13671225], [-0.5058244,-0.6568735,-0.31837505,-0.7905574], [-0.50511885,0.50999504,0.74102694,0.12891835]]] ) let initialForwardLayerState = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialBackwardLayerState = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let expectedSum = Tensor<Float>( -1.3748394 ) let expectedStates = Tensor<Float>( [[[-0.66729283,0.007141886,-0.36695832,-0.13031624,0.7070243,0.29404274, -0.76932997,-0.51012546], [-0.03940088,-0.34914643,0.57051975,0.46499598,-0.329371,0.57927746, -0.51708,-0.17458834], [-0.19038993,0.44098023,0.062064223,-0.9267066,-0.53273416, 0.0063606827,-0.5311964,0.27960557], [0.8125853,-0.5553411,0.27422628,0.73577887,-0.39687672,-0.9447659, -0.47644293,-0.82400316]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those two and test it. // let expectedFinalStateForward = Tensor<Float>( // [[0.8125853,-0.5553411,0.27422628,0.73577887]] // ) // let expectedFinalStateBackward = Tensor<Float>( // [[0.7070243,0.29404274,-0.76932997,-0.51012546]] // ) let expectedGradKernelForward = Tensor<Float>( [[-0.25060007,0.44844362,0.017417982,-0.39773455], [0.08897984,1.4653344,1.0778612,0.13088357], [0.23334727,1.066688,0.9485493,0.37866586], [0.20101692,0.36850378,0.45986187,0.18827611]] ) let expectedGradRecurrentKernelForward = Tensor<Float>( [[-0.016110066,-0.50083566,-0.22681743,-0.17596911], [0.24926353,0.33903763,0.51411784,0.3097041], [-0.12677985,-0.19154882,-0.1418991,-0.20690772], [-0.14268747,-1.8729569,-1.4547974,-0.23180081]] ) let expectedGradBiasForward = Tensor<Float>( [0.3045485,0.011022985,0.25799057,0.6699498] ) let expectedGradKernelBackward = Tensor<Float>( [[-0.42555702,-0.054258525,-0.39045796,-0.16215265], [0.42966515,0.054782312,0.39422727,0.163718], [0.624307,0.07959915,0.5728154,0.23788358], [0.10861228,0.013848067,0.09965416,0.041385215]] ) let expectedGradRecurrentKernelBackward = Tensor<Float>( [[-0.82486856,-0.10517075,-0.7568351,-0.31430483], [-0.5736132,-0.07313569,-0.52630275,-0.21856743], [0.87171334,0.11114346,0.79981625,0.3321544], [-0.8984336,-0.1145503,-0.82433265,-0.3423358]] ) let expectedGradBiasBackward = Tensor<Float>( [0.8424889,0.107417345,0.77300215,0.32101882] ) let expectedGradX = Tensor<Float>( [[[0.29702687,-0.20684643,0.48203292,0.27731684], [-0.36015642,0.51716775,-0.49674046,-0.22718005], [0.40323955,-0.47796234,0.2614523,0.24429059], [-0.5762627,0.6844691,-0.14327642,-0.093995675]]] ) let expectedGradInitialStateForward = Tensor<Float>( [[-0.18421142,0.7250765,0.04656464,-0.31281057]] ) let expectedGradInitialStateBackward = Tensor<Float>( [[1.0965196,0.26124585,0.29434562,0.2542974]] ) // END GENERATED CODE withTensorLeakChecking { var rnn = BidirectionalBasicRNN<Float>( BasicRNNCell(inputSize: 4, hiddenSize: 4) ) rnn.forward.cell.weight = Tensor(concatenating: [kernelForward, recurrentKernelForward]) rnn.forward.cell.bias = biasForward rnn.backward.cell.weight = Tensor(concatenating: [kernelBackward, recurrentKernelBackward]) rnn.backward.cell.bias = biasBackward let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = BasicRNNCell<Float>.State(initialForwardLayerState) let initialBackwardLayerState = BasicRNNCell<Float>.State(initialBackwardLayerState) let outputs = rnn( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ) assertEqual( Tensor(concatenating: outputs), expectedStates, accuracy: 1e-6) let (outputSum, (gradRNN)) = valueWithGradient(at: rnn) { rnn in rnn.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradRNN.forward.cell.weight, Tensor(concatenating: [expectedGradKernelForward, expectedGradRecurrentKernelForward]), accuracy: 1e-6) assertEqual( gradRNN.forward.cell.bias, expectedGradBiasForward, accuracy: 1e-6) assertEqual( gradRNN.backward.cell.weight, Tensor(concatenating: [expectedGradKernelBackward, expectedGradRecurrentKernelBackward]), accuracy: 1e-6) assertEqual( gradRNN.backward.cell.bias, expectedGradBiasBackward, accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in rnn.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward, expectedGradInitialStateForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward, expectedGradInitialStateBackward, accuracy: 1e-6) } #endif } func testBidirectionalBasicRNNAverageMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_rnn.py --merge-mode ave". // BEGIN GENERATED CODE let kernelForward = Tensor<Float>( [[-0.3603096,-0.5082418,0.06129855,0.106101096], [-0.144324,0.5331736,-0.011734486,0.86278516], [0.34075528,-0.64887196,0.36341316,0.28131205], [0.12515205,-0.23425382,-0.1376664,0.22526532]] ) let recurrentKernelForward = Tensor<Float>( [[0.34720516,0.6280322,-0.6963875,-0.008289718], [-0.057777617,-0.7034996,-0.6661205,0.240902], [0.2612954,-0.2549268,-0.08859509,-0.9267621], [-0.89879644,0.21372059,-0.25195017,-0.2881138]] ) let biasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let kernelBackward = Tensor<Float>( [[-0.5279052,0.4159922,-0.02112794,0.6500738], [-0.16088444,-0.8408272,0.36293703,-0.23294312], [0.14004618,0.69427365,-0.637702,0.077886045], [0.3410867,-0.85888004,-0.23541403,0.1133005]] ) let recurrentKernelBackward = Tensor<Float>( [[0.67490876,-0.05608359,0.44851846,0.58325285], [0.6672334,0.4354152,-0.21524309,-0.56469786], [0.027053772,-0.4727077,0.6594652,-0.5838845], [-0.31395176,0.7640783,0.5635665,0.003379479]] ) let biasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.8425845,-0.7054219,-0.023461938,0.35520858], [-0.24800867,0.09574294,0.3316267,-0.13671225], [-0.5058244,-0.6568735,-0.31837505,-0.7905574], [-0.50511885,0.50999504,0.74102694,0.12891835]]] ) let initialForwardLayerState = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialBackwardLayerState = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let expectedSum = Tensor<Float>( -0.6874197 ) let expectedStates = Tensor<Float>( [[[0.019865721,0.15059231,-0.56814414,-0.32022086], [-0.18438594,0.115065515,0.026719868,0.14520383], [-0.36156204,0.22367045,-0.23456609,-0.32355052], [0.20785429,-0.7500535,-0.10110833,-0.044112146]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those two and test it. // let expectedFinalStateForward = Tensor<Float>( // [[0.8125853,-0.5553411,0.27422628,0.73577887]] // ) // let expectedFinalStateBackward = Tensor<Float>( // [[0.7070243,0.29404274,-0.76932997,-0.51012546]] // ) let expectedGradKernelForward = Tensor<Float>( [[-0.12530003,0.22422181,0.008708991,-0.19886728], [0.04448992,0.7326672,0.5389306,0.06544179], [0.11667363,0.533344,0.47427464,0.18933293], [0.10050846,0.18425189,0.22993094,0.094138056]] ) let expectedGradRecurrentKernelForward = Tensor<Float>( [[-0.008055033,-0.25041783,-0.113408715,-0.087984554], [0.12463176,0.16951881,0.25705892,0.15485205], [-0.06338993,-0.09577441,-0.07094955,-0.10345386], [-0.071343735,-0.93647844,-0.7273987,-0.115900405]] ) let expectedGradBiasForward = Tensor<Float>( [0.15227425,0.0055114925,0.12899528,0.3349749] ) let expectedGradKernelBackward = Tensor<Float>( [[-0.21277851,-0.027129263,-0.19522898,-0.081076324], [0.21483257,0.027391156,0.19711363,0.081859], [0.3121535,0.039799575,0.2864077,0.11894179], [0.05430614,0.0069240336,0.04982708,0.020692607]] ) let expectedGradRecurrentKernelBackward = Tensor<Float>( [[-0.41243428,-0.052585375,-0.37841755,-0.15715241], [-0.2868066,-0.036567844,-0.26315138,-0.109283715], [0.43585667,0.05557173,0.39990813,0.1660772], [-0.4492168,-0.05727515,-0.41216633,-0.1711679]] ) let expectedGradBiasBackward = Tensor<Float>( [0.42124444,0.053708673,0.38650107,0.16050941] ) let expectedGradX = Tensor<Float>( [[[0.14851344,-0.103423215,0.24101646,0.13865842], [-0.18007821,0.25858387,-0.24837023,-0.113590024], [0.20161977,-0.23898117,0.13072614,0.122145295], [-0.28813136,0.34223455,-0.07163821,-0.046997838]]] ) let expectedGradInitialStateForward = Tensor<Float>( [[-0.09210571,0.36253825,0.02328232,-0.15640529]] ) let expectedGradInitialStateBackward = Tensor<Float>( [[0.5482598,0.13062292,0.14717281,0.1271487]] ) // END GENERATED CODE withTensorLeakChecking { var rnn = BidirectionalBasicRNN<Float>( BasicRNNCell(inputSize: 4, hiddenSize: 4), mergeFunction: BasicRNNCell<Float>.State.average ) rnn.forward.cell.weight = Tensor(concatenating: [kernelForward, recurrentKernelForward]) rnn.forward.cell.bias = biasForward rnn.backward.cell.weight = Tensor(concatenating: [kernelBackward, recurrentKernelBackward]) rnn.backward.cell.bias = biasBackward let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = BasicRNNCell<Float>.State(initialForwardLayerState) let initialBackwardLayerState = BasicRNNCell<Float>.State(initialBackwardLayerState) let outputs = rnn( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ) assertEqual( Tensor(concatenating: outputs), expectedStates, accuracy: 1e-6) let (outputSum, (gradRNN)) = valueWithGradient(at: rnn) { rnn in rnn.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradRNN.forward.cell.weight, Tensor(concatenating: [expectedGradKernelForward, expectedGradRecurrentKernelForward]), accuracy: 1e-6) assertEqual( gradRNN.forward.cell.bias, expectedGradBiasForward, accuracy: 1e-6) assertEqual( gradRNN.backward.cell.weight, Tensor(concatenating: [expectedGradKernelBackward, expectedGradRecurrentKernelBackward]), accuracy: 1e-6) assertEqual( gradRNN.backward.cell.bias, expectedGradBiasBackward, accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in rnn.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward, expectedGradInitialStateForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward, expectedGradInitialStateBackward, accuracy: 1e-6) } #endif } func testBidirectionalBasicRNNMultiplyMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_rnn.py --merge-mode mul". // BEGIN GENERATED CODE let kernelForward = Tensor<Float>( [[-0.3603096,-0.5082418,0.06129855,0.106101096], [-0.144324,0.5331736,-0.011734486,0.86278516], [0.34075528,-0.64887196,0.36341316,0.28131205], [0.12515205,-0.23425382,-0.1376664,0.22526532]] ) let recurrentKernelForward = Tensor<Float>( [[0.34720516,0.6280322,-0.6963875,-0.008289718], [-0.057777617,-0.7034996,-0.6661205,0.240902], [0.2612954,-0.2549268,-0.08859509,-0.9267621], [-0.89879644,0.21372059,-0.25195017,-0.2881138]] ) let biasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let kernelBackward = Tensor<Float>( [[-0.5279052,0.4159922,-0.02112794,0.6500738], [-0.16088444,-0.8408272,0.36293703,-0.23294312], [0.14004618,0.69427365,-0.637702,0.077886045], [0.3410867,-0.85888004,-0.23541403,0.1133005]] ) let recurrentKernelBackward = Tensor<Float>( [[0.67490876,-0.05608359,0.44851846,0.58325285], [0.6672334,0.4354152,-0.21524309,-0.56469786], [0.027053772,-0.4727077,0.6594652,-0.5838845], [-0.31395176,0.7640783,0.5635665,0.003379479]] ) let biasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.8425845,-0.7054219,-0.023461938,0.35520858], [-0.24800867,0.09574294,0.3316267,-0.13671225], [-0.5058244,-0.6568735,-0.31837505,-0.7905574], [-0.50511885,0.50999504,0.74102694,0.12891835]]] ) let initialForwardLayerState = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialBackwardLayerState = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let expectedSum = Tensor<Float>( -0.5347661 ) let expectedStates = Tensor<Float>( [[[-0.47179222,0.0021000197,0.28231204,0.066477634], [0.012977507,-0.20225266,-0.29500437,-0.081182875], [0.10142722,0.0028049352,-0.032968294,-0.25911233], [-0.32249618,0.5246674,-0.13065317,-0.60628414]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those two and test it. // let expectedFinalStateForward = Tensor<Float>( // [[0.8125853,-0.5553411,0.27422628,0.73577887]] // ) // let expectedFinalStateBackward = Tensor<Float>( // [[0.7070243,0.29404274,-0.76932997,-0.51012546]] // ) let expectedGradKernelForward = Tensor<Float>( [[0.29835904,-0.271358,-0.056388527,0.19803399], [0.13539863,-1.1518296,-0.62982273,-0.16866776], [-0.07457287,-0.876209,-0.54846895,-0.26091105], [0.045224264,-0.22196792,-0.41959473,-0.09994551]] ) let expectedGradRecurrentKernelForward = Tensor<Float>( [[0.11663125,0.39018548,0.1591308,0.027596578], [-0.071245454,-0.27228498,-0.3515284,-0.19403662], [0.06461461,0.05803746,0.27710906,0.00072359666], [-0.108036324,1.5429575,0.7437697,0.30051786]] ) let expectedGradBiasForward = Tensor<Float>( [-0.51533103,-0.16392553,-0.019812264,-0.31751463] ) let expectedGradKernelBackward = Tensor<Float>( [[-0.34580138,0.030131992,-0.10707383,-0.119308494], [0.3491396,-0.030422872,0.10810747,0.12046025], [0.50730264,-0.044204682,0.15708104,0.17502971], [0.08825674,-0.0076904013,0.027327789,0.030450366]] ) let expectedGradRecurrentKernelBackward = Tensor<Float>( [[-0.67027605,0.058405645,-0.20754407,-0.23125885], [-0.46610966,0.040615257,-0.14432605,-0.1608173], [0.7083415,-0.06172254,0.21933062,0.24439217], [-0.73005396,0.063614495,-0.22605367,-0.25188342]] ) let expectedGradBiasBackward = Tensor<Float>( [0.6845941,-0.05965327,0.2119775,0.23619886] ) let expectedGradX = Tensor<Float>( [[[-0.23223981,0.2862338,-0.41787457,-0.17583233], [0.34112248,-0.2498242,0.34255287,0.17837948], [-0.18834808,0.32665232,-0.20202757,-0.20915407], [0.07640687,-0.68787134,0.049270652,0.37331474]]] ) let expectedGradInitialStateForward = Tensor<Float>( [[0.25459114,-0.45141447,-0.14997824,0.26960957]] ) let expectedGradInitialStateBackward = Tensor<Float>( [[0.6982236,0.25180238,0.048598364,-0.14024764]] ) // END GENERATED CODE withTensorLeakChecking { var rnn = BidirectionalBasicRNN<Float>( BasicRNNCell(inputSize: 4, hiddenSize: 4), mergeFunction: BasicRNNCell<Float>.State.multiply ) rnn.forward.cell.weight = Tensor(concatenating: [kernelForward, recurrentKernelForward]) rnn.forward.cell.bias = biasForward rnn.backward.cell.weight = Tensor(concatenating: [kernelBackward, recurrentKernelBackward]) rnn.backward.cell.bias = biasBackward let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = BasicRNNCell<Float>.State(initialForwardLayerState) let initialBackwardLayerState = BasicRNNCell<Float>.State(initialBackwardLayerState) let outputs = rnn( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ) assertEqual( Tensor(concatenating: outputs), expectedStates, accuracy: 1e-6) let (outputSum, (gradRNN)) = valueWithGradient(at: rnn) { rnn in rnn.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradRNN.forward.cell.weight, Tensor(concatenating: [expectedGradKernelForward, expectedGradRecurrentKernelForward]), accuracy: 1e-6) assertEqual( gradRNN.forward.cell.bias, expectedGradBiasForward, accuracy: 1e-6) assertEqual( gradRNN.backward.cell.weight, Tensor(concatenating: [expectedGradKernelBackward, expectedGradRecurrentKernelBackward]), accuracy: 1e-6) assertEqual( gradRNN.backward.cell.bias, expectedGradBiasBackward, accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in rnn.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward, expectedGradInitialStateForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward, expectedGradInitialStateBackward, accuracy: 1e-6) } #endif } func testBidirectionalBasicRNNStackMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_rnn.py --merge-mode none". // BEGIN GENERATED CODE let kernelForward = Tensor<Float>( [[-0.3603096,-0.5082418,0.06129855,0.106101096], [-0.144324,0.5331736,-0.011734486,0.86278516], [0.34075528,-0.64887196,0.36341316,0.28131205], [0.12515205,-0.23425382,-0.1376664,0.22526532]] ) let recurrentKernelForward = Tensor<Float>( [[0.34720516,0.6280322,-0.6963875,-0.008289718], [-0.057777617,-0.7034996,-0.6661205,0.240902], [0.2612954,-0.2549268,-0.08859509,-0.9267621], [-0.89879644,0.21372059,-0.25195017,-0.2881138]] ) let biasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let kernelBackward = Tensor<Float>( [[-0.5279052,0.4159922,-0.02112794,0.6500738], [-0.16088444,-0.8408272,0.36293703,-0.23294312], [0.14004618,0.69427365,-0.637702,0.077886045], [0.3410867,-0.85888004,-0.23541403,0.1133005]] ) let recurrentKernelBackward = Tensor<Float>( [[0.67490876,-0.05608359,0.44851846,0.58325285], [0.6672334,0.4354152,-0.21524309,-0.56469786], [0.027053772,-0.4727077,0.6594652,-0.5838845], [-0.31395176,0.7640783,0.5635665,0.003379479]] ) let biasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.8425845,-0.7054219,-0.023461938,0.35520858], [-0.24800867,0.09574294,0.3316267,-0.13671225], [-0.5058244,-0.6568735,-0.31837505,-0.7905574], [-0.50511885,0.50999504,0.74102694,0.12891835]]] ) let initialForwardLayerState = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialBackwardLayerState = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let expectedSum = Tensor<Float>( -1.3748394 ) let expectedStatesForward = Tensor<Float>( [[[-0.66729283,0.007141886,-0.36695832,-0.13031624], [-0.03940088,-0.34914643,0.57051975,0.46499598], [-0.19038993,0.44098023,0.062064223,-0.9267066], [0.8125853,-0.5553411,0.27422628,0.73577887]]] ) let expectedStatesBackward = Tensor<Float>( [[[0.7070243,0.29404274,-0.76932997,-0.51012546], [-0.329371,0.57927746,-0.51708,-0.17458834], [-0.53273416,0.0063606827,-0.5311964,0.27960557], [-0.39687672,-0.9447659,-0.47644293,-0.82400316]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those two and test it. // let expectedFinalStateForward = Tensor<Float>( // [[0.8125853,-0.5553411,0.27422628,0.73577887]] // ) // let expectedFinalStateBackward = Tensor<Float>( // [[0.7070243,0.29404274,-0.76932997,-0.51012546]] // ) let expectedGradKernelForward = Tensor<Float>( [[-0.25060007,0.44844362,0.017417982,-0.39773455], [0.08897984,1.4653344,1.0778612,0.13088357], [0.23334727,1.066688,0.9485493,0.37866586], [0.20101692,0.36850378,0.45986187,0.18827611]] ) let expectedGradRecurrentKernelForward = Tensor<Float>( [[-0.016110066,-0.50083566,-0.22681743,-0.17596911], [0.24926353,0.33903763,0.51411784,0.3097041], [-0.12677985,-0.19154882,-0.1418991,-0.20690772], [-0.14268747,-1.8729569,-1.4547974,-0.23180081]] ) let expectedGradBiasForward = Tensor<Float>( [0.3045485,0.011022985,0.25799057,0.6699498] ) let expectedGradKernelBackward = Tensor<Float>( [[-0.42555702,-0.054258525,-0.39045796,-0.16215265], [0.42966515,0.054782312,0.39422727,0.163718], [0.624307,0.07959915,0.5728154,0.23788358], [0.10861228,0.013848067,0.09965416,0.041385215]] ) let expectedGradRecurrentKernelBackward = Tensor<Float>( [[-0.82486856,-0.10517075,-0.7568351,-0.31430483], [-0.5736132,-0.07313569,-0.52630275,-0.21856743], [0.87171334,0.11114346,0.79981625,0.3321544], [-0.8984336,-0.1145503,-0.82433265,-0.3423358]] ) let expectedGradBiasBackward = Tensor<Float>( [0.8424889,0.107417345,0.77300215,0.32101882] ) let expectedGradX = Tensor<Float>( [[[0.29702687,-0.20684643,0.48203292,0.27731684], [-0.36015642,0.51716775,-0.49674046,-0.22718005], [0.40323955,-0.47796234,0.2614523,0.24429059], [-0.5762627,0.6844691,-0.14327642,-0.093995675]]] ) let expectedGradInitialStateForward = Tensor<Float>( [[-0.18421142,0.7250765,0.04656464,-0.31281057]] ) let expectedGradInitialStateBackward = Tensor<Float>( [[1.0965196,0.26124585,0.29434562,0.2542974]] ) // END GENERATED CODE withTensorLeakChecking { var rnn = BidirectionalBasicRNN<Float>( BasicRNNCell(inputSize: 4, hiddenSize: 4), mergeFunction: BasicRNNCell<Float>.State.stack ) rnn.forward.cell.weight = Tensor(concatenating: [kernelForward, recurrentKernelForward]) rnn.forward.cell.bias = biasForward rnn.backward.cell.weight = Tensor(concatenating: [kernelBackward, recurrentKernelBackward]) rnn.backward.cell.bias = biasBackward let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = BasicRNNCell<Float>.State(initialForwardLayerState) let initialBackwardLayerState = BasicRNNCell<Float>.State(initialBackwardLayerState) let outputs = rnn( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).map { $0.unstacked(alongAxis: 0) } assertEqual( Tensor(concatenating: outputs.map { $0[0] }), expectedStatesForward, accuracy: 1e-6) assertEqual( Tensor(concatenating: outputs.map { $0[1] }), expectedStatesBackward, accuracy: 1e-6) let (outputSum, (gradRNN)) = valueWithGradient(at: rnn) { rnn in rnn.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradRNN.forward.cell.weight, Tensor(concatenating: [expectedGradKernelForward, expectedGradRecurrentKernelForward]), accuracy: 1e-6) assertEqual( gradRNN.forward.cell.bias, expectedGradBiasForward, accuracy: 1e-6) assertEqual( gradRNN.backward.cell.weight, Tensor(concatenating: [expectedGradKernelBackward, expectedGradRecurrentKernelBackward]), accuracy: 1e-6) assertEqual( gradRNN.backward.cell.bias, expectedGradBiasBackward, accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in rnn.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward, expectedGradInitialStateForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward, expectedGradInitialStateBackward, accuracy: 1e-6) } #endif } func testLSTM() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/lstm.py". // BEGIN GENERATED CODE let kernel = Tensor<Float>( [ [ 0.4545238, 0.17410219, 0.07151973, -0.043370485, -0.08141422, -0.23986903, 0.2063713, 0.17585361, 0.4534099, -0.5096329, 0.2199418, -0.2149244, 0.23440659, 0.43826634, -0.13891399, -0.17842606, ], [ -0.3797379, 0.079282284, -0.10015741, -0.3239718, -0.27132228, 0.39218837, -0.43364745, -0.34852988, 0.2132551, -0.5461597, -0.048002183, 0.26265675, -0.18781787, -0.41067505, -0.051611483, 0.4885484, ], [ -0.06933203, 0.54473567, -0.21874839, -0.49106207, -0.071650594, -0.08455315, 0.5346174, 0.057993293, -0.13344201, -0.48908734, -0.058430463, -0.15182033, 0.03391558, 0.009597003, 0.273346, -0.49635035, ], [ -0.07164055, 0.37893647, -0.108646095, 0.07596207, 0.31213146, -0.3623113, -0.20532963, -0.302337, -0.26968825, 0.4479969, -0.085390985, 0.2579115, 0.2743805, -0.21505526, -0.31751555, -0.44200268, ], ] ) let recurrentKernel = Tensor<Float>( [ [ 0.001444459, -0.44615534, 0.17120321, 0.028076064, -0.36675194, -0.37769908, -0.038331404, -0.3308463, 0.18919824, 0.21540813, 0.21875387, -0.17696984, 0.24726436, -0.2989273, 0.26229933, 0.045673575, ], [ -0.0060651056, -0.010614913, -0.41048288, -0.16720156, -0.042991478, -0.034523666, -0.22591552, -0.46458426, -0.15950868, 0.0032770582, 0.02271657, 0.26582226, -0.38004795, 0.21254668, 0.35087258, 0.35231543, ], [ -0.2352461, -0.12130469, -0.19648746, 0.29172993, 0.10191456, -0.2919168, -0.1870388, 0.2183716, 0.34960067, -0.24624759, 0.3270614, 0.4467347, 0.11563631, 0.2551108, 0.06388308, -0.2366966, ], [ -0.36797202, 0.21800567, -0.06400205, 0.43761855, 0.1086247, 0.3239568, -0.23723324, -0.07836083, -0.10523385, 0.34244883, 0.11385839, -0.15765572, 0.42096126, 0.08826415, 0.10015068, 0.28478572, ], ] ) let bias = Tensor<Float>( [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) let x = Tensor<Float>( [ [ [-0.6346513, -0.43788078, -0.40050998, -0.35219777], [-0.59232813, -0.728384, -0.22974151, 0.3288936], [0.5766824, -0.5468713, 0.16438323, 0.6741958], [-0.47952235, -0.24399251, 0.8553043, 0.8588342], ] ] ) let initialStateHidden = Tensor<Float>( [[0.9577427, -0.7377565, 0.35953724, -0.5784317]] ) let initialStateCell = Tensor<Float>( [[-0.905442, -0.95177335, -0.05345559, -1.0015926]] ) let expectedStates = Tensor<Float>( [ [ [-0.24107721, -0.17449945, 0.037506927, -0.30990827], [-0.26881245, -0.00634476, -0.019400658, -0.2071909], [-0.2842662, 0.032890536, -0.015112571, -0.13682269], [-0.31182146, 0.08775673, -0.072591506, -0.07358349], ] ] ) let expectedOutput = Tensor<Float>( [[-0.7036462, 0.19863679, -0.14904207, -0.25543863]] ) let expectedGradKernel = Tensor<Float>( [ [ 0.0805003, -0.08275342, 0.03522955, -0.030312482, 0.11720966, 0.07540316, -0.0023639323, 0.10740622, -0.2532557, -0.16903767, -0.5353516, -0.3493193, 0.016285714, 0.008904671, -0.003577555, -0.006157878, ], [ 0.08940101, -0.095668815, 0.032129567, -0.013392258, 0.17761931, 0.071601115, -0.000029361108, 0.17159097, -0.78527546, -0.5366851, -0.898436, -0.68411684, 0.05064467, 0.0044404613, 0.0010539321, 0.022477672, ], [ -0.124524735, 0.014374042, -0.065310925, 0.04207304, -0.018112179, 0.054847445, -0.0053864224, -0.044751726, 0.12626463, 0.57195514, 0.0789956, 0.21590737, 0.010621901, 0.0052103405, -0.0023645863, -0.00021189498, ], [ -0.1812453, 0.07054679, -0.08742681, 0.046577554, -0.10540785, 0.021182634, -0.002338124, -0.14174302, 0.6233163, 0.88522494, 0.5829264, 0.6225763, -0.026014743, 0.0054547004, -0.0054682456, -0.018445207, ], ] ) let expectedGradRecurrentKernel = Tensor<Float>( [ [ 0.109804794, -0.006917909, 0.06479619, -0.02927, -0.07282017, -0.06949664, -0.007851637, -0.0064141527, 0.01585731, -0.27055892, 0.18191284, -0.036890596, 0.00081066974, -0.012041213, 0.008538903, 0.004745292, ], [ -0.022427287, -0.037062988, -0.021642044, 0.009100201, 0.113654904, 0.07015832, 0.00417687, 0.073882714, -0.31279865, -0.057589047, -0.4670751, -0.2540243, 0.019137694, 0.008957855, -0.004623856, 0.005064313, ], [ 0.015348908, 0.013859384, 0.012477149, -0.0050131185, -0.050523866, -0.031698443, -0.0024695867, -0.0299116, 0.12353469, 0.012106655, 0.19668634, 0.0989304, -0.0068828184, -0.0043967483, 0.0024977797, -0.001459891, ], [ 0.024811182, -0.05493941, 0.0018467754, -0.001980858, 0.1320867, 0.06232968, 0.0034385736, 0.10646886, -0.46687102, -0.2663457, -0.5953469, -0.4029197, 0.02738668, 0.0066831633, -0.0024504992, 0.010666027, ], ] ) let expectedGradBias = Tensor<Float>( [ -0.2057409, 0.18275242, -0.07681093, 0.042995583, -0.3810982, -0.12361911, -0.008955841, -0.3550135, 1.5545796, 1.3119538, 1.8124579, 1.4128002, -0.08343395, -0.010454425, 0.0008502216, -0.038896702, ] ) let expectedGradX = Tensor<Float>( [ [ [0.21591075, 0.11293747, -0.13014226, -0.022586256], [0.08480768, 0.13718912, -0.12702335, 0.077232406], [0.01666388, 0.0068455637, -0.35854548, 0.1287557], [-0.2761167, -0.088074416, -0.415294, 0.32159615], ] ] ) let expectedGradInitialStateHidden = Tensor<Float>( [[0.25400645, 0.07120966, 0.36865664, -0.05423181]] ) let expectedGradInitialStateCell = Tensor<Float>( [[0.48873883, 0.23135301, 0.6608742, 0.37556332]] ) // END GENERATED CODE // Swaps the columns corresponding to "forget" and "update" gates. // // This translates between the keras ordering // [input | forget | update | output] // and the swift-apis ordering // [input | update | forget | output] func swapForgetUpdate(_ t: Tensor<Float>) -> Tensor<Float> { var split = t.split(count: 4, alongAxis: -1) split.swapAt(1, 2) return Tensor(concatenating: split, alongAxis: -1) } withTensorLeakChecking { var lstm = LSTM<Float>(LSTMCell(inputSize: 4, hiddenSize: 4)) lstm.cell.fusedWeight = swapForgetUpdate(Tensor(concatenating: [kernel, recurrentKernel])) lstm.cell.fusedBias = swapForgetUpdate(bias) let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialState = LSTMCell<Float>.State( cell: initialStateCell, hidden: initialStateHidden) let outputs = lstm(inputs, initialState: initialState) assertEqual( Tensor(concatenating: outputs.map { $0.hidden }), expectedStates, accuracy: 1e-6) assertEqual( outputs.last!.cell, expectedOutput, accuracy: 1e-6) let (gradLSTM, gradInputs, gradInitialState) = gradient(at: lstm, inputs, initialState) { lstm, inputs, initialState in lstm.lastOutput(from: inputs, initialState: initialState).cell.sum() } assertEqual( gradLSTM.cell.fusedWeight, swapForgetUpdate( Tensor(concatenating: [expectedGradKernel, expectedGradRecurrentKernel])), accuracy: 1e-6) assertEqual( gradLSTM.cell.fusedBias, swapForgetUpdate(expectedGradBias), accuracy: 1e-6) assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialState.cell, expectedGradInitialStateCell, accuracy: 1e-6) assertEqual( gradInitialState.hidden, expectedGradInitialStateHidden, accuracy: 1e-6) } #endif } func testBidirectionalLSTMSumMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_lstm.py --merge-mode sum". // BEGIN GENERATED CODE let kernelForward = Tensor<Float>( [[-0.23379976,-0.32979083,0.03977573,0.06884748,-0.093649775,0.34596872, -0.0076143146,0.55984896,0.22111118,-0.4210437,0.23581362,0.1825394, 0.08120936,-0.15200394,-0.08932975,0.14617139], [0.4650857,0.18167573,0.37479192,-0.46759078,-0.24752906,-0.5445049, 0.2544219,0.29843968,0.20215267,0.03678304,0.28829694,-0.5086538, -0.5053389,0.2829352,-0.36783904,-0.2113666], [-0.23447555,-0.44898528,-0.3757536,0.3030774,0.096295714,0.541732, 0.46623164,-0.4027334,-0.45229727,0.119446635,-0.36198467,0.020288646, 0.5418573,-0.3643924,-0.5106659,0.10962713]] ) let recurrentKernelForward = Tensor<Float>( [[0.22804272,-0.03794806,0.17161758,-0.5903252,-0.32132986,-0.028507836, -0.02729048,0.15502541,-0.29579595,0.041225288,-0.04219827,-0.22448958, 0.51597697,-0.103077516,0.005849608,0.14667785], [0.09507164,-0.25853005,-0.22325921,0.499246,-0.3109755,0.01945003, 0.33349884,-0.030728217,-0.2997637,0.4836203,0.035094753,-0.1599233, 0.16274704,-0.0034662904,-0.18398553,-0.06985295], [-0.13635698,-0.51163936,-0.09270489,-0.12567669,0.41930002,-0.48658654, -0.12225373,-0.28107005,-0.004303295,0.16249746,0.024185713,-0.24801093, 0.019665923,0.040028445,0.038016353,0.31107086], [0.14521983,0.63589036,0.04985115,0.17409262,0.18315184,-0.341375, -0.048293047,-0.037892636,0.08461128,0.19565175,-0.18345755,-0.12093313, 0.27880925,0.39949074,-0.1981584,0.13265577]] ) let biasForward = Tensor<Float>( [0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] ) let kernelBackward = Tensor<Float>( [[-0.3425501,0.26993138,-0.013709605,0.42182362,-0.10439563,-0.5456007, 0.23550463,-0.15115345,0.09087402,0.45050424,-0.41379565,0.050539136, 0.22132623,-0.55731493,-0.15275678,0.07351905], [-0.20979714,0.1675657,0.5581859,-0.50259715,0.4392975,-0.26118547, -0.06672484,0.26642138,-0.37113252,-0.29193833,0.5320031,0.54281443, -0.5196755,-0.013125479,0.006757021,0.5087437], [0.41886348,0.16300112,0.15921205,0.3881111,0.34322268,0.0014763474, 0.2432934,0.32898188,0.26853347,-0.48425156,-0.3587765,-0.19107765, 0.5605115,-0.18283507,0.13686264,0.008577526]] ) let recurrentKernelBackward = Tensor<Float>( [[0.332492,0.3287107,0.013327966,-0.15466748,0.18726069,-0.18434268, -0.13676699,-0.06803291,-0.55743134,0.2967973,-0.09094952,-0.12427574, -0.27146038,-0.37563083,0.15853615,0.049586363], [-0.23724489,0.016642023,-0.2502587,0.48801288,0.4526761,0.012872117, -0.0565288,-0.113935634,-0.08418312,0.2147764,0.16762011,0.058674254, 0.16494237,0.1398105,0.25171497,0.4759469], [-0.0038104642,-0.2387862,0.22545648,-0.28967497,0.5137987,-0.12194693, -0.17891966,0.33095407,-0.003036025,-0.4760634,0.06607926,-0.2880439, 0.09167388,-0.10248731,-0.025532419,0.23298186], [0.06349304,0.13959168,-0.2960539,-0.20912763,0.18433903,-0.2516703, -0.007072272,-0.09261524,0.37721395,0.09471353,-0.3878575,0.20997167, -0.18772967,0.004912289,-0.48590505,0.3492866]] ) let biasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.90076077,-0.7541278,-0.025081873], [0.37973404,-0.26513243,0.10235357], [0.3545239,-0.14615154,-0.540749], [-0.70222735,-0.34035724,-0.8451414]]] ) let initialStateHiddenForward = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialStateCellForward = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let initialStateHiddenBackward = Tensor<Float>( [[0.60601985,0.77093506,0.7210845,-0.012122989]] ) let initialStateCellBackward = Tensor<Float>( [[0.06269443,-0.80621815,0.47859335,0.13418436]] ) let expectedSum = Tensor<Float>( -0.045482513 ) let expectedStates = Tensor<Float>( [[[-0.3856787,-0.18899523,0.28026745,-0.3131796], [-0.2729215,-0.13601428,0.23670897,-0.14869213], [-0.18623777,-0.24313766,0.3612848,-0.042357195], [-0.12827212,-0.32416072,0.43230215,-0.025351819]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those four and test it. // let expectedFinalStateHiddenForward = Tensor<Float>( // [[-0.048278596,-0.028744427,0.17434421,-0.011268792]] // ) // let expectedFinalStateCellForward = Tensor<Float>( // [[-0.123089634,-0.049444646,0.27142566,-0.023337575]] // ) // let expectedFinalStateHiddenBackward = Tensor<Float>( // [[0.05788272,-0.12734284,0.03379057,-0.11494892]] // ) // let expectedFinalStateCellBackward = Tensor<Float>( // [[0.10647693,-0.207313,0.0632082,-0.31257194]] // ) let expectedGradKernelForward = Tensor<Float>( [[0.002949718,-0.05191034,0.024074148,0.00030408613,0.01421415, 0.046752453,-0.050661147,0.03154892,-0.12825678,-0.26617724,-0.16949388, -0.14972451,0.018881105,0.006620474,-0.040960394,0.0029444664], [-0.005592436,-0.019203003,0.010193658,-0.0143793905,0.036039345, 0.04006479,-0.05743648,0.042255975,-0.14608386,-0.28398836,-0.20509121, -0.21936977,0.0006449912,0.0065013315,-0.018848399,0.00052668864], [-0.030478455,-0.0063452446,-0.01916258,-0.008174095,0.03241433, 0.035240535,-0.06443699,0.008317959,-0.21671411,-0.38373917,-0.36592808, -0.2629513,0.020803409,0.012763705,-0.05019115,0.0049239537]] ) let expectedGradRecurrentKernelForward = Tensor<Float>( [[-0.009446432,0.0046872147,-0.0034881886,-0.013322812,0.028175268, 0.017745323,-0.035205625,0.023002235,-0.097775,-0.1761905,-0.15024684, -0.15604898,-0.0037074601,0.0044266693,-0.0065767397,-0.000016547507], [-0.007838752,0.00966959,-0.011096001,0.0011524474,-0.001799419, -0.0070223105,0.0018404042,-0.0133392075,-0.013871465,-0.009875648, -0.04120832,-0.0055879317,0.0054747947,0.0015693348,-0.0077096755, 0.0012488244], [0.017221574,-0.023692459,0.024221376,-0.00008906564,0.00012817048, 0.014727241,-0.0016071051,0.025199406,0.034627024,0.029167444, 0.09496009,0.025977321,-0.009273197,-0.0034023263,0.013966143, -0.0023199678], [-0.012845716,0.03203996,-0.026622673,0.0055777295,-0.015383496, -0.032603078,0.027565092,-0.04110182,0.035235237,0.10470742, 0.0075816773,0.07301342,0.007193738,0.000036919606,-0.0029361092, 0.0017134398]] ) let expectedGradBiasForward = Tensor<Float>( [0.04171711,0.0077266786,0.011825588,0.041857343,-0.10179798,-0.08539298, 0.15041551,-0.08090454,0.4313099,0.7878589,0.66939783,0.62814295, -0.005506222,-0.02124701,0.05680367,-0.0033201296] ) let expectedGradKernelBackward = Tensor<Float>( [[0.034572557,-0.014308241,-0.03773727,0.028604513,-0.0025521838, 0.04228866,-0.036268644,-0.011494972,-0.09629307,-0.12330009,-0.0996568, -0.15201326,0.033916347,0.08542741,-0.07855631,0.004139293], [0.01675671,-0.0069349525,-0.01829059,0.013864105,-0.0012369986, 0.02049657,-0.017578775,-0.0055714105,-0.04667156,-0.059761383, -0.048301898,-0.07367815,0.016438656,0.041405164,-0.03807486, 0.0020062423], [0.0416086,-0.017220188,-0.045417383,0.03442597,-0.0030715924, 0.050895054,-0.04364987,-0.013834375,-0.11589019,-0.14839356, -0.11993849,-0.18295029,0.040818844,0.1028132,-0.09454372,0.0049817027]] ) let expectedGradRecurrentKernelBackward = Tensor<Float>( [[-0.029835999,0.012347964,0.032567136,-0.024685599,0.002202526, -0.036494974,0.031299718,0.009920122,0.0831006,0.10640756,0.08600348, 0.13118693,-0.029269692,-0.07372357,0.06779383,-0.0035721958], [-0.03795522,0.015708195,0.04142958,-0.03140325,0.0028018958, -0.046426293,0.039817262,0.012619669,0.105714634,0.13536409,0.10940748, 0.16688661,-0.037234806,-0.093785845,0.08624245,-0.0045442916], [-0.035500944,0.014692465,0.038750637,-0.02937264,0.0026207182, -0.043424252,0.037242576,0.011803649,0.09887886,0.1266111,0.10233291, 0.15609531,-0.03482711,-0.087721415,0.080665804,-0.0042504463], [0.0005968476,-0.0002470121,-0.00065148197,0.00049381756,-0.00004405994, 0.00073005556,-0.0006261282,-0.00019844486,-0.0016623674,-0.0021286064, -0.0017204374,-0.0026242996,0.000585519,0.0014747867,-0.0013561664, 0.000071459195]] ) let expectedGradBiasBackward = Tensor<Float>( [-0.04923271,0.02037551,0.053739388,-0.04073398,0.0036344123,-0.060220756, 0.05164801,0.016369302,0.13712521,0.17558429,0.14191529,0.21647298, -0.04829824,-0.12165207,0.11186734,-0.0058945194] ) let expectedGradX = Tensor<Float>( [[[-0.054938864,-0.022083992,-0.004919176], [0.011244737,-0.020291347,-0.024337105], [0.017743915,0.023487188,-0.07303475], [0.11390987,0.2743578,-0.34671983]]] ) let expectedGradInitialStateHiddenForward = Tensor<Float>( [[-0.04673153,0.058627672,0.00071731675,0.035859868]] ) let expectedGradInitialStateCellForward = Tensor<Float>( [[0.09301593,0.20037422,0.123320214,0.10345342]] ) let expectedGradInitialStateHiddenBackward = Tensor<Float>( [[0.013064697,0.037812762,-0.108545646,0.01709126]] ) let expectedGradInitialStateCellBackward = Tensor<Float>( [[0.30869982,0.34445402,0.26831728,0.4068746]] ) // END GENERATED CODE // Swaps the columns corresponding to "forget" and "update" gates. // // This translates between the keras ordering // [input | forget | update | output] // and the swift-apis ordering // [input | update | forget | output] func swapForgetUpdate(_ t: Tensor<Float>) -> Tensor<Float> { var split = t.split(count: 4, alongAxis: -1) split.swapAt(1, 2) return Tensor(concatenating: split, alongAxis: -1) } withTensorLeakChecking { var lstm = BidirectionalLSTM<Float>( LSTMCell(inputSize: 3, hiddenSize: 4), mergeFunction: LSTMCell<Float>.State.sum ) lstm.forward.cell.fusedWeight = swapForgetUpdate(Tensor(concatenating: [kernelForward, recurrentKernelForward])) lstm.forward.cell.fusedBias = swapForgetUpdate(biasForward) lstm.backward.cell.fusedWeight = swapForgetUpdate(Tensor(concatenating: [kernelBackward, recurrentKernelBackward])) lstm.backward.cell.fusedBias = swapForgetUpdate(biasBackward) let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = LSTMCell<Float>.State( cell: initialStateCellForward, hidden: initialStateHiddenForward) let initialBackwardLayerState = LSTMCell<Float>.State( cell: initialStateCellBackward, hidden: initialStateHiddenBackward) let outputs = lstm( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ) assertEqual( Tensor(concatenating: outputs.map { $0.hidden }), expectedStates, accuracy: 1e-6) let (outputSum, (gradLSTM)) = valueWithGradient(at: lstm) { lstm in lstm.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).hidden.sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradLSTM.forward.cell.fusedWeight, swapForgetUpdate(Tensor(concatenating: [expectedGradKernelForward, expectedGradRecurrentKernelForward])), accuracy: 1e-6) assertEqual( gradLSTM.forward.cell.fusedBias, swapForgetUpdate(expectedGradBiasForward), accuracy: 1e-6) assertEqual( gradLSTM.backward.cell.fusedWeight, swapForgetUpdate(Tensor(concatenating: [expectedGradKernelBackward, expectedGradRecurrentKernelBackward])), accuracy: 1e-6) assertEqual( gradLSTM.backward.cell.fusedBias, swapForgetUpdate(expectedGradBiasBackward), accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in lstm.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).hidden.sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward.hidden, expectedGradInitialStateHiddenForward, accuracy: 1e-6) assertEqual( gradInitialStateForward.cell, expectedGradInitialStateCellForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward.hidden, expectedGradInitialStateHiddenBackward, accuracy: 1e-6) assertEqual( gradInitialStateBackward.cell, expectedGradInitialStateCellBackward, accuracy: 1e-6) } #endif } func testBidirectionalLSTMConcatenateMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_lstm.py --merge-mode concat". // BEGIN GENERATED CODE let kernelForward = Tensor<Float>( [[-0.23379976,-0.32979083,0.03977573,0.06884748,-0.093649775,0.34596872, -0.0076143146,0.55984896,0.22111118,-0.4210437,0.23581362,0.1825394, 0.08120936,-0.15200394,-0.08932975,0.14617139], [0.4650857,0.18167573,0.37479192,-0.46759078,-0.24752906,-0.5445049, 0.2544219,0.29843968,0.20215267,0.03678304,0.28829694,-0.5086538, -0.5053389,0.2829352,-0.36783904,-0.2113666], [-0.23447555,-0.44898528,-0.3757536,0.3030774,0.096295714,0.541732, 0.46623164,-0.4027334,-0.45229727,0.119446635,-0.36198467,0.020288646, 0.5418573,-0.3643924,-0.5106659,0.10962713]] ) let recurrentKernelForward = Tensor<Float>( [[0.22804272,-0.03794806,0.17161758,-0.5903252,-0.32132986,-0.028507836, -0.02729048,0.15502541,-0.29579595,0.041225288,-0.04219827,-0.22448958, 0.51597697,-0.103077516,0.005849608,0.14667785], [0.09507164,-0.25853005,-0.22325921,0.499246,-0.3109755,0.01945003, 0.33349884,-0.030728217,-0.2997637,0.4836203,0.035094753,-0.1599233, 0.16274704,-0.0034662904,-0.18398553,-0.06985295], [-0.13635698,-0.51163936,-0.09270489,-0.12567669,0.41930002,-0.48658654, -0.12225373,-0.28107005,-0.004303295,0.16249746,0.024185713,-0.24801093, 0.019665923,0.040028445,0.038016353,0.31107086], [0.14521983,0.63589036,0.04985115,0.17409262,0.18315184,-0.341375, -0.048293047,-0.037892636,0.08461128,0.19565175,-0.18345755,-0.12093313, 0.27880925,0.39949074,-0.1981584,0.13265577]] ) let biasForward = Tensor<Float>( [0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] ) let kernelBackward = Tensor<Float>( [[-0.3425501,0.26993138,-0.013709605,0.42182362,-0.10439563,-0.5456007, 0.23550463,-0.15115345,0.09087402,0.45050424,-0.41379565,0.050539136, 0.22132623,-0.55731493,-0.15275678,0.07351905], [-0.20979714,0.1675657,0.5581859,-0.50259715,0.4392975,-0.26118547, -0.06672484,0.26642138,-0.37113252,-0.29193833,0.5320031,0.54281443, -0.5196755,-0.013125479,0.006757021,0.5087437], [0.41886348,0.16300112,0.15921205,0.3881111,0.34322268,0.0014763474, 0.2432934,0.32898188,0.26853347,-0.48425156,-0.3587765,-0.19107765, 0.5605115,-0.18283507,0.13686264,0.008577526]] ) let recurrentKernelBackward = Tensor<Float>( [[0.332492,0.3287107,0.013327966,-0.15466748,0.18726069,-0.18434268, -0.13676699,-0.06803291,-0.55743134,0.2967973,-0.09094952,-0.12427574, -0.27146038,-0.37563083,0.15853615,0.049586363], [-0.23724489,0.016642023,-0.2502587,0.48801288,0.4526761,0.012872117, -0.0565288,-0.113935634,-0.08418312,0.2147764,0.16762011,0.058674254, 0.16494237,0.1398105,0.25171497,0.4759469], [-0.0038104642,-0.2387862,0.22545648,-0.28967497,0.5137987,-0.12194693, -0.17891966,0.33095407,-0.003036025,-0.4760634,0.06607926,-0.2880439, 0.09167388,-0.10248731,-0.025532419,0.23298186], [0.06349304,0.13959168,-0.2960539,-0.20912763,0.18433903,-0.2516703, -0.007072272,-0.09261524,0.37721395,0.09471353,-0.3878575,0.20997167, -0.18772967,0.004912289,-0.48590505,0.3492866]] ) let biasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.90076077,-0.7541278,-0.025081873], [0.37973404,-0.26513243,0.10235357], [0.3545239,-0.14615154,-0.540749], [-0.70222735,-0.34035724,-0.8451414]]] ) let initialStateHiddenForward = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialStateCellForward = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let initialStateHiddenBackward = Tensor<Float>( [[0.60601985,0.77093506,0.7210845,-0.012122989]] ) let initialStateCellBackward = Tensor<Float>( [[0.06269443,-0.80621815,0.47859335,0.13418436]] ) let expectedSum = Tensor<Float>( -0.045482457 ) let expectedStates = Tensor<Float>( [[[-0.44356138,-0.061652392,0.24647687,-0.19823068,0.05788271, -0.12734284,0.033790566,-0.11494893], [-0.2737949,-0.07248981,0.19220428,-0.08825301,0.0008733621, -0.06352448,0.044504695,-0.060439102], [-0.124358594,-0.1213435,0.21946031,-0.025490183,-0.061879173, -0.12179416,0.1418245,-0.016867002], [-0.048278596,-0.028744407,0.1743442,-0.011268781,-0.07999351, -0.29541627,0.25795794,-0.014083028]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those four and test it. // let expectedFinalStateHiddenForward = Tensor<Float>( // [[-0.048278596,-0.028744407,0.1743442,-0.011268781]] // ) // let expectedFinalStateCellForward = Tensor<Float>( // [[-0.123089634,-0.049444616,0.27142566,-0.023337554]] // ) // let expectedFinalStateHiddenBackward = Tensor<Float>( // [[0.05788271,-0.12734284,0.033790566,-0.11494893]] // ) // let expectedFinalStateCellBackward = Tensor<Float>( // [[0.106476925,-0.20731302,0.0632082,-0.31257194]] // ) let expectedGradKernelForward = Tensor<Float>( [[0.0029497184,-0.05191034,0.02407415,0.000304088,0.014214157,0.046752453, -0.050661147,0.031548906,-0.12825678,-0.26617724,-0.16949388, -0.14972453,0.018881105,0.0066204695,-0.040960398,0.002944462], [-0.005592435,-0.019203003,0.010193659,-0.014379387,0.03603935, 0.04006479,-0.05743648,0.04225596,-0.14608386,-0.28398833,-0.20509121, -0.21936974,0.00064499304,0.0065013287,-0.0188484,0.0005266868], [-0.030478455,-0.0063452474,-0.019162579,-0.008174095,0.03241433, 0.035240535,-0.06443699,0.008317955,-0.21671411,-0.38373917,-0.36592808, -0.26295128,0.020803409,0.012763699,-0.050191153,0.0049239486]] ) let expectedGradRecurrentKernelForward = Tensor<Float>( [[-0.009446431,0.0046872147,-0.0034881886,-0.013322809,0.028175268, 0.017745323,-0.035205625,0.02300223,-0.097775005,-0.17619048, -0.15024684,-0.15604895,-0.0037074587,0.0044266684,-0.006576741, -0.000016547943], [-0.007838752,0.00966959,-0.011096001,0.0011524465,-0.0017994214, -0.0070223105,0.0018404042,-0.013339203,-0.013871463,-0.009875648, -0.04120832,-0.005587943,0.0054747937,0.0015693338,-0.007709676, 0.0012488235], [0.017221576,-0.023692459,0.024221376,-0.00008906424,0.00012817606, 0.014727241,-0.0016071051,0.025199397,0.034627017,0.029167429, 0.09496009,0.025977343,-0.009273196,-0.0034023244,0.013966144, -0.0023199664], [-0.012845716,0.032039955,-0.026622673,0.0055777263,-0.0153835025, -0.032603078,0.027565094,-0.041101806,0.03523525,0.104707435, 0.0075816847,0.07301338,0.0071937367,0.000036919257,-0.0029361085, 0.0017134396]] ) let expectedGradBiasForward = Tensor<Float>( [0.041717105,0.0077266824,0.011825588,0.041857336,-0.10179798,-0.08539298, 0.15041551,-0.08090452,0.43130994,0.7878589,0.66939783,0.6281428, -0.005506225,-0.021247003,0.056803677,-0.0033201245] ) let expectedGradKernelBackward = Tensor<Float>( [[0.034572553,-0.014308241,-0.037737265,0.028604513,-0.002552184, 0.042288657,-0.036268644,-0.011494972,-0.09629306,-0.12330007, -0.09965681,-0.15201326,0.033916343,0.08542741,-0.07855631,0.004139293], [0.016756708,-0.0069349525,-0.018290589,0.013864105,-0.0012369987, 0.020496568,-0.017578775,-0.0055714105,-0.046671554,-0.059761375, -0.0483019,-0.07367815,0.016438654,0.041405164,-0.03807486,0.0020062423], [0.041608598,-0.017220188,-0.04541738,0.03442597,-0.0030715927, 0.050895046,-0.04364987,-0.013834375,-0.11589018,-0.14839353,-0.1199385, -0.18295029,0.04081884,0.10281321,-0.09454372,0.0049817027]] ) let expectedGradRecurrentKernelBackward = Tensor<Float>( [[-0.029835997,0.012347964,0.032567132,-0.024685599,0.0022025262, -0.03649497,0.031299718,0.009920122,0.08310059,0.106407546,0.08600349, 0.13118693,-0.02926969,-0.07372357,0.06779383,-0.0035721958], [-0.03795522,0.015708195,0.041429576,-0.03140325,0.0028018963, -0.046426285,0.039817262,0.012619669,0.10571462,0.13536406,0.109407485, 0.16688661,-0.0372348,-0.09378585,0.08624245,-0.0045442916], [-0.03550094,0.014692465,0.038750634,-0.02937264,0.0026207187, -0.043424245,0.037242576,0.011803649,0.098878846,0.12661108,0.10233293, 0.15609531,-0.03482711,-0.08772142,0.080665804,-0.0042504463], [0.00059684756,-0.0002470121,-0.00065148197,0.00049381756, -0.000044059943,0.00073005544,-0.0006261282,-0.00019844486, -0.0016623671,-0.002128606,-0.0017204377,-0.0026242996,0.00058551895, 0.0014747867,-0.0013561664,0.000071459195]] ) let expectedGradBiasBackward = Tensor<Float>( [-0.049232706,0.02037551,0.053739384,-0.04073398,0.0036344128,-0.06022075, 0.05164801,0.016369302,0.1371252,0.17558426,0.1419153,0.21647298, -0.048298236,-0.121652074,0.11186734,-0.0058945194] ) let expectedGradX = Tensor<Float>( [[[-0.054938864,-0.022083957,-0.004919187], [0.01124474,-0.020291314,-0.02433711], [0.017743908,0.02348721,-0.07303476], [0.113909885,0.27435783,-0.3467198]]] ) let expectedGradInitialStateHiddenForward = Tensor<Float>( [[-0.046731517,0.05862768,0.0007173242,0.035859868]] ) let expectedGradInitialStateCellForward = Tensor<Float>( [[0.09301593,0.20037422,0.123320214,0.10345338]] ) let expectedGradInitialStateHiddenBackward = Tensor<Float>( [[0.013064705,0.037812762,-0.10854563,0.017091252]] ) let expectedGradInitialStateCellBackward = Tensor<Float>( [[0.3086998,0.34445396,0.26831728,0.4068746]] ) // END GENERATED CODE // Swaps the columns corresponding to "forget" and "update" gates. // // This translates between the keras ordering // [input | forget | update | output] // and the swift-apis ordering // [input | update | forget | output] func swapForgetUpdate(_ t: Tensor<Float>) -> Tensor<Float> { var split = t.split(count: 4, alongAxis: -1) split.swapAt(1, 2) return Tensor(concatenating: split, alongAxis: -1) } withTensorLeakChecking { var lstm = BidirectionalLSTM<Float>( LSTMCell(inputSize: 3, hiddenSize: 4) ) lstm.forward.cell.fusedWeight = swapForgetUpdate(Tensor(concatenating: [kernelForward, recurrentKernelForward])) lstm.forward.cell.fusedBias = swapForgetUpdate(biasForward) lstm.backward.cell.fusedWeight = swapForgetUpdate(Tensor(concatenating: [kernelBackward, recurrentKernelBackward])) lstm.backward.cell.fusedBias = swapForgetUpdate(biasBackward) let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = LSTMCell<Float>.State( cell: initialStateCellForward, hidden: initialStateHiddenForward) let initialBackwardLayerState = LSTMCell<Float>.State( cell: initialStateCellBackward, hidden: initialStateHiddenBackward) let outputs = lstm( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ) assertEqual( Tensor(concatenating: outputs.map { $0.hidden }), expectedStates, accuracy: 1e-6) let (outputSum, (gradLSTM)) = valueWithGradient(at: lstm) { lstm in lstm.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).hidden.sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradLSTM.forward.cell.fusedWeight, swapForgetUpdate(Tensor(concatenating: [expectedGradKernelForward, expectedGradRecurrentKernelForward])), accuracy: 1e-6) assertEqual( gradLSTM.forward.cell.fusedBias, swapForgetUpdate(expectedGradBiasForward), accuracy: 1e-6) assertEqual( gradLSTM.backward.cell.fusedWeight, swapForgetUpdate(Tensor(concatenating: [expectedGradKernelBackward, expectedGradRecurrentKernelBackward])), accuracy: 1e-6) assertEqual( gradLSTM.backward.cell.fusedBias, swapForgetUpdate(expectedGradBiasBackward), accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in lstm.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).hidden.sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward.hidden, expectedGradInitialStateHiddenForward, accuracy: 1e-6) assertEqual( gradInitialStateForward.cell, expectedGradInitialStateCellForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward.hidden, expectedGradInitialStateHiddenBackward, accuracy: 1e-6) assertEqual( gradInitialStateBackward.cell, expectedGradInitialStateCellBackward, accuracy: 1e-6) } #endif } func testBidirectionalLSTMAverageMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_lstm.py --merge-mode ave". // BEGIN GENERATED CODE let kernelForward = Tensor<Float>( [[-0.23379976,-0.32979083,0.03977573,0.06884748,-0.093649775,0.34596872, -0.0076143146,0.55984896,0.22111118,-0.4210437,0.23581362,0.1825394, 0.08120936,-0.15200394,-0.08932975,0.14617139], [0.4650857,0.18167573,0.37479192,-0.46759078,-0.24752906,-0.5445049, 0.2544219,0.29843968,0.20215267,0.03678304,0.28829694,-0.5086538, -0.5053389,0.2829352,-0.36783904,-0.2113666], [-0.23447555,-0.44898528,-0.3757536,0.3030774,0.096295714,0.541732, 0.46623164,-0.4027334,-0.45229727,0.119446635,-0.36198467,0.020288646, 0.5418573,-0.3643924,-0.5106659,0.10962713]] ) let recurrentKernelForward = Tensor<Float>( [[0.22804272,-0.03794806,0.17161758,-0.5903252,-0.32132986,-0.028507836, -0.02729048,0.15502541,-0.29579595,0.041225288,-0.04219827,-0.22448958, 0.51597697,-0.103077516,0.005849608,0.14667785], [0.09507164,-0.25853005,-0.22325921,0.499246,-0.3109755,0.01945003, 0.33349884,-0.030728217,-0.2997637,0.4836203,0.035094753,-0.1599233, 0.16274704,-0.0034662904,-0.18398553,-0.06985295], [-0.13635698,-0.51163936,-0.09270489,-0.12567669,0.41930002,-0.48658654, -0.12225373,-0.28107005,-0.004303295,0.16249746,0.024185713,-0.24801093, 0.019665923,0.040028445,0.038016353,0.31107086], [0.14521983,0.63589036,0.04985115,0.17409262,0.18315184,-0.341375, -0.048293047,-0.037892636,0.08461128,0.19565175,-0.18345755,-0.12093313, 0.27880925,0.39949074,-0.1981584,0.13265577]] ) let biasForward = Tensor<Float>( [0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] ) let kernelBackward = Tensor<Float>( [[-0.3425501,0.26993138,-0.013709605,0.42182362,-0.10439563,-0.5456007, 0.23550463,-0.15115345,0.09087402,0.45050424,-0.41379565,0.050539136, 0.22132623,-0.55731493,-0.15275678,0.07351905], [-0.20979714,0.1675657,0.5581859,-0.50259715,0.4392975,-0.26118547, -0.06672484,0.26642138,-0.37113252,-0.29193833,0.5320031,0.54281443, -0.5196755,-0.013125479,0.006757021,0.5087437], [0.41886348,0.16300112,0.15921205,0.3881111,0.34322268,0.0014763474, 0.2432934,0.32898188,0.26853347,-0.48425156,-0.3587765,-0.19107765, 0.5605115,-0.18283507,0.13686264,0.008577526]] ) let recurrentKernelBackward = Tensor<Float>( [[0.332492,0.3287107,0.013327966,-0.15466748,0.18726069,-0.18434268, -0.13676699,-0.06803291,-0.55743134,0.2967973,-0.09094952,-0.12427574, -0.27146038,-0.37563083,0.15853615,0.049586363], [-0.23724489,0.016642023,-0.2502587,0.48801288,0.4526761,0.012872117, -0.0565288,-0.113935634,-0.08418312,0.2147764,0.16762011,0.058674254, 0.16494237,0.1398105,0.25171497,0.4759469], [-0.0038104642,-0.2387862,0.22545648,-0.28967497,0.5137987,-0.12194693, -0.17891966,0.33095407,-0.003036025,-0.4760634,0.06607926,-0.2880439, 0.09167388,-0.10248731,-0.025532419,0.23298186], [0.06349304,0.13959168,-0.2960539,-0.20912763,0.18433903,-0.2516703, -0.007072272,-0.09261524,0.37721395,0.09471353,-0.3878575,0.20997167, -0.18772967,0.004912289,-0.48590505,0.3492866]] ) let biasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.90076077,-0.7541278,-0.025081873], [0.37973404,-0.26513243,0.10235357], [0.3545239,-0.14615154,-0.540749], [-0.70222735,-0.34035724,-0.8451414]]] ) let initialStateHiddenForward = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialStateCellForward = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let initialStateHiddenBackward = Tensor<Float>( [[0.60601985,0.77093506,0.7210845,-0.012122989]] ) let initialStateCellBackward = Tensor<Float>( [[0.06269443,-0.80621815,0.47859335,0.13418436]] ) let expectedSum = Tensor<Float>( -0.02274122 ) let expectedStates = Tensor<Float>( [[[-0.19283932,-0.09449761,0.14013372,-0.1565898], [-0.13646077,-0.06800714,0.118354484,-0.07434605], [-0.09311888,-0.12156883,0.1806424,-0.021178592], [-0.06413605,-0.16208033,0.21615106,-0.012675904]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those four and test it. // let expectedFinalStateHiddenForward = Tensor<Float>( // [[-0.048278596,-0.028744407,0.1743442,-0.011268781]] // ) // let expectedFinalStateCellForward = Tensor<Float>( // [[-0.123089634,-0.049444616,0.27142566,-0.023337554]] // ) // let expectedFinalStateHiddenBackward = Tensor<Float>( // [[0.05788271,-0.12734284,0.033790566,-0.11494893]] // ) // let expectedFinalStateCellBackward = Tensor<Float>( // [[0.106476925,-0.20731302,0.0632082,-0.31257194]] // ) let expectedGradKernelForward = Tensor<Float>( [[0.0014748592,-0.02595517,0.012037075,0.000152044,0.0071070786, 0.023376226,-0.025330573,0.015774453,-0.06412839,-0.13308862, -0.08474694,-0.074862264,0.009440552,0.0033102348,-0.020480199, 0.001472231], [-0.0027962176,-0.009601502,0.0050968295,-0.0071896934,0.018019674, 0.020032395,-0.02871824,0.02112798,-0.07304193,-0.14199416,-0.102545604, -0.10968487,0.00032249652,0.0032506643,-0.0094242,0.0002633434], [-0.015239228,-0.0031726237,-0.009581289,-0.0040870477,0.016207164, 0.017620267,-0.032218494,0.0041589774,-0.10835706,-0.19186959, -0.18296404,-0.13147564,0.010401704,0.0063818493,-0.025095576, 0.0024619743]] ) let expectedGradRecurrentKernelForward = Tensor<Float>( [[-0.0047232155,0.0023436074,-0.0017440943,-0.0066614044,0.014087634, 0.008872662,-0.017602812,0.011501115,-0.048887502,-0.08809524, -0.07512342,-0.07802448,-0.0018537294,0.0022133342,-0.0032883706, -0.000008273972], [-0.003919376,0.004834795,-0.0055480003,0.00057622325,-0.0008997107, -0.0035111553,0.0009202021,-0.0066696014,-0.0069357315,-0.004937824, -0.02060416,-0.0027939714,0.0027373969,0.0007846669,-0.003854838, 0.00062441174], [0.008610788,-0.011846229,0.012110688,-0.00004453212,0.00006408803, 0.0073636207,-0.00080355257,0.012599698,0.017313508,0.014583714, 0.047480047,0.012988672,-0.004636598,-0.0017011622,0.006983072, -0.0011599832], [-0.006422858,0.016019978,-0.013311337,0.0027888631,-0.0076917512, -0.016301539,0.013782547,-0.020550903,0.017617624,0.052353717, 0.0037908424,0.03650669,0.0035968684,0.000018459628,-0.0014680543, 0.0008567198]] ) let expectedGradBiasForward = Tensor<Float>( [0.020858552,0.0038633412,0.005912794,0.020928668,-0.05089899,-0.04269649, 0.075207755,-0.04045226,0.21565497,0.39392945,0.33469892,0.3140714, -0.0027531125,-0.010623502,0.028401839,-0.0016600622] ) let expectedGradKernelBackward = Tensor<Float>( [[0.017286276,-0.0071541206,-0.018868633,0.0143022565,-0.001276092, 0.021144329,-0.018134322,-0.005747486,-0.04814653,-0.061650034, -0.049828406,-0.07600663,0.016958172,0.042713705,-0.039278153, 0.0020696465], [0.008378354,-0.0034674762,-0.009145294,0.0069320523,-0.00061849935, 0.010248284,-0.0087893875,-0.0027857053,-0.023335777,-0.029880688, -0.02415095,-0.036839075,0.008219327,0.020702582,-0.01903743, 0.0010031211], [0.020804299,-0.008610094,-0.02270869,0.017212985,-0.0015357963, 0.025447523,-0.021824935,-0.0069171875,-0.05794509,-0.07419676, -0.05996925,-0.091475144,0.02040942,0.051406603,-0.04727186, 0.0024908513]] ) let expectedGradRecurrentKernelBackward = Tensor<Float>( [[-0.014917999,0.006173982,0.016283566,-0.012342799,0.0011012631, -0.018247485,0.015649859,0.004960061,0.041550294,0.053203773, 0.043001745,0.065593466,-0.014634845,-0.036861785,0.033896916, -0.0017860979], [-0.01897761,0.0078540975,0.020714788,-0.015701625,0.0014009482, -0.023213143,0.019908631,0.0063098343,0.05285731,0.06768203,0.054703742, 0.08344331,-0.0186174,-0.046892926,0.043121226,-0.0022721458], [-0.01775047,0.0073462324,0.019375317,-0.01468632,0.0013103593, -0.021712122,0.018621288,0.0059018247,0.049439423,0.06330554, 0.051166464,0.078047656,-0.017413555,-0.04386071,0.040332902, -0.0021252232], [0.00029842378,-0.00012350605,-0.00032574098,0.00024690878, -0.000022029972,0.00036502772,-0.0003130641,-0.00009922243, -0.00083118357,-0.001064303,-0.00086021883,-0.0013121498,0.00029275948, 0.00073739333,-0.0006780832,0.000035729598]] ) let expectedGradBiasBackward = Tensor<Float>( [-0.024616353,0.010187755,0.026869692,-0.02036699,0.0018172064, -0.030110374,0.025824005,0.008184651,0.0685626,0.08779213,0.07095765, 0.10823649,-0.024149118,-0.060826037,0.05593367,-0.0029472597] ) let expectedGradX = Tensor<Float>( [[[-0.027469432,-0.011041978,-0.0024595936], [0.00562237,-0.010145657,-0.012168555], [0.008871954,0.011743605,-0.03651738], [0.056954943,0.13717891,-0.1733599]]] ) let expectedGradInitialStateHiddenForward = Tensor<Float>( [[-0.023365758,0.02931384,0.0003586621,0.017929934]] ) let expectedGradInitialStateCellForward = Tensor<Float>( [[0.046507966,0.10018711,0.061660107,0.05172669]] ) let expectedGradInitialStateHiddenBackward = Tensor<Float>( [[0.0065323524,0.018906381,-0.054272816,0.008545626]] ) let expectedGradInitialStateCellBackward = Tensor<Float>( [[0.1543499,0.17222698,0.13415864,0.2034373]] ) // END GENERATED CODE // Swaps the columns corresponding to "forget" and "update" gates. // // This translates between the keras ordering // [input | forget | update | output] // and the swift-apis ordering // [input | update | forget | output] func swapForgetUpdate(_ t: Tensor<Float>) -> Tensor<Float> { var split = t.split(count: 4, alongAxis: -1) split.swapAt(1, 2) return Tensor(concatenating: split, alongAxis: -1) } withTensorLeakChecking { var lstm = BidirectionalLSTM<Float>( LSTMCell(inputSize: 3, hiddenSize: 4), mergeFunction: LSTMCell<Float>.State.average ) lstm.forward.cell.fusedWeight = swapForgetUpdate(Tensor(concatenating: [kernelForward, recurrentKernelForward])) lstm.forward.cell.fusedBias = swapForgetUpdate(biasForward) lstm.backward.cell.fusedWeight = swapForgetUpdate(Tensor(concatenating: [kernelBackward, recurrentKernelBackward])) lstm.backward.cell.fusedBias = swapForgetUpdate(biasBackward) let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = LSTMCell<Float>.State( cell: initialStateCellForward, hidden: initialStateHiddenForward) let initialBackwardLayerState = LSTMCell<Float>.State( cell: initialStateCellBackward, hidden: initialStateHiddenBackward) let outputs = lstm( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ) assertEqual( Tensor(concatenating: outputs.map { $0.hidden }), expectedStates, accuracy: 1e-6) let (outputSum, (gradLSTM)) = valueWithGradient(at: lstm) { lstm in lstm.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).hidden.sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradLSTM.forward.cell.fusedWeight, swapForgetUpdate(Tensor(concatenating: [expectedGradKernelForward, expectedGradRecurrentKernelForward])), accuracy: 1e-6) assertEqual( gradLSTM.forward.cell.fusedBias, swapForgetUpdate(expectedGradBiasForward), accuracy: 1e-6) assertEqual( gradLSTM.backward.cell.fusedWeight, swapForgetUpdate(Tensor(concatenating: [expectedGradKernelBackward, expectedGradRecurrentKernelBackward])), accuracy: 1e-6) assertEqual( gradLSTM.backward.cell.fusedBias, swapForgetUpdate(expectedGradBiasBackward), accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in lstm.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).hidden.sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward.hidden, expectedGradInitialStateHiddenForward, accuracy: 1e-6) assertEqual( gradInitialStateForward.cell, expectedGradInitialStateCellForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward.hidden, expectedGradInitialStateHiddenBackward, accuracy: 1e-6) assertEqual( gradInitialStateBackward.cell, expectedGradInitialStateCellBackward, accuracy: 1e-6) } #endif } func testBidirectionalLSTMMultiplyMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_lstm.py --merge-mode mul". // BEGIN GENERATED CODE let kernelForward = Tensor<Float>( [[-0.23379976,-0.32979083,0.03977573,0.06884748,-0.093649775,0.34596872, -0.0076143146,0.55984896,0.22111118,-0.4210437,0.23581362,0.1825394, 0.08120936,-0.15200394,-0.08932975,0.14617139], [0.4650857,0.18167573,0.37479192,-0.46759078,-0.24752906,-0.5445049, 0.2544219,0.29843968,0.20215267,0.03678304,0.28829694,-0.5086538, -0.5053389,0.2829352,-0.36783904,-0.2113666], [-0.23447555,-0.44898528,-0.3757536,0.3030774,0.096295714,0.541732, 0.46623164,-0.4027334,-0.45229727,0.119446635,-0.36198467,0.020288646, 0.5418573,-0.3643924,-0.5106659,0.10962713]] ) let recurrentKernelForward = Tensor<Float>( [[0.22804272,-0.03794806,0.17161758,-0.5903252,-0.32132986,-0.028507836, -0.02729048,0.15502541,-0.29579595,0.041225288,-0.04219827,-0.22448958, 0.51597697,-0.103077516,0.005849608,0.14667785], [0.09507164,-0.25853005,-0.22325921,0.499246,-0.3109755,0.01945003, 0.33349884,-0.030728217,-0.2997637,0.4836203,0.035094753,-0.1599233, 0.16274704,-0.0034662904,-0.18398553,-0.06985295], [-0.13635698,-0.51163936,-0.09270489,-0.12567669,0.41930002,-0.48658654, -0.12225373,-0.28107005,-0.004303295,0.16249746,0.024185713,-0.24801093, 0.019665923,0.040028445,0.038016353,0.31107086], [0.14521983,0.63589036,0.04985115,0.17409262,0.18315184,-0.341375, -0.048293047,-0.037892636,0.08461128,0.19565175,-0.18345755,-0.12093313, 0.27880925,0.39949074,-0.1981584,0.13265577]] ) let biasForward = Tensor<Float>( [0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] ) let kernelBackward = Tensor<Float>( [[-0.3425501,0.26993138,-0.013709605,0.42182362,-0.10439563,-0.5456007, 0.23550463,-0.15115345,0.09087402,0.45050424,-0.41379565,0.050539136, 0.22132623,-0.55731493,-0.15275678,0.07351905], [-0.20979714,0.1675657,0.5581859,-0.50259715,0.4392975,-0.26118547, -0.06672484,0.26642138,-0.37113252,-0.29193833,0.5320031,0.54281443, -0.5196755,-0.013125479,0.006757021,0.5087437], [0.41886348,0.16300112,0.15921205,0.3881111,0.34322268,0.0014763474, 0.2432934,0.32898188,0.26853347,-0.48425156,-0.3587765,-0.19107765, 0.5605115,-0.18283507,0.13686264,0.008577526]] ) let recurrentKernelBackward = Tensor<Float>( [[0.332492,0.3287107,0.013327966,-0.15466748,0.18726069,-0.18434268, -0.13676699,-0.06803291,-0.55743134,0.2967973,-0.09094952,-0.12427574, -0.27146038,-0.37563083,0.15853615,0.049586363], [-0.23724489,0.016642023,-0.2502587,0.48801288,0.4526761,0.012872117, -0.0565288,-0.113935634,-0.08418312,0.2147764,0.16762011,0.058674254, 0.16494237,0.1398105,0.25171497,0.4759469], [-0.0038104642,-0.2387862,0.22545648,-0.28967497,0.5137987,-0.12194693, -0.17891966,0.33095407,-0.003036025,-0.4760634,0.06607926,-0.2880439, 0.09167388,-0.10248731,-0.025532419,0.23298186], [0.06349304,0.13959168,-0.2960539,-0.20912763,0.18433903,-0.2516703, -0.007072272,-0.09261524,0.37721395,0.09471353,-0.3878575,0.20997167, -0.18772967,0.004912289,-0.48590505,0.3492866]] ) let biasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.90076077,-0.7541278,-0.025081873], [0.37973404,-0.26513243,0.10235357], [0.3545239,-0.14615154,-0.540749], [-0.70222735,-0.34035724,-0.8451414]]] ) let initialStateHiddenForward = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialStateCellForward = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let initialStateHiddenBackward = Tensor<Float>( [[0.60601985,0.77093506,0.7210845,-0.012122989]] ) let initialStateCellBackward = Tensor<Float>( [[0.06269443,-0.80621815,0.47859335,0.13418436]] ) let expectedSum = Tensor<Float>( 0.057485707 ) let expectedStates = Tensor<Float>( [[[-0.025674535,0.007850991,0.008328593,0.022786405], [-0.00023912209,0.0046048774,0.008553993,0.0053339326], [0.007695207,0.01477893,0.031124849,0.000429943], [0.0038619742,0.0084915655,0.04497347,0.00015869855]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those four and test it. // let expectedFinalStateHiddenForward = Tensor<Float>( // [[-0.048278596,-0.028744407,0.1743442,-0.011268781]] // ) // let expectedFinalStateCellForward = Tensor<Float>( // [[-0.123089634,-0.049444616,0.27142566,-0.023337554]] // ) // let expectedFinalStateHiddenBackward = Tensor<Float>( // [[0.05788271,-0.12734284,0.033790566,-0.11494893]] // ) // let expectedFinalStateCellBackward = Tensor<Float>( // [[0.106476925,-0.20731302,0.0632082,-0.31257194]] // ) let expectedGradKernelForward = Tensor<Float>( [[-0.0006356439,0.015833925,0.005248367,0.000088096946,-0.001286473, -0.014080829,-0.012435054,-0.0042246087,0.010528095,0.0785853, -0.04466948,0.005445134,-0.0011754832,-0.0016675827,-0.011209748, -0.00035536994], [0.00035326666,0.005798911,0.0020744896,0.0016610449,-0.0035952562, -0.012197385,-0.013497299,-0.0053806542,0.013618026,0.08609101, -0.04995886,0.018841323,-0.0003639532,-0.0020185974,-0.0043832674, -0.0008603267], [0.002633221,0.00171838,-0.004717764,0.00048049382,-0.0028204727, -0.010515593,-0.016336953,-0.00037660176,0.018144649,0.114633985, -0.09280567,0.008752153,-0.0020848382,-0.0041145375,-0.01230508, -0.00033673478]] ) let expectedGradRecurrentKernelForward = Tensor<Float>( [[0.00085955136,-0.0015130613,-0.0009309999,0.0014424899,-0.0028096742, -0.005426242,-0.008224582,-0.0027340245,0.009384694,0.053980358, -0.035707016,0.014470998,-0.00012773072,-0.0015185195,-0.0009792406, -0.00059664843], [0.00075029954,-0.0030118634,-0.0025134794,-0.00027205143,0.00029734446, 0.0022050086,0.00009390758,0.0019716173,0.0007304535,0.0025818497, -0.010839711,-0.0033222511,-0.0004790762,-0.0005259809,-0.0018902641, 0.0002027992], [-0.0016653631,0.007366645,0.0054886946,0.0003065939,-0.00023920857, -0.004606634,0.00025729695,-0.0038056956,-0.0022326056,-0.008233182, 0.024358716,0.0047218287,0.0009058922,0.0011722009,0.0032562078, -0.00033911638], [0.001339203,-0.009877648,-0.0059118806,-0.00090225495,0.0017254684, 0.0100316,0.005946205,0.005787832,-0.004097135,-0.032188937,0.000986672, -0.01200073,-0.0005991369,-0.000113752816,-0.00061858393,0.0006727869]] ) let expectedGradBiasForward = Tensor<Float>( [-0.0036032305,-0.0020163525,0.0033609606,-0.004352904,0.009900483, 0.02591736,0.035977,0.009494458,-0.039504252,-0.23896675,0.1634979, -0.0476815,0.0017783717,0.006988898,0.012471562,0.0020117098] ) let expectedGradKernelBackward = Tensor<Float>( [[-0.0016691145,0.00041128194,-0.0065792724,-0.00032233805,0.00012321587, -0.0012155625,-0.0063232277,0.00012953431,0.004648894,0.0035441876, -0.017374588,0.0017130041,-0.0016374333,-0.0024555605,-0.013695836, -0.000046644785], [-0.0008089904,0.00019934113,-0.0031888576,-0.00015623159,0.00005972056, -0.0005891617,-0.0030647572,0.000062783,0.0022532372,0.0017178054, -0.008421157,0.0008302629,-0.00079363515,-0.0011901669,-0.006638131, -0.000022607906], [-0.0020088048,0.00049498415,-0.007918255,-0.0003879388,0.00014829218, -0.001462948,-0.0076101017,0.00015589653,0.005595016,0.0042654844, -0.020910583,0.0020616266,-0.0019706762,-0.0029553047,-0.01648315, -0.000056137716]] ) let expectedGradRecurrentKernelBackward = Tensor<Float>( [[0.0014404402,-0.00035493495,0.00567789,0.00027817665,-0.000106334875, 0.0010490263,0.0054569244,-0.000111787675,-0.0040119803,-0.003058622, 0.014994211,-0.0014783167,0.0014130995,0.0021191405,0.011819461, 0.000040254294], [0.0018324248,-0.00045152282,0.0072230054,0.0003538764,-0.00013527162, 0.0013344962,0.006941908,-0.00014220827,-0.005103754,-0.0038909598, 0.019074561,-0.0018806087,0.001797644,0.0026958187,0.015035871, 0.00005120863], [0.0017139356,-0.00042232624,0.0067559476,0.0003309939,-0.00012652461, 0.0012482043,0.0064930273,-0.00013301274,-0.0047737323,-0.0036393607, 0.017841153,-0.0017590038,0.0016814038,0.0025215005,0.014063614, 0.000047897352], [-0.000028814964,0.000007100217,-0.000113582086,-0.000005564723, 0.0000021271524,-0.000020985013,-0.000109161825,0.0000022362317, 0.00008025676,0.00006118552,-0.00029994833,0.000029572657, -0.000028268032,-0.000042391872,-0.00023643977,-0.000000805258]] ) let expectedGradBiasBackward = Tensor<Float>( [0.002376886,-0.00058568205,0.009369149,0.00045902235,-0.00017546435, 0.0017310098,0.0090045305,-0.00018446207,-0.0066202125,-0.0050470657, 0.024742112,-0.0024393867,0.002331771,0.0034968168,0.019503422, 0.00006642405] ) let expectedGradX = Tensor<Float>( [[[0.025954716,0.0037635816,0.005093654], [0.016548203,0.014938684,-0.0098211765], [0.028925406,0.018546272,-0.017679248], [0.045659292,0.028008066,-0.028804896]]] ) let expectedGradInitialStateHiddenForward = Tensor<Float>( [[0.002969412,-0.012251236,-0.0049122106,-0.018355861]] ) let expectedGradInitialStateCellForward = Tensor<Float>( [[-0.010009506,-0.061632644,0.027160529,-0.014186442]] ) let expectedGradInitialStateHiddenBackward = Tensor<Float>( [[0.00047474913,0.006052384,0.0042700856,-0.026273249]] ) let expectedGradInitialStateCellBackward = Tensor<Float>( [[-0.014903592,-0.009901126,0.046779558,-0.0045849807]] ) // END GENERATED CODE // Swaps the columns corresponding to "forget" and "update" gates. // // This translates between the keras ordering // [input | forget | update | output] // and the swift-apis ordering // [input | update | forget | output] func swapForgetUpdate(_ t: Tensor<Float>) -> Tensor<Float> { var split = t.split(count: 4, alongAxis: -1) split.swapAt(1, 2) return Tensor(concatenating: split, alongAxis: -1) } withTensorLeakChecking { var lstm = BidirectionalLSTM<Float>( LSTMCell(inputSize: 3, hiddenSize: 4), mergeFunction: LSTMCell<Float>.State.multiply ) lstm.forward.cell.fusedWeight = swapForgetUpdate(Tensor(concatenating: [kernelForward, recurrentKernelForward])) lstm.forward.cell.fusedBias = swapForgetUpdate(biasForward) lstm.backward.cell.fusedWeight = swapForgetUpdate(Tensor(concatenating: [kernelBackward, recurrentKernelBackward])) lstm.backward.cell.fusedBias = swapForgetUpdate(biasBackward) let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = LSTMCell<Float>.State( cell: initialStateCellForward, hidden: initialStateHiddenForward) let initialBackwardLayerState = LSTMCell<Float>.State( cell: initialStateCellBackward, hidden: initialStateHiddenBackward) let outputs = lstm( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ) assertEqual( Tensor(concatenating: outputs.map { $0.hidden }), expectedStates, accuracy: 1e-6) let (outputSum, (gradLSTM)) = valueWithGradient(at: lstm) { lstm in lstm.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).hidden.sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradLSTM.forward.cell.fusedWeight, swapForgetUpdate(Tensor(concatenating: [expectedGradKernelForward, expectedGradRecurrentKernelForward])), accuracy: 1e-6) assertEqual( gradLSTM.forward.cell.fusedBias, swapForgetUpdate(expectedGradBiasForward), accuracy: 1e-6) assertEqual( gradLSTM.backward.cell.fusedWeight, swapForgetUpdate(Tensor(concatenating: [expectedGradKernelBackward, expectedGradRecurrentKernelBackward])), accuracy: 1e-6) assertEqual( gradLSTM.backward.cell.fusedBias, swapForgetUpdate(expectedGradBiasBackward), accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in lstm.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).hidden.sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward.hidden, expectedGradInitialStateHiddenForward, accuracy: 1e-6) assertEqual( gradInitialStateForward.cell, expectedGradInitialStateCellForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward.hidden, expectedGradInitialStateHiddenBackward, accuracy: 1e-6) assertEqual( gradInitialStateBackward.cell, expectedGradInitialStateCellBackward, accuracy: 1e-6) } #endif } func testBidirectionalLSTMStackMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_lstm.py --merge-mode none". // BEGIN GENERATED CODE let kernelForward = Tensor<Float>( [[-0.23379976,-0.32979083,0.03977573,0.06884748,-0.093649775,0.34596872, -0.0076143146,0.55984896,0.22111118,-0.4210437,0.23581362,0.1825394, 0.08120936,-0.15200394,-0.08932975,0.14617139], [0.4650857,0.18167573,0.37479192,-0.46759078,-0.24752906,-0.5445049, 0.2544219,0.29843968,0.20215267,0.03678304,0.28829694,-0.5086538, -0.5053389,0.2829352,-0.36783904,-0.2113666], [-0.23447555,-0.44898528,-0.3757536,0.3030774,0.096295714,0.541732, 0.46623164,-0.4027334,-0.45229727,0.119446635,-0.36198467,0.020288646, 0.5418573,-0.3643924,-0.5106659,0.10962713]] ) let recurrentKernelForward = Tensor<Float>( [[0.22804272,-0.03794806,0.17161758,-0.5903252,-0.32132986,-0.028507836, -0.02729048,0.15502541,-0.29579595,0.041225288,-0.04219827,-0.22448958, 0.51597697,-0.103077516,0.005849608,0.14667785], [0.09507164,-0.25853005,-0.22325921,0.499246,-0.3109755,0.01945003, 0.33349884,-0.030728217,-0.2997637,0.4836203,0.035094753,-0.1599233, 0.16274704,-0.0034662904,-0.18398553,-0.06985295], [-0.13635698,-0.51163936,-0.09270489,-0.12567669,0.41930002,-0.48658654, -0.12225373,-0.28107005,-0.004303295,0.16249746,0.024185713,-0.24801093, 0.019665923,0.040028445,0.038016353,0.31107086], [0.14521983,0.63589036,0.04985115,0.17409262,0.18315184,-0.341375, -0.048293047,-0.037892636,0.08461128,0.19565175,-0.18345755,-0.12093313, 0.27880925,0.39949074,-0.1981584,0.13265577]] ) let biasForward = Tensor<Float>( [0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] ) let kernelBackward = Tensor<Float>( [[-0.3425501,0.26993138,-0.013709605,0.42182362,-0.10439563,-0.5456007, 0.23550463,-0.15115345,0.09087402,0.45050424,-0.41379565,0.050539136, 0.22132623,-0.55731493,-0.15275678,0.07351905], [-0.20979714,0.1675657,0.5581859,-0.50259715,0.4392975,-0.26118547, -0.06672484,0.26642138,-0.37113252,-0.29193833,0.5320031,0.54281443, -0.5196755,-0.013125479,0.006757021,0.5087437], [0.41886348,0.16300112,0.15921205,0.3881111,0.34322268,0.0014763474, 0.2432934,0.32898188,0.26853347,-0.48425156,-0.3587765,-0.19107765, 0.5605115,-0.18283507,0.13686264,0.008577526]] ) let recurrentKernelBackward = Tensor<Float>( [[0.332492,0.3287107,0.013327966,-0.15466748,0.18726069,-0.18434268, -0.13676699,-0.06803291,-0.55743134,0.2967973,-0.09094952,-0.12427574, -0.27146038,-0.37563083,0.15853615,0.049586363], [-0.23724489,0.016642023,-0.2502587,0.48801288,0.4526761,0.012872117, -0.0565288,-0.113935634,-0.08418312,0.2147764,0.16762011,0.058674254, 0.16494237,0.1398105,0.25171497,0.4759469], [-0.0038104642,-0.2387862,0.22545648,-0.28967497,0.5137987,-0.12194693, -0.17891966,0.33095407,-0.003036025,-0.4760634,0.06607926,-0.2880439, 0.09167388,-0.10248731,-0.025532419,0.23298186], [0.06349304,0.13959168,-0.2960539,-0.20912763,0.18433903,-0.2516703, -0.007072272,-0.09261524,0.37721395,0.09471353,-0.3878575,0.20997167, -0.18772967,0.004912289,-0.48590505,0.3492866]] ) let biasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.90076077,-0.7541278,-0.025081873], [0.37973404,-0.26513243,0.10235357], [0.3545239,-0.14615154,-0.540749], [-0.70222735,-0.34035724,-0.8451414]]] ) let initialStateHiddenForward = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialStateCellForward = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let initialStateHiddenBackward = Tensor<Float>( [[0.60601985,0.77093506,0.7210845,-0.012122989]] ) let initialStateCellBackward = Tensor<Float>( [[0.06269443,-0.80621815,0.47859335,0.13418436]] ) let expectedSum = Tensor<Float>( -0.045482457 ) let expectedStatesForward = Tensor<Float>( [[[-0.44356138,-0.061652392,0.24647687,-0.19823068], [-0.2737949,-0.07248981,0.19220428,-0.08825301], [-0.124358594,-0.1213435,0.21946031,-0.025490183], [-0.048278596,-0.028744407,0.1743442,-0.011268781]]] ) let expectedStatesBackward = Tensor<Float>( [[[0.05788271,-0.12734284,0.033790566,-0.11494893], [0.0008733621,-0.06352448,0.044504695,-0.060439102], [-0.061879173,-0.12179416,0.1418245,-0.016867002], [-0.07999351,-0.29541627,0.25795794,-0.014083028]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those four and test it. // let expectedFinalStateHiddenForward = Tensor<Float>( // [[-0.048278596,-0.028744407,0.1743442,-0.011268781]] // ) // let expectedFinalStateCellForward = Tensor<Float>( // [[-0.123089634,-0.049444616,0.27142566,-0.023337554]] // ) // let expectedFinalStateHiddenBackward = Tensor<Float>( // [[0.05788271,-0.12734284,0.033790566,-0.11494893]] // ) // let expectedFinalStateCellBackward = Tensor<Float>( // [[0.106476925,-0.20731302,0.0632082,-0.31257194]] // ) let expectedGradKernelForward = Tensor<Float>( [[0.0029497184,-0.05191034,0.02407415,0.000304088,0.014214157,0.046752453, -0.050661147,0.031548906,-0.12825678,-0.26617724,-0.16949388, -0.14972453,0.018881105,0.0066204695,-0.040960398,0.002944462], [-0.005592435,-0.019203003,0.010193659,-0.014379387,0.03603935, 0.04006479,-0.05743648,0.04225596,-0.14608386,-0.28398833,-0.20509121, -0.21936974,0.00064499304,0.0065013287,-0.0188484,0.0005266868], [-0.030478455,-0.0063452474,-0.019162579,-0.008174095,0.03241433, 0.035240535,-0.06443699,0.008317955,-0.21671411,-0.38373917,-0.36592808, -0.26295128,0.020803409,0.012763699,-0.050191153,0.0049239486]] ) let expectedGradRecurrentKernelForward = Tensor<Float>( [[-0.009446431,0.0046872147,-0.0034881886,-0.013322809,0.028175268, 0.017745323,-0.035205625,0.02300223,-0.097775005,-0.17619048, -0.15024684,-0.15604895,-0.0037074587,0.0044266684,-0.006576741, -0.000016547943], [-0.007838752,0.00966959,-0.011096001,0.0011524465,-0.0017994214, -0.0070223105,0.0018404042,-0.013339203,-0.013871463,-0.009875648, -0.04120832,-0.005587943,0.0054747937,0.0015693338,-0.007709676, 0.0012488235], [0.017221576,-0.023692459,0.024221376,-0.00008906424,0.00012817606, 0.014727241,-0.0016071051,0.025199397,0.034627017,0.029167429, 0.09496009,0.025977343,-0.009273196,-0.0034023244,0.013966144, -0.0023199664], [-0.012845716,0.032039955,-0.026622673,0.0055777263,-0.0153835025, -0.032603078,0.027565094,-0.041101806,0.03523525,0.104707435, 0.0075816847,0.07301338,0.0071937367,0.000036919257,-0.0029361085, 0.0017134396]] ) let expectedGradBiasForward = Tensor<Float>( [0.041717105,0.0077266824,0.011825588,0.041857336,-0.10179798,-0.08539298, 0.15041551,-0.08090452,0.43130994,0.7878589,0.66939783,0.6281428, -0.005506225,-0.021247003,0.056803677,-0.0033201245] ) let expectedGradKernelBackward = Tensor<Float>( [[0.034572553,-0.014308241,-0.037737265,0.028604513,-0.002552184, 0.042288657,-0.036268644,-0.011494972,-0.09629306,-0.12330007, -0.09965681,-0.15201326,0.033916343,0.08542741,-0.07855631,0.004139293], [0.016756708,-0.0069349525,-0.018290589,0.013864105,-0.0012369987, 0.020496568,-0.017578775,-0.0055714105,-0.046671554,-0.059761375, -0.0483019,-0.07367815,0.016438654,0.041405164,-0.03807486,0.0020062423], [0.041608598,-0.017220188,-0.04541738,0.03442597,-0.0030715927, 0.050895046,-0.04364987,-0.013834375,-0.11589018,-0.14839353,-0.1199385, -0.18295029,0.04081884,0.10281321,-0.09454372,0.0049817027]] ) let expectedGradRecurrentKernelBackward = Tensor<Float>( [[-0.029835997,0.012347964,0.032567132,-0.024685599,0.0022025262, -0.03649497,0.031299718,0.009920122,0.08310059,0.106407546,0.08600349, 0.13118693,-0.02926969,-0.07372357,0.06779383,-0.0035721958], [-0.03795522,0.015708195,0.041429576,-0.03140325,0.0028018963, -0.046426285,0.039817262,0.012619669,0.10571462,0.13536406,0.109407485, 0.16688661,-0.0372348,-0.09378585,0.08624245,-0.0045442916], [-0.03550094,0.014692465,0.038750634,-0.02937264,0.0026207187, -0.043424245,0.037242576,0.011803649,0.098878846,0.12661108,0.10233293, 0.15609531,-0.03482711,-0.08772142,0.080665804,-0.0042504463], [0.00059684756,-0.0002470121,-0.00065148197,0.00049381756, -0.000044059943,0.00073005544,-0.0006261282,-0.00019844486, -0.0016623671,-0.002128606,-0.0017204377,-0.0026242996,0.00058551895, 0.0014747867,-0.0013561664,0.000071459195]] ) let expectedGradBiasBackward = Tensor<Float>( [-0.049232706,0.02037551,0.053739384,-0.04073398,0.0036344128,-0.06022075, 0.05164801,0.016369302,0.1371252,0.17558426,0.1419153,0.21647298, -0.048298236,-0.121652074,0.11186734,-0.0058945194] ) let expectedGradX = Tensor<Float>( [[[-0.054938864,-0.022083957,-0.004919187], [0.01124474,-0.020291314,-0.02433711], [0.017743908,0.02348721,-0.07303476], [0.113909885,0.27435783,-0.3467198]]] ) let expectedGradInitialStateHiddenForward = Tensor<Float>( [[-0.046731517,0.05862768,0.0007173242,0.035859868]] ) let expectedGradInitialStateCellForward = Tensor<Float>( [[0.09301593,0.20037422,0.123320214,0.10345338]] ) let expectedGradInitialStateHiddenBackward = Tensor<Float>( [[0.013064705,0.037812762,-0.10854563,0.017091252]] ) let expectedGradInitialStateCellBackward = Tensor<Float>( [[0.3086998,0.34445396,0.26831728,0.4068746]] ) // END GENERATED CODE // Swaps the columns corresponding to "forget" and "update" gates. // // This translates between the keras ordering // [input | forget | update | output] // and the swift-apis ordering // [input | update | forget | output] func swapForgetUpdate(_ t: Tensor<Float>) -> Tensor<Float> { var split = t.split(count: 4, alongAxis: -1) split.swapAt(1, 2) return Tensor(concatenating: split, alongAxis: -1) } withTensorLeakChecking { var lstm = BidirectionalLSTM<Float>( LSTMCell(inputSize: 3, hiddenSize: 4), mergeFunction: LSTMCell<Float>.State.stack ) lstm.forward.cell.fusedWeight = swapForgetUpdate(Tensor(concatenating: [kernelForward, recurrentKernelForward])) lstm.forward.cell.fusedBias = swapForgetUpdate(biasForward) lstm.backward.cell.fusedWeight = swapForgetUpdate(Tensor(concatenating: [kernelBackward, recurrentKernelBackward])) lstm.backward.cell.fusedBias = swapForgetUpdate(biasBackward) let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = LSTMCell<Float>.State( cell: initialStateCellForward, hidden: initialStateHiddenForward) let initialBackwardLayerState = LSTMCell<Float>.State( cell: initialStateCellBackward, hidden: initialStateHiddenBackward) let outputs = lstm( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).map { $0.hidden.unstacked(alongAxis: 0) } assertEqual( Tensor(concatenating: outputs.map { $0[0] }), expectedStatesForward, accuracy: 1e-6) assertEqual( Tensor(concatenating: outputs.map { $0[1] }), expectedStatesBackward, accuracy: 1e-6) let (outputSum, (gradLSTM)) = valueWithGradient(at: lstm) { lstm in lstm.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).hidden.sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradLSTM.forward.cell.fusedWeight, swapForgetUpdate(Tensor(concatenating: [expectedGradKernelForward, expectedGradRecurrentKernelForward])), accuracy: 1e-6) assertEqual( gradLSTM.forward.cell.fusedBias, swapForgetUpdate(expectedGradBiasForward), accuracy: 1e-6) assertEqual( gradLSTM.backward.cell.fusedWeight, swapForgetUpdate(Tensor(concatenating: [expectedGradKernelBackward, expectedGradRecurrentKernelBackward])), accuracy: 1e-6) assertEqual( gradLSTM.backward.cell.fusedBias, swapForgetUpdate(expectedGradBiasBackward), accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in lstm.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).hidden.sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward.hidden, expectedGradInitialStateHiddenForward, accuracy: 1e-6) assertEqual( gradInitialStateForward.cell, expectedGradInitialStateCellForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward.hidden, expectedGradInitialStateHiddenBackward, accuracy: 1e-6) assertEqual( gradInitialStateBackward.cell, expectedGradInitialStateCellBackward, accuracy: 1e-6) } #endif } func testGRU() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/gru.py". // BEGIN GENERATED CODE let updateKernel = Tensor<Float>( [[-0.26313293,-0.37116733,0.044766128,0.07748526], [0.09139812,-0.17107481,-0.1005373,0.16451049], [0.22751534,0.04139793,0.32446748,-0.572471]] ) let resetKernel = Tensor<Float>( [[-0.10539937,0.38937503,-0.008569658,0.6300892], [0.5234366,0.20446932,0.42181438,-0.5262561], [-0.5687402,0.31843305,-0.4139892,-0.23788527]] ) let outputKernel = Tensor<Float>( [[0.24885243,-0.4738691,0.26539946,0.2054413], [-0.27858475,-0.6128201,0.28634238,0.33588284], [-0.2638935,-0.5053163,-0.42289674,0.34110242]] ) let updateRecurrentKernel = Tensor<Float>( [[0.27225327,-0.04530505,0.20488906,-0.70477146], [0.1233796,-0.2725925,-0.21331471,0.45468533], [-0.12901938,-0.5375645,-0.07981183,-0.18903717], [0.22767149,0.6950712,0.06780873,0.12117213]] ) let resetRecurrentKernel = Tensor<Float>( [[-0.38362607,-0.03403465,-0.032581285,0.18508019], [-0.35768405,0.017118583,0.34339952,-0.015158445], [0.42593452,-0.51679564,-0.13895734,-0.2845649], [0.15196994,-0.4617733,-0.03934008,-0.038054474]] ) let outputRecurrentKernel = Tensor<Float>( [[-0.3531419,0.04921763,-0.050379246,-0.26801136], [-0.34328082,0.5067098,0.031886574,-0.19034609], [-0.020022772,0.16366726,0.021551719,-0.27538475], [0.0029521734,0.31402355,-0.22738007,-0.23688483]] ) let updateBias = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetBias = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputBias = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateRecurrentBias = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetRecurrentBias = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputRecurrentBias = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.5643544,0.44471443,-0.022586703], [0.6949582,-0.17199272,-0.8988821], [0.38799608,-0.24902666,0.14971566], [0.7422098,-0.6817321,0.083263636]]] ) let initialState = Tensor<Float>( [[-0.71174276,-0.39879853,0.7789655,-0.1812765]] ) let expectedSum = Tensor<Float>( 0.2622946 ) let expectedStates = Tensor<Float>( [[[-0.31175402,-0.20596652,0.36340874,-0.075575344], [0.21953434,0.03525635,0.43513912,-0.11752244], [0.1467207,-0.031999923,0.21731833,-0.0734479], [0.24567646,0.0015162053,0.10337216,-0.08827023]]] ) let expectedFinalState = Tensor<Float>( [[0.24567646,0.0015162053,0.10337216,-0.08827023]] ) let expectedGradX = Tensor<Float>( [[[0.0044808714,-0.0021028928,-0.030270718], [0.008932473,-0.025464162,-0.09908461], [0.011008073,-0.06111902,-0.16229588], [0.1040091,-0.177594,-0.41953978]]] ) let expectedGradInitialState = Tensor<Float>( [[0.005508149,0.03993896,0.053400937,0.037300646]] ) let expectedGradUpdateKernel = Tensor<Float>( [[-0.040157042,-0.0136785135,0.050436385,0.007616069], [0.029918717,0.006519991,-0.045159567,-0.005434308], [0.013227239,0.01569719,0.019206645,-0.004196606]] ) let expectedGradResetKernel = Tensor<Float>( [[-0.004324538,0.0015231472,0.0015622675,-0.010165867], [0.00435052,-0.0018293709,-0.00096766773,0.008604034], [-0.0024347848,0.0026376988,-0.00044454157,-0.0025067823]] ) let expectedGradOutputKernel = Tensor<Float>( [[0.4559958,0.5759123,0.4702625,0.51912045], [-0.38423252,-0.45619243,-0.36462966,-0.4307824], [0.025001988,-0.0074325786,-0.018035406,0.030591251]] ) let expectedGradUpdateRecurrentKernel = Tensor<Float>( [[0.0015186802,0.010627928,0.008849502,0.0014116366], [0.0055325227,0.0070856367,-0.0066436627,0.0005385389], [-0.012196659,-0.00962431,0.050553232,-0.0037394736], [0.003526025,0.0022264342,-0.014122595,0.0008748602]] ) let expectedGradResetRecurrentKernel = Tensor<Float>( [[-0.0021709674,0.0029862812,-0.0005916139,-0.0038731585], [-0.0003447486,0.0013247593,-0.0006560448,-0.00038965122], [-0.0019658464,-0.00036801025,0.0022314903,-0.004976805], [0.00065238454,-0.000011753844,-0.0005693683,0.0015112129]] ) let expectedGradOutputRecurrentKernel = Tensor<Float>( [[0.03295932,0.04461184,0.012124008,0.06561776], [-0.010434465,-0.022276893,-0.025632525,-0.019136468], [0.08186121,0.15295859,0.12944305,0.1582405], [-0.024327286,-0.04418066,-0.035645414,-0.047330596]] ) let expectedGradUpdateBias = Tensor<Float>( [-0.052024383,-0.026385367,0.12956381,-0.0010043234] ) let expectedGradResetBias = Tensor<Float>( [-0.0070920927,0.0005423294,0.0050295107,-0.01650119] ) let expectedGradOutputBias = Tensor<Float>( [0.6879913,0.98991126,0.85718745,0.871734] ) let expectedGradUpdateRecurrentBias = Tensor<Float>( [-0.052024383,-0.026385367,0.12956381,-0.0010043234] ) let expectedGradResetRecurrentBias = Tensor<Float>( [-0.0070920927,0.0005423294,0.0050295107,-0.01650119] ) let expectedGradOutputRecurrentBias = Tensor<Float>( [0.28977823,0.49616843,0.3776239,0.5536645] ) // END GENERATED CODE withTensorLeakChecking { var gru = GRU<Float>( GRUCell(inputSize: 3, hiddenSize: 4) ) XCTAssertEqual(gru.cell.updateKernel.shape, updateKernel.shape) XCTAssertEqual(gru.cell.updateRecurrentKernel.shape, updateRecurrentKernel.shape) XCTAssertEqual(gru.cell.resetKernel.shape, resetKernel.shape) XCTAssertEqual(gru.cell.resetRecurrentKernel.shape, resetRecurrentKernel.shape) XCTAssertEqual(gru.cell.outputKernel.shape, outputKernel.shape) XCTAssertEqual(gru.cell.outputRecurrentKernel.shape, outputRecurrentKernel.shape) XCTAssertEqual(gru.cell.updateBias.shape, updateBias.shape) XCTAssertEqual(gru.cell.updateRecurrentBias.shape, updateRecurrentBias.shape) XCTAssertEqual(gru.cell.resetBias.shape, resetBias.shape) XCTAssertEqual(gru.cell.resetRecurrentBias.shape, resetRecurrentBias.shape) XCTAssertEqual(gru.cell.outputBias.shape, outputBias.shape) XCTAssertEqual(gru.cell.outputRecurrentBias.shape, outputRecurrentBias.shape) gru.cell.updateKernel = updateKernel gru.cell.updateRecurrentKernel = updateRecurrentKernel gru.cell.resetKernel = resetKernel gru.cell.resetRecurrentKernel = resetRecurrentKernel gru.cell.outputKernel = outputKernel gru.cell.outputRecurrentKernel = outputRecurrentKernel gru.cell.updateBias = updateBias gru.cell.updateRecurrentBias = updateRecurrentBias gru.cell.resetBias = resetBias gru.cell.resetRecurrentBias = resetRecurrentBias gru.cell.outputBias = outputBias gru.cell.outputRecurrentBias = outputRecurrentBias let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialState = GRUCell<Float>.State(initialState) let outputs = gru(inputs, initialState: initialState) assertEqual( Tensor(concatenating: outputs.map { $0 }), expectedStates, accuracy: 1e-6) assertEqual( outputs.last!, expectedFinalState, accuracy: 1e-6) let (outputSum, (gradGRU, gradInputs, gradInitialState)) = valueWithGradient(at: gru, inputs, initialState) { gru, inputs, initialState in gru.lastOutput( from: inputs, initialState: initialState ).sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialState, expectedGradInitialState, accuracy: 1e-6) assertEqual( gradGRU.cell.updateKernel, expectedGradUpdateKernel, accuracy: 1e-6) assertEqual( gradGRU.cell.resetKernel, expectedGradResetKernel, accuracy: 1e-6) assertEqual( gradGRU.cell.outputKernel, expectedGradOutputKernel, accuracy: 1e-6) assertEqual( gradGRU.cell.updateRecurrentKernel, expectedGradUpdateRecurrentKernel, accuracy: 1e-6) assertEqual( gradGRU.cell.resetRecurrentKernel, expectedGradResetRecurrentKernel, accuracy: 1e-6) assertEqual( gradGRU.cell.outputRecurrentKernel, expectedGradOutputRecurrentKernel, accuracy: 1e-6) assertEqual( gradGRU.cell.updateBias, expectedGradUpdateBias, accuracy: 1e-6) assertEqual( gradGRU.cell.resetBias, expectedGradResetBias, accuracy: 1e-6) assertEqual( gradGRU.cell.outputBias, expectedGradOutputBias, accuracy: 1e-6) assertEqual( gradGRU.cell.updateRecurrentBias, expectedGradUpdateRecurrentBias, accuracy: 1e-6) assertEqual( gradGRU.cell.resetRecurrentBias, expectedGradResetRecurrentBias, accuracy: 1e-6) assertEqual( gradGRU.cell.outputRecurrentBias, expectedGradOutputRecurrentBias, accuracy: 1e-6) } #endif } func testBidirectionalGRUSumMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_gru.py --merge-mode sum". // BEGIN GENERATED CODE let updateKernelForward = Tensor<Float>( [[-0.26313293,-0.37116733,0.044766128,0.07748526], [0.09139812,-0.17107481,-0.1005373,0.16451049], [0.22751534,0.04139793,0.32446748,-0.572471]] ) let resetKernelForward = Tensor<Float>( [[-0.10539937,0.38937503,-0.008569658,0.6300892], [0.5234366,0.20446932,0.42181438,-0.5262561], [-0.5687402,0.31843305,-0.4139892,-0.23788527]] ) let outputKernelForward = Tensor<Float>( [[0.24885243,-0.4738691,0.26539946,0.2054413], [-0.27858475,-0.6128201,0.28634238,0.33588284], [-0.2638935,-0.5053163,-0.42289674,0.34110242]] ) let updateRecurrentKernelForward = Tensor<Float>( [[0.27225327,-0.04530505,0.20488906,-0.70477146], [0.1233796,-0.2725925,-0.21331471,0.45468533], [-0.12901938,-0.5375645,-0.07981183,-0.18903717], [0.22767149,0.6950712,0.06780873,0.12117213]] ) let resetRecurrentKernelForward = Tensor<Float>( [[-0.38362607,-0.03403465,-0.032581285,0.18508019], [-0.35768405,0.017118583,0.34339952,-0.015158445], [0.42593452,-0.51679564,-0.13895734,-0.2845649], [0.15196994,-0.4617733,-0.03934008,-0.038054474]] ) let outputRecurrentKernelForward = Tensor<Float>( [[-0.3531419,0.04921763,-0.050379246,-0.26801136], [-0.34328082,0.5067098,0.031886574,-0.19034609], [-0.020022772,0.16366726,0.021551719,-0.27538475], [0.0029521734,0.31402355,-0.22738007,-0.23688483]] ) let updateBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateKernelBackward = Tensor<Float>( [[-0.38552743,0.30379778,-0.015429676,0.47474676], [0.24909449,-0.6272373,-0.17192209,0.08274299], [-0.41769588,-0.32856578,0.5987498,0.6109175]] ) let resetKernelBackward = Tensor<Float>( [[-0.11749339,-0.61405337,0.26505172,-0.17011762], [-0.23611891,0.18858898,0.6282174,-0.5656544], [-0.5848755,-0.014772236,0.007604778,0.5725722]] ) let outputKernelBackward = Tensor<Float>( [[0.10227531,0.5070258,-0.46571168,0.056879938], [0.49441308,-0.29395455,-0.07509631,0.29984736], [0.47141522,0.18345171,0.1791873,0.4368046]] ) let updateRecurrentKernelBackward = Tensor<Float>( [[0.3819934,0.37764925,0.015312237,-0.17769441], [-0.30984464,0.0024376288,-0.3083459,0.6083385], [-0.035942614,-0.24049878,0.19538112,-0.22652327], [0.06525053,0.14899497,-0.36888042,-0.2775943]] ) let resetRecurrentKernelBackward = Tensor<Float>( [[0.2151401,-0.21178766,-0.15712889,-0.078161664], [0.54615974,0.025927158,-0.061987586,-0.13631916], [0.61778206,-0.12979838,-0.19998191,0.32677993], [0.3122218,-0.3348464,-0.029183073,-0.08691845]] ) let outputRecurrentKernelBackward = Tensor<Float>( [[-0.64042187,0.34098455,-0.10449011,-0.14277793], [-0.07292092,0.24773169,0.21102233,0.07893403], [-0.029284794,-0.45729926,0.09502104,-0.29511455], [0.49253088,0.07420389,-0.48452082,0.2440229]] ) let updateBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.90076077,-0.7541278,-0.025081873], [0.37973404,-0.26513243,0.10235357], [0.3545239,-0.14615154,-0.540749], [-0.70222735,-0.34035724,-0.8451414]]] ) let initialForwardLayerState = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialBackwardLayerState = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let expectedSum = Tensor<Float>( -1.0636934 ) let expectedStates = Tensor<Float>( [[[-0.47425687,0.13057935,-0.28099662,0.09199959], [-0.23789163,0.07386574,-0.09076065,-0.07140374], [-0.37719586,-0.22458386,0.3951493,-0.43688574], [-0.6900477,-0.26849592,0.795504,-0.9006538]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those two and test it. // let expectedFinalStateForward = Tensor<Float>( // [[0.08708767,0.49491018,0.019275323,-0.13219076]] // ) // let expectedFinalStateBackward = Tensor<Float>( // [[-0.328244,-0.30765843,0.35560328,-0.3700244]] // ) let expectedGradX = Tensor<Float>( [[[0.016884286,0.031954587,-0.034630362], [-0.030145949,-0.032830622,-0.09927184], [0.010677528,-0.06555416,-0.24680781], [0.36794654,0.22227536,0.035613686]]] ) let expectedGradInitialStateForward = Tensor<Float>( [[-0.07189826,0.26491642,0.021249572,0.09973241]] ) let expectedGradUpdateKernelForward = Tensor<Float>( [[-0.014633494,0.11262925,-0.0124673275,-0.14178306], [-0.0015309703,0.043804236,0.026814371,-0.117686585], [0.0006633089,0.10263121,0.05096156,-0.15763283]] ) let expectedGradResetKernelForward = Tensor<Float>( [[0.010167458,0.0012375548,0.0016463948,0.0056149918], [0.0059102885,-0.007958793,0.0032499032,0.0029476206], [0.01513045,-0.011363849,0.0046043447,0.0065481835]] ) let expectedGradOutputKernelForward = Tensor<Float>( [[-0.27720484,0.01121016,-0.3119189,-0.15031564], [-0.17816868,-0.1504507,-0.26702198,-0.19132887], [-0.47820407,-0.2667625,-0.5929085,-0.3111684]] ) let expectedGradUpdateRecurrentKernelForward = Tensor<Float>( [[0.0013306543,-0.01375161,0.0037764863,-0.0035531288], [-0.0023589546,-0.024710568,-0.038062952,0.096005075], [0.0055330433,-0.0055813976,0.042736366,-0.09101869], [-0.002846387,-0.016188195,-0.037352126,0.11634412]] ) let expectedGradResetRecurrentKernelForward = Tensor<Float>( [[-0.0016176911,-0.0013255397,0.0003207235,-0.0006573718], [-0.0055763996,0.010337391,-0.0034352662,-0.0023184759], [0.0016612073,-0.011832552,0.003696582,0.000721002], [-0.0028628546,0.010542515,-0.0038019938,-0.0016213771]] ) let expectedGradOutputRecurrentKernelForward = Tensor<Float>( [[0.027280934,-0.011064235,0.02276091,-0.004477814], [0.09789748,0.09476159,0.15628886,0.10902606], [-0.032271817,-0.10743487,-0.093189105,-0.10548531], [0.05016677,0.09146461,0.10986484,0.10788684]] ) let expectedGradUpdateBiasForward = Tensor<Float>( [-0.007191318,-0.0988105,-0.11562109,0.29936516] ) let expectedGradResetBiasForward = Tensor<Float>( [-0.019118859,0.030049099,-0.010341871,-0.0081044715] ) let expectedGradOutputBiasForward = Tensor<Float>( [0.61583984,0.5973234,0.9004895,0.605246] ) let expectedGradUpdateRecurrentBiasForward = Tensor<Float>( [-0.007191318,-0.0988105,-0.11562109,0.29936516] ) let expectedGradResetRecurrentBiasForward = Tensor<Float>( [-0.019118859,0.030049099,-0.010341871,-0.0081044715] ) let expectedGradOutputRecurrentBiasForward = Tensor<Float>( [0.33583188,0.2782093,0.5110848,0.33206433] ) let expectedGradInitialStateBackward = Tensor<Float>( [[0.436919,0.39781284,0.48556933,0.34003386]] ) let expectedGradUpdateKernelBackward = Tensor<Float>( [[0.080392286,-0.02186797,-0.106636874,0.05397816], [0.038964726,-0.010599021,-0.051685017,0.026162265], [0.09675335,-0.026318438,-0.12833911,0.06496355]] ) let expectedGradResetKernelBackward = Tensor<Float>( [[-0.006548254,0.033489596,-0.03336197,0.033302337], [-0.0031738235,0.016231818,-0.016169962,0.016141057], [-0.007880924,0.040305246,-0.04015165,0.040079877]] ) let expectedGradOutputKernelBackward = Tensor<Float>( [[-0.2241628,-0.14797445,-0.24141216,-0.2907229], [-0.108647764,-0.071720615,-0.11700823,-0.14090827], [-0.26978338,-0.17808953,-0.29054326,-0.3498895]] ) let expectedGradUpdateRecurrentKernelBackward = Tensor<Float>( [[0.11208751,-0.03048957,-0.14867921,0.07525943], [0.0779456,-0.021202432,-0.10339145,0.05233537], [-0.118453026,0.03222109,0.15712279,-0.07953346], [0.12208392,-0.03320875,-0.16193901,0.08197136]] ) let expectedGradResetRecurrentKernelBackward = Tensor<Float>( [[-0.009129949,0.046693105,-0.046515163,0.04643202], [-0.006348962,0.032470364,-0.03234662,0.032288805], [0.009648444,-0.049344834,0.04915679,-0.04906892], [-0.009944194,0.05085738,-0.050663568,0.05057301]] ) let expectedGradOutputRecurrentKernelBackward = Tensor<Float>( [[-0.18567991,-0.14199756,-0.13620174,-0.24541472], [-0.12912172,-0.09874504,-0.09471462,-0.17066127], [0.19622478,0.1500617,0.14393671,0.25935197], [-0.20223959,-0.15466146,-0.14834875,-0.26730177]] ) let expectedGradUpdateBiasBackward = Tensor<Float>( [-0.11448185,0.03114087,0.1518552,-0.076867074] ) let expectedGradResetBiasBackward = Tensor<Float>( [0.009324977,-0.047690533,0.04750879,-0.04742387] ) let expectedGradOutputBiasBackward = Tensor<Float>( [0.31921685,0.21072157,0.34378064,0.4140011] ) let expectedGradUpdateRecurrentBiasBackward = Tensor<Float>( [-0.11448185,0.03114087,0.1518552,-0.076867074] ) let expectedGradResetRecurrentBiasBackward = Tensor<Float>( [0.009324977,-0.047690533,0.04750879,-0.04742387] ) let expectedGradOutputRecurrentBiasBackward = Tensor<Float>( [0.18964629,0.14503083,0.13911119,0.2506571] ) // END GENERATED CODE withTensorLeakChecking { var gru = BidirectionalGRU<Float>( GRUCell(inputSize: 3, hiddenSize: 4), mergeFunction: GRUCell<Float>.State.sum ) XCTAssertEqual(gru.forward.cell.updateKernel.shape, updateKernelForward.shape) XCTAssertEqual(gru.forward.cell.updateRecurrentKernel.shape, updateRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.resetKernel.shape, resetKernelForward.shape) XCTAssertEqual(gru.forward.cell.resetRecurrentKernel.shape, resetRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.outputKernel.shape, outputKernelForward.shape) XCTAssertEqual(gru.forward.cell.outputRecurrentKernel.shape, outputRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.updateBias.shape, updateBiasForward.shape) XCTAssertEqual(gru.forward.cell.updateRecurrentBias.shape, updateRecurrentBiasForward.shape) XCTAssertEqual(gru.forward.cell.resetBias.shape, resetBiasForward.shape) XCTAssertEqual(gru.forward.cell.resetRecurrentBias.shape, resetRecurrentBiasForward.shape) XCTAssertEqual(gru.forward.cell.outputBias.shape, outputBiasForward.shape) XCTAssertEqual(gru.forward.cell.outputRecurrentBias.shape, outputRecurrentBiasForward.shape) XCTAssertEqual(gru.backward.cell.updateKernel.shape, updateKernelBackward.shape) XCTAssertEqual(gru.backward.cell.updateRecurrentKernel.shape, updateRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.resetKernel.shape, resetKernelBackward.shape) XCTAssertEqual(gru.backward.cell.resetRecurrentKernel.shape, resetRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.outputKernel.shape, outputKernelBackward.shape) XCTAssertEqual(gru.backward.cell.outputRecurrentKernel.shape, outputRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.updateBias.shape, updateBiasBackward.shape) XCTAssertEqual(gru.backward.cell.updateRecurrentBias.shape, updateRecurrentBiasBackward.shape) XCTAssertEqual(gru.backward.cell.resetBias.shape, resetBiasBackward.shape) XCTAssertEqual(gru.backward.cell.resetRecurrentBias.shape, resetRecurrentBiasBackward.shape) XCTAssertEqual(gru.backward.cell.outputBias.shape, outputBiasBackward.shape) XCTAssertEqual(gru.backward.cell.outputRecurrentBias.shape, outputRecurrentBiasBackward.shape) gru.forward.cell.updateKernel = updateKernelForward gru.forward.cell.updateRecurrentKernel = updateRecurrentKernelForward gru.forward.cell.resetKernel = resetKernelForward gru.forward.cell.resetRecurrentKernel = resetRecurrentKernelForward gru.forward.cell.outputKernel = outputKernelForward gru.forward.cell.outputRecurrentKernel = outputRecurrentKernelForward gru.forward.cell.updateBias = updateBiasForward gru.forward.cell.updateRecurrentBias = updateRecurrentBiasForward gru.forward.cell.resetBias = resetBiasForward gru.forward.cell.resetRecurrentBias = resetRecurrentBiasForward gru.forward.cell.outputBias = outputBiasForward gru.forward.cell.outputRecurrentBias = outputRecurrentBiasForward gru.backward.cell.updateKernel = updateKernelBackward gru.backward.cell.updateRecurrentKernel = updateRecurrentKernelBackward gru.backward.cell.resetKernel = resetKernelBackward gru.backward.cell.resetRecurrentKernel = resetRecurrentKernelBackward gru.backward.cell.outputKernel = outputKernelBackward gru.backward.cell.outputRecurrentKernel = outputRecurrentKernelBackward gru.backward.cell.updateBias = updateBiasBackward gru.backward.cell.updateRecurrentBias = updateRecurrentBiasBackward gru.backward.cell.resetBias = resetBiasBackward gru.backward.cell.resetRecurrentBias = resetRecurrentBiasBackward gru.backward.cell.outputBias = outputBiasBackward gru.backward.cell.outputRecurrentBias = outputRecurrentBiasBackward let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = GRUCell<Float>.State(initialForwardLayerState) let initialBackwardLayerState = GRUCell<Float>.State(initialBackwardLayerState) let outputs = gru( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ) assertEqual( Tensor(concatenating: outputs), expectedStates, accuracy: 1e-6) let (outputSum, (gradGRU)) = valueWithGradient(at: gru) { gru in gru.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateKernel, expectedGradUpdateKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetKernel, expectedGradResetKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputKernel, expectedGradOutputKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateRecurrentKernel, expectedGradUpdateRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetRecurrentKernel, expectedGradResetRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputRecurrentKernel, expectedGradOutputRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateBias, expectedGradUpdateBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetBias, expectedGradResetBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputBias, expectedGradOutputBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateRecurrentBias, expectedGradUpdateRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetRecurrentBias, expectedGradResetRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputRecurrentBias, expectedGradOutputRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateKernel, expectedGradUpdateKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetKernel, expectedGradResetKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputKernel, expectedGradOutputKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateRecurrentKernel, expectedGradUpdateRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetRecurrentKernel, expectedGradResetRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputRecurrentKernel, expectedGradOutputRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateBias, expectedGradUpdateBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetBias, expectedGradResetBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputBias, expectedGradOutputBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateRecurrentBias, expectedGradUpdateRecurrentBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetRecurrentBias, expectedGradResetRecurrentBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputRecurrentBias, expectedGradOutputRecurrentBiasBackward, accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in gru.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward, expectedGradInitialStateForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward, expectedGradInitialStateBackward, accuracy: 1e-6) } #endif } func testBidirectionalGRUConcatenateMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_gru.py --merge-mode concat". // BEGIN GENERATED CODE let updateKernelForward = Tensor<Float>( [[-0.26313293,-0.37116733,0.044766128,0.07748526], [0.09139812,-0.17107481,-0.1005373,0.16451049], [0.22751534,0.04139793,0.32446748,-0.572471]] ) let resetKernelForward = Tensor<Float>( [[-0.10539937,0.38937503,-0.008569658,0.6300892], [0.5234366,0.20446932,0.42181438,-0.5262561], [-0.5687402,0.31843305,-0.4139892,-0.23788527]] ) let outputKernelForward = Tensor<Float>( [[0.24885243,-0.4738691,0.26539946,0.2054413], [-0.27858475,-0.6128201,0.28634238,0.33588284], [-0.2638935,-0.5053163,-0.42289674,0.34110242]] ) let updateRecurrentKernelForward = Tensor<Float>( [[0.27225327,-0.04530505,0.20488906,-0.70477146], [0.1233796,-0.2725925,-0.21331471,0.45468533], [-0.12901938,-0.5375645,-0.07981183,-0.18903717], [0.22767149,0.6950712,0.06780873,0.12117213]] ) let resetRecurrentKernelForward = Tensor<Float>( [[-0.38362607,-0.03403465,-0.032581285,0.18508019], [-0.35768405,0.017118583,0.34339952,-0.015158445], [0.42593452,-0.51679564,-0.13895734,-0.2845649], [0.15196994,-0.4617733,-0.03934008,-0.038054474]] ) let outputRecurrentKernelForward = Tensor<Float>( [[-0.3531419,0.04921763,-0.050379246,-0.26801136], [-0.34328082,0.5067098,0.031886574,-0.19034609], [-0.020022772,0.16366726,0.021551719,-0.27538475], [0.0029521734,0.31402355,-0.22738007,-0.23688483]] ) let updateBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateKernelBackward = Tensor<Float>( [[-0.38552743,0.30379778,-0.015429676,0.47474676], [0.24909449,-0.6272373,-0.17192209,0.08274299], [-0.41769588,-0.32856578,0.5987498,0.6109175]] ) let resetKernelBackward = Tensor<Float>( [[-0.11749339,-0.61405337,0.26505172,-0.17011762], [-0.23611891,0.18858898,0.6282174,-0.5656544], [-0.5848755,-0.014772236,0.007604778,0.5725722]] ) let outputKernelBackward = Tensor<Float>( [[0.10227531,0.5070258,-0.46571168,0.056879938], [0.49441308,-0.29395455,-0.07509631,0.29984736], [0.47141522,0.18345171,0.1791873,0.4368046]] ) let updateRecurrentKernelBackward = Tensor<Float>( [[0.3819934,0.37764925,0.015312237,-0.17769441], [-0.30984464,0.0024376288,-0.3083459,0.6083385], [-0.035942614,-0.24049878,0.19538112,-0.22652327], [0.06525053,0.14899497,-0.36888042,-0.2775943]] ) let resetRecurrentKernelBackward = Tensor<Float>( [[0.2151401,-0.21178766,-0.15712889,-0.078161664], [0.54615974,0.025927158,-0.061987586,-0.13631916], [0.61778206,-0.12979838,-0.19998191,0.32677993], [0.3122218,-0.3348464,-0.029183073,-0.08691845]] ) let outputRecurrentKernelBackward = Tensor<Float>( [[-0.64042187,0.34098455,-0.10449011,-0.14277793], [-0.07292092,0.24773169,0.21102233,0.07893403], [-0.029284794,-0.45729926,0.09502104,-0.29511455], [0.49253088,0.07420389,-0.48452082,0.2440229]] ) let updateBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.90076077,-0.7541278,-0.025081873], [0.37973404,-0.26513243,0.10235357], [0.3545239,-0.14615154,-0.540749], [-0.70222735,-0.34035724,-0.8451414]]] ) let initialForwardLayerState = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialBackwardLayerState = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let expectedSum = Tensor<Float>( -1.0636933 ) let expectedStates = Tensor<Float>( [[[-0.14601289,0.4382378,-0.6365999,0.462024,-0.328244,-0.30765843, 0.35560328,-0.37002444], [-0.024607085,0.29749468,-0.35770136,0.2921221,-0.21328454,-0.22362898, 0.2669407,-0.36352584], [0.10575075,0.28877518,-0.03438914,0.12433955,-0.48294663,-0.51335907, 0.4295384,-0.5612253], [0.087087676,0.49491018,0.019275311,-0.13219076,-0.7771353,-0.7634061, 0.77622867,-0.768463]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those two and test it. // let expectedFinalStateForward = Tensor<Float>( // [[0.087087676,0.49491018,0.019275311,-0.13219076]] // ) // let expectedFinalStateBackward = Tensor<Float>( // [[-0.328244,-0.30765843,0.35560328,-0.37002444]] // ) let expectedGradX = Tensor<Float>( [[[0.016884288,0.031954587,-0.03463035], [-0.030145962,-0.03283064,-0.09927187], [0.010677524,-0.065554164,-0.24680781], [0.36794654,0.22227536,0.035613716]]] ) let expectedGradInitialStateForward = Tensor<Float>( [[-0.07189825,0.26491642,0.021249587,0.0997324]] ) let expectedGradUpdateKernelForward = Tensor<Float>( [[-0.014633494,0.11262925,-0.012467325,-0.14178306], [-0.0015309711,0.04380424,0.026814379,-0.11768658], [0.0006633061,0.10263122,0.050961565,-0.15763283]] ) let expectedGradResetKernelForward = Tensor<Float>( [[0.010167458,0.001237556,0.0016463955,0.0056149918], [0.0059102885,-0.007958793,0.0032499037,0.00294762], [0.01513045,-0.011363849,0.0046043447,0.006548183]] ) let expectedGradOutputKernelForward = Tensor<Float>( [[-0.27720484,0.011210177,-0.3119189,-0.15031563], [-0.17816868,-0.1504507,-0.267022,-0.19132887], [-0.47820407,-0.2667625,-0.59290844,-0.3111684]] ) let expectedGradUpdateRecurrentKernelForward = Tensor<Float>( [[0.0013306541,-0.013751614,0.0037764856,-0.0035531214], [-0.0023589535,-0.02471057,-0.03806296,0.09600505], [0.0055330424,-0.0055813985,0.042736374,-0.09101869], [-0.0028463858,-0.01618819,-0.03735213,0.1163441]] ) let expectedGradResetRecurrentKernelForward = Tensor<Float>( [[-0.0016176912,-0.0013255394,0.00032072357,-0.0006573719], [-0.005576399,0.010337391,-0.0034352664,-0.002318475], [0.0016612078,-0.011832552,0.0036965827,0.000721002], [-0.0028628546,0.010542516,-0.0038019943,-0.0016213768]] ) let expectedGradOutputRecurrentKernelForward = Tensor<Float>( [[0.027280936,-0.011064235,0.022760917,-0.0044778096], [0.09789747,0.09476159,0.15628885,0.109026045], [-0.03227183,-0.10743488,-0.09318911,-0.10548531], [0.05016677,0.09146462,0.10986483,0.107886836]] ) let expectedGradUpdateBiasForward = Tensor<Float>( [-0.0071913144,-0.09881051,-0.11562111,0.29936513] ) let expectedGradResetBiasForward = Tensor<Float>( [-0.019118859,0.0300491,-0.010341872,-0.0081044715] ) let expectedGradOutputBiasForward = Tensor<Float>( [0.61583984,0.5973235,0.9004895,0.605246] ) let expectedGradUpdateRecurrentBiasForward = Tensor<Float>( [-0.0071913144,-0.09881051,-0.11562111,0.29936513] ) let expectedGradResetRecurrentBiasForward = Tensor<Float>( [-0.019118859,0.0300491,-0.010341872,-0.0081044715] ) let expectedGradOutputRecurrentBiasForward = Tensor<Float>( [0.33583188,0.27820933,0.5110848,0.33206433] ) let expectedGradInitialStateBackward = Tensor<Float>( [[0.43691894,0.39781284,0.48556933,0.3400339]] ) let expectedGradUpdateKernelBackward = Tensor<Float>( [[0.080392286,-0.02186797,-0.106636874,0.05397816], [0.038964726,-0.010599021,-0.051685017,0.026162265], [0.09675335,-0.026318438,-0.12833911,0.06496355]] ) let expectedGradResetKernelBackward = Tensor<Float>( [[-0.006548254,0.033489596,-0.03336197,0.033302337], [-0.0031738235,0.016231818,-0.016169962,0.016141057], [-0.007880924,0.040305246,-0.04015165,0.040079877]] ) let expectedGradOutputKernelBackward = Tensor<Float>( [[-0.22416282,-0.14797445,-0.24141216,-0.29072288], [-0.10864778,-0.071720615,-0.11700823,-0.14090827], [-0.2697834,-0.17808953,-0.29054326,-0.34988946]] ) let expectedGradUpdateRecurrentKernelBackward = Tensor<Float>( [[0.11208751,-0.03048957,-0.14867921,0.07525943], [0.0779456,-0.021202432,-0.10339145,0.05233537], [-0.118453026,0.03222109,0.15712279,-0.07953346], [0.12208392,-0.03320875,-0.16193901,0.08197136]] ) let expectedGradResetRecurrentKernelBackward = Tensor<Float>( [[-0.009129949,0.046693105,-0.046515163,0.04643202], [-0.006348962,0.032470364,-0.03234662,0.032288805], [0.009648444,-0.049344834,0.04915679,-0.04906892], [-0.009944194,0.05085738,-0.050663568,0.05057301]] ) let expectedGradOutputRecurrentKernelBackward = Tensor<Float>( [[-0.18567993,-0.14199756,-0.13620174,-0.24541469], [-0.12912174,-0.09874504,-0.09471462,-0.17066126], [0.1962248,0.1500617,0.14393671,0.25935194], [-0.2022396,-0.15466146,-0.14834875,-0.26730174]] ) let expectedGradUpdateBiasBackward = Tensor<Float>( [-0.11448185,0.03114087,0.1518552,-0.076867074] ) let expectedGradResetBiasBackward = Tensor<Float>( [0.009324977,-0.047690533,0.04750879,-0.04742387] ) let expectedGradOutputBiasBackward = Tensor<Float>( [0.31921688,0.21072157,0.34378064,0.41400108] ) let expectedGradUpdateRecurrentBiasBackward = Tensor<Float>( [-0.11448185,0.03114087,0.1518552,-0.076867074] ) let expectedGradResetRecurrentBiasBackward = Tensor<Float>( [0.009324977,-0.047690533,0.04750879,-0.04742387] ) let expectedGradOutputRecurrentBiasBackward = Tensor<Float>( [0.1896463,0.14503083,0.13911119,0.25065708] ) // END GENERATED CODE withTensorLeakChecking { var gru = BidirectionalGRU<Float>( GRUCell(inputSize: 3, hiddenSize: 4) ) XCTAssertEqual(gru.forward.cell.updateKernel.shape, updateKernelForward.shape) XCTAssertEqual(gru.forward.cell.updateRecurrentKernel.shape, updateRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.resetKernel.shape, resetKernelForward.shape) XCTAssertEqual(gru.forward.cell.resetRecurrentKernel.shape, resetRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.outputKernel.shape, outputKernelForward.shape) XCTAssertEqual(gru.forward.cell.outputRecurrentKernel.shape, outputRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.updateBias.shape, updateBiasForward.shape) XCTAssertEqual(gru.forward.cell.updateRecurrentBias.shape, updateRecurrentBiasForward.shape) XCTAssertEqual(gru.forward.cell.resetBias.shape, resetBiasForward.shape) XCTAssertEqual(gru.forward.cell.resetRecurrentBias.shape, resetRecurrentBiasForward.shape) XCTAssertEqual(gru.forward.cell.outputBias.shape, outputBiasForward.shape) XCTAssertEqual(gru.forward.cell.outputRecurrentBias.shape, outputRecurrentBiasForward.shape) XCTAssertEqual(gru.backward.cell.updateKernel.shape, updateKernelBackward.shape) XCTAssertEqual(gru.backward.cell.updateRecurrentKernel.shape, updateRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.resetKernel.shape, resetKernelBackward.shape) XCTAssertEqual(gru.backward.cell.resetRecurrentKernel.shape, resetRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.outputKernel.shape, outputKernelBackward.shape) XCTAssertEqual(gru.backward.cell.outputRecurrentKernel.shape, outputRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.updateBias.shape, updateBiasBackward.shape) XCTAssertEqual(gru.backward.cell.updateRecurrentBias.shape, updateRecurrentBiasBackward.shape) XCTAssertEqual(gru.backward.cell.resetBias.shape, resetBiasBackward.shape) XCTAssertEqual(gru.backward.cell.resetRecurrentBias.shape, resetRecurrentBiasBackward.shape) XCTAssertEqual(gru.backward.cell.outputBias.shape, outputBiasBackward.shape) XCTAssertEqual(gru.backward.cell.outputRecurrentBias.shape, outputRecurrentBiasBackward.shape) gru.forward.cell.updateKernel = updateKernelForward gru.forward.cell.updateRecurrentKernel = updateRecurrentKernelForward gru.forward.cell.resetKernel = resetKernelForward gru.forward.cell.resetRecurrentKernel = resetRecurrentKernelForward gru.forward.cell.outputKernel = outputKernelForward gru.forward.cell.outputRecurrentKernel = outputRecurrentKernelForward gru.forward.cell.updateBias = updateBiasForward gru.forward.cell.updateRecurrentBias = updateRecurrentBiasForward gru.forward.cell.resetBias = resetBiasForward gru.forward.cell.resetRecurrentBias = resetRecurrentBiasForward gru.forward.cell.outputBias = outputBiasForward gru.forward.cell.outputRecurrentBias = outputRecurrentBiasForward gru.backward.cell.updateKernel = updateKernelBackward gru.backward.cell.updateRecurrentKernel = updateRecurrentKernelBackward gru.backward.cell.resetKernel = resetKernelBackward gru.backward.cell.resetRecurrentKernel = resetRecurrentKernelBackward gru.backward.cell.outputKernel = outputKernelBackward gru.backward.cell.outputRecurrentKernel = outputRecurrentKernelBackward gru.backward.cell.updateBias = updateBiasBackward gru.backward.cell.updateRecurrentBias = updateRecurrentBiasBackward gru.backward.cell.resetBias = resetBiasBackward gru.backward.cell.resetRecurrentBias = resetRecurrentBiasBackward gru.backward.cell.outputBias = outputBiasBackward gru.backward.cell.outputRecurrentBias = outputRecurrentBiasBackward let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = GRUCell<Float>.State(initialForwardLayerState) let initialBackwardLayerState = GRUCell<Float>.State(initialBackwardLayerState) let outputs = gru( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ) assertEqual( Tensor(concatenating: outputs), expectedStates, accuracy: 1e-6) let (outputSum, (gradGRU)) = valueWithGradient(at: gru) { gru in gru.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateKernel, expectedGradUpdateKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetKernel, expectedGradResetKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputKernel, expectedGradOutputKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateRecurrentKernel, expectedGradUpdateRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetRecurrentKernel, expectedGradResetRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputRecurrentKernel, expectedGradOutputRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateBias, expectedGradUpdateBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetBias, expectedGradResetBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputBias, expectedGradOutputBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateRecurrentBias, expectedGradUpdateRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetRecurrentBias, expectedGradResetRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputRecurrentBias, expectedGradOutputRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateKernel, expectedGradUpdateKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetKernel, expectedGradResetKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputKernel, expectedGradOutputKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateRecurrentKernel, expectedGradUpdateRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetRecurrentKernel, expectedGradResetRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputRecurrentKernel, expectedGradOutputRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateBias, expectedGradUpdateBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetBias, expectedGradResetBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputBias, expectedGradOutputBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateRecurrentBias, expectedGradUpdateRecurrentBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetRecurrentBias, expectedGradResetRecurrentBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputRecurrentBias, expectedGradOutputRecurrentBiasBackward, accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in gru.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward, expectedGradInitialStateForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward, expectedGradInitialStateBackward, accuracy: 1e-6) } #endif } func testBidirectionalGRUAverageMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_gru.py --merge-mode ave". // BEGIN GENERATED CODE let updateKernelForward = Tensor<Float>( [[-0.26313293,-0.37116733,0.044766128,0.07748526], [0.09139812,-0.17107481,-0.1005373,0.16451049], [0.22751534,0.04139793,0.32446748,-0.572471]] ) let resetKernelForward = Tensor<Float>( [[-0.10539937,0.38937503,-0.008569658,0.6300892], [0.5234366,0.20446932,0.42181438,-0.5262561], [-0.5687402,0.31843305,-0.4139892,-0.23788527]] ) let outputKernelForward = Tensor<Float>( [[0.24885243,-0.4738691,0.26539946,0.2054413], [-0.27858475,-0.6128201,0.28634238,0.33588284], [-0.2638935,-0.5053163,-0.42289674,0.34110242]] ) let updateRecurrentKernelForward = Tensor<Float>( [[0.27225327,-0.04530505,0.20488906,-0.70477146], [0.1233796,-0.2725925,-0.21331471,0.45468533], [-0.12901938,-0.5375645,-0.07981183,-0.18903717], [0.2276715,0.6950712,0.06780873,0.121172115]] ) let resetRecurrentKernelForward = Tensor<Float>( [[-0.38362607,-0.03403465,-0.032581285,0.18508019], [-0.35768405,0.017118583,0.34339952,-0.015158445], [0.42593452,-0.51679564,-0.13895734,-0.2845649], [0.15196995,-0.4617733,-0.03934008,-0.038054474]] ) let outputRecurrentKernelForward = Tensor<Float>( [[-0.3531419,0.04921763,-0.050379246,-0.26801136], [-0.34328082,0.5067098,0.031886574,-0.19034609], [-0.020022772,0.16366726,0.021551719,-0.27538475], [0.002952166,0.31402355,-0.22738007,-0.23688485]] ) let updateBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateKernelBackward = Tensor<Float>( [[-0.38552743,0.30379778,-0.015429676,0.47474676], [0.24909449,-0.6272373,-0.17192209,0.08274299], [-0.41769588,-0.32856578,0.5987498,0.6109175]] ) let resetKernelBackward = Tensor<Float>( [[-0.11749339,-0.61405337,0.26505172,-0.17011762], [-0.23611891,0.18858898,0.6282174,-0.5656544], [-0.5848755,-0.014772236,0.007604778,0.5725722]] ) let outputKernelBackward = Tensor<Float>( [[0.10227531,0.5070258,-0.46571168,0.056879938], [0.49441308,-0.29395455,-0.07509631,0.29984736], [0.47141522,0.18345171,0.1791873,0.4368046]] ) let updateRecurrentKernelBackward = Tensor<Float>( [[0.3819934,0.37764925,0.015312237,-0.17769441], [-0.30984464,0.0024376288,-0.3083459,0.6083385], [-0.035942614,-0.24049878,0.19538112,-0.22652327], [0.06525053,0.14899497,-0.36888042,-0.2775943]] ) let resetRecurrentKernelBackward = Tensor<Float>( [[0.2151401,-0.21178766,-0.15712889,-0.078161664], [0.54615974,0.025927158,-0.061987586,-0.13631916], [0.61778206,-0.12979838,-0.19998191,0.32677993], [0.3122218,-0.3348464,-0.029183073,-0.08691845]] ) let outputRecurrentKernelBackward = Tensor<Float>( [[-0.64042187,0.34098455,-0.10449011,-0.14277793], [-0.07292092,0.24773169,0.21102233,0.07893403], [-0.029284794,-0.45729926,0.09502104,-0.29511455], [0.49253088,0.07420389,-0.48452082,0.2440229]] ) let updateBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.90076077,-0.7541278,-0.025081873], [0.37973404,-0.26513243,0.10235357], [0.3545239,-0.14615154,-0.540749], [-0.70222735,-0.34035724,-0.8451414]]] ) let initialForwardLayerState = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialBackwardLayerState = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let expectedSum = Tensor<Float>( -0.53184664 ) let expectedStates = Tensor<Float>( [[[-0.23712845,0.065289676,-0.14049831,0.045999765], [-0.11894582,0.03693285,-0.045380324,-0.03570187], [-0.18859795,-0.11229195,0.19757463,-0.21844287], [-0.3450238,-0.13424796,0.397752,-0.4503269]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those two and test it. // let expectedFinalStateForward = Tensor<Float>( // [[0.087087676,0.49491018,0.019275311,-0.13219076]] // ) // let expectedFinalStateBackward = Tensor<Float>( // [[-0.328244,-0.30765843,0.35560328,-0.37002444]] // ) let expectedGradX = Tensor<Float>( [[[0.008442146,0.015977293,-0.017315175], [-0.015072985,-0.01641532,-0.049635936], [0.005338762,-0.032777082,-0.12340391], [0.18397327,0.11113768,0.017806858]]] ) let expectedGradInitialStateForward = Tensor<Float>( [[-0.035949126,0.1324582,0.010624796,0.0498662]] ) let expectedGradUpdateKernelForward = Tensor<Float>( [[-0.0073167454,0.056314625,-0.0062336624,-0.07089153], [-0.00076548447,0.02190212,0.013407189,-0.05884329], [0.00033165538,0.05131561,0.025480783,-0.07881642]] ) let expectedGradResetKernelForward = Tensor<Float>( [[0.0050837277,0.000618778,0.00082319777,0.002807496], [0.0029551436,-0.003979396,0.0016249518,0.0014738103], [0.0075652236,-0.0056819245,0.0023021724,0.0032740915]] ) let expectedGradOutputKernelForward = Tensor<Float>( [[-0.13860242,0.0056050895,-0.15595947,-0.075157814], [-0.08908434,-0.07522535,-0.133511,-0.095664434], [-0.23910204,-0.13338125,-0.29645422,-0.1555842]] ) let expectedGradUpdateRecurrentKernelForward = Tensor<Float>( [[0.0006653269,-0.006875807,0.0018882437,-0.0017765616], [-0.0011794777,-0.012355285,-0.01903148,0.048002526], [0.0027665214,-0.0027906992,0.021368187,-0.045509342], [-0.0014231934,-0.008094095,-0.018676067,0.058172047]] ) let expectedGradResetRecurrentKernelForward = Tensor<Float>( [[-0.0008088454,-0.0006627698,0.00016036181,-0.0003286859], [-0.0027881989,0.0051686955,-0.0017176332,-0.0011592377], [0.0008306038,-0.0059162755,0.0018482914,0.00036050117], [-0.0014314271,0.005271257,-0.0019009972,-0.00081068865]] ) let expectedGradOutputRecurrentKernelForward = Tensor<Float>( [[0.013640466,-0.005532119,0.011380454,-0.0022389072], [0.048948735,0.047380794,0.07814442,0.054513022], [-0.016135914,-0.05371744,-0.046594556,-0.052742656], [0.025083385,0.045732304,0.054932415,0.053943418]] ) let expectedGradUpdateBiasForward = Tensor<Float>( [-0.0035956602,-0.049405254,-0.057810556,0.14968255] ) let expectedGradResetBiasForward = Tensor<Float>( [-0.009559427,0.01502455,-0.005170936,-0.004052236] ) let expectedGradOutputBiasForward = Tensor<Float>( [0.30791992,0.29866174,0.45024475,0.302623] ) let expectedGradUpdateRecurrentBiasForward = Tensor<Float>( [-0.0035956602,-0.049405254,-0.057810556,0.14968255] ) let expectedGradResetRecurrentBiasForward = Tensor<Float>( [-0.009559427,0.01502455,-0.005170936,-0.004052236] ) let expectedGradOutputRecurrentBiasForward = Tensor<Float>( [0.16791594,0.13910466,0.2555424,0.16603217] ) let expectedGradInitialStateBackward = Tensor<Float>( [[0.21845947,0.19890642,0.24278466,0.17001694]] ) let expectedGradUpdateKernelBackward = Tensor<Float>( [[0.040196143,-0.010933985,-0.053318437,0.02698908], [0.019482363,-0.0052995104,-0.025842508,0.013081132], [0.048376676,-0.013159219,-0.064169556,0.032481775]] ) let expectedGradResetKernelBackward = Tensor<Float>( [[-0.003274127,0.016744798,-0.016680986,0.016651168], [-0.0015869117,0.008115909,-0.008084981,0.0080705285], [-0.003940462,0.020152623,-0.020075824,0.020039938]] ) let expectedGradOutputKernelBackward = Tensor<Float>( [[-0.11208141,-0.07398722,-0.12070608,-0.14536144], [-0.05432389,-0.035860308,-0.058504116,-0.070454136], [-0.1348917,-0.089044765,-0.14527163,-0.17494473]] ) let expectedGradUpdateRecurrentKernelBackward = Tensor<Float>( [[0.056043755,-0.015244785,-0.074339606,0.037629716], [0.0389728,-0.010601216,-0.051695727,0.026167685], [-0.059226513,0.016110545,0.078561395,-0.03976673], [0.06104196,-0.016604375,-0.080969505,0.04098568]] ) let expectedGradResetRecurrentKernelBackward = Tensor<Float>( [[-0.0045649745,0.023346553,-0.023257582,0.02321601], [-0.003174481,0.016235182,-0.01617331,0.016144402], [0.004824222,-0.024672417,0.024578394,-0.02453446], [-0.004972097,0.02542869,-0.025331784,0.025286505]] ) let expectedGradOutputRecurrentKernelBackward = Tensor<Float>( [[-0.092839964,-0.07099878,-0.06810087,-0.122707345], [-0.06456087,-0.04937252,-0.04735731,-0.08533063], [0.0981124,0.07503085,0.071968354,0.12967597], [-0.1011198,-0.07733073,-0.074174374,-0.13365087]] ) let expectedGradUpdateBiasBackward = Tensor<Float>( [-0.057240926,0.015570435,0.0759276,-0.038433537] ) let expectedGradResetBiasBackward = Tensor<Float>( [0.0046624886,-0.023845267,0.023754396,-0.023711935] ) let expectedGradOutputBiasBackward = Tensor<Float>( [0.15960844,0.10536078,0.17189032,0.20700054] ) let expectedGradUpdateRecurrentBiasBackward = Tensor<Float>( [-0.057240926,0.015570435,0.0759276,-0.038433537] ) let expectedGradResetRecurrentBiasBackward = Tensor<Float>( [0.0046624886,-0.023845267,0.023754396,-0.023711935] ) let expectedGradOutputRecurrentBiasBackward = Tensor<Float>( [0.09482315,0.07251541,0.069555596,0.12532854] ) // END GENERATED CODE withTensorLeakChecking { var gru = BidirectionalGRU<Float>( GRUCell(inputSize: 3, hiddenSize: 4), mergeFunction: GRUCell<Float>.State.average ) XCTAssertEqual(gru.forward.cell.updateKernel.shape, updateKernelForward.shape) XCTAssertEqual(gru.forward.cell.updateRecurrentKernel.shape, updateRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.resetKernel.shape, resetKernelForward.shape) XCTAssertEqual(gru.forward.cell.resetRecurrentKernel.shape, resetRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.outputKernel.shape, outputKernelForward.shape) XCTAssertEqual(gru.forward.cell.outputRecurrentKernel.shape, outputRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.updateBias.shape, updateBiasForward.shape) XCTAssertEqual(gru.forward.cell.updateRecurrentBias.shape, updateRecurrentBiasForward.shape) XCTAssertEqual(gru.forward.cell.resetBias.shape, resetBiasForward.shape) XCTAssertEqual(gru.forward.cell.resetRecurrentBias.shape, resetRecurrentBiasForward.shape) XCTAssertEqual(gru.forward.cell.outputBias.shape, outputBiasForward.shape) XCTAssertEqual(gru.forward.cell.outputRecurrentBias.shape, outputRecurrentBiasForward.shape) XCTAssertEqual(gru.backward.cell.updateKernel.shape, updateKernelBackward.shape) XCTAssertEqual(gru.backward.cell.updateRecurrentKernel.shape, updateRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.resetKernel.shape, resetKernelBackward.shape) XCTAssertEqual(gru.backward.cell.resetRecurrentKernel.shape, resetRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.outputKernel.shape, outputKernelBackward.shape) XCTAssertEqual(gru.backward.cell.outputRecurrentKernel.shape, outputRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.updateBias.shape, updateBiasBackward.shape) XCTAssertEqual(gru.backward.cell.updateRecurrentBias.shape, updateRecurrentBiasBackward.shape) XCTAssertEqual(gru.backward.cell.resetBias.shape, resetBiasBackward.shape) XCTAssertEqual(gru.backward.cell.resetRecurrentBias.shape, resetRecurrentBiasBackward.shape) XCTAssertEqual(gru.backward.cell.outputBias.shape, outputBiasBackward.shape) XCTAssertEqual(gru.backward.cell.outputRecurrentBias.shape, outputRecurrentBiasBackward.shape) gru.forward.cell.updateKernel = updateKernelForward gru.forward.cell.updateRecurrentKernel = updateRecurrentKernelForward gru.forward.cell.resetKernel = resetKernelForward gru.forward.cell.resetRecurrentKernel = resetRecurrentKernelForward gru.forward.cell.outputKernel = outputKernelForward gru.forward.cell.outputRecurrentKernel = outputRecurrentKernelForward gru.forward.cell.updateBias = updateBiasForward gru.forward.cell.updateRecurrentBias = updateRecurrentBiasForward gru.forward.cell.resetBias = resetBiasForward gru.forward.cell.resetRecurrentBias = resetRecurrentBiasForward gru.forward.cell.outputBias = outputBiasForward gru.forward.cell.outputRecurrentBias = outputRecurrentBiasForward gru.backward.cell.updateKernel = updateKernelBackward gru.backward.cell.updateRecurrentKernel = updateRecurrentKernelBackward gru.backward.cell.resetKernel = resetKernelBackward gru.backward.cell.resetRecurrentKernel = resetRecurrentKernelBackward gru.backward.cell.outputKernel = outputKernelBackward gru.backward.cell.outputRecurrentKernel = outputRecurrentKernelBackward gru.backward.cell.updateBias = updateBiasBackward gru.backward.cell.updateRecurrentBias = updateRecurrentBiasBackward gru.backward.cell.resetBias = resetBiasBackward gru.backward.cell.resetRecurrentBias = resetRecurrentBiasBackward gru.backward.cell.outputBias = outputBiasBackward gru.backward.cell.outputRecurrentBias = outputRecurrentBiasBackward let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = GRUCell<Float>.State(initialForwardLayerState) let initialBackwardLayerState = GRUCell<Float>.State(initialBackwardLayerState) let outputs = gru( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ) assertEqual( Tensor(concatenating: outputs), expectedStates, accuracy: 1e-6) let (outputSum, (gradGRU)) = valueWithGradient(at: gru) { gru in gru.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateKernel, expectedGradUpdateKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetKernel, expectedGradResetKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputKernel, expectedGradOutputKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateRecurrentKernel, expectedGradUpdateRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetRecurrentKernel, expectedGradResetRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputRecurrentKernel, expectedGradOutputRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateBias, expectedGradUpdateBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetBias, expectedGradResetBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputBias, expectedGradOutputBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateRecurrentBias, expectedGradUpdateRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetRecurrentBias, expectedGradResetRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputRecurrentBias, expectedGradOutputRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateKernel, expectedGradUpdateKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetKernel, expectedGradResetKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputKernel, expectedGradOutputKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateRecurrentKernel, expectedGradUpdateRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetRecurrentKernel, expectedGradResetRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputRecurrentKernel, expectedGradOutputRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateBias, expectedGradUpdateBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetBias, expectedGradResetBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputBias, expectedGradOutputBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateRecurrentBias, expectedGradUpdateRecurrentBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetRecurrentBias, expectedGradResetRecurrentBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputRecurrentBias, expectedGradOutputRecurrentBiasBackward, accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in gru.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward, expectedGradInitialStateForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward, expectedGradInitialStateBackward, accuracy: 1e-6) } #endif } func testBidirectionalGRUMultiplyMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_gru.py --merge-mode mul". // BEGIN GENERATED CODE let updateKernelForward = Tensor<Float>( [[-0.26313293,-0.37116733,0.044766128,0.07748526], [0.09139812,-0.17107481,-0.1005373,0.16451049], [0.22751534,0.04139793,0.32446748,-0.572471]] ) let resetKernelForward = Tensor<Float>( [[-0.10539937,0.38937503,-0.008569658,0.6300892], [0.5234366,0.20446932,0.42181438,-0.5262561], [-0.5687402,0.31843305,-0.4139892,-0.23788527]] ) let outputKernelForward = Tensor<Float>( [[0.24885243,-0.4738691,0.26539946,0.2054413], [-0.27858475,-0.6128201,0.28634238,0.33588284], [-0.2638935,-0.5053163,-0.42289674,0.34110242]] ) let updateRecurrentKernelForward = Tensor<Float>( [[0.27225327,-0.04530505,0.20488906,-0.70477146], [0.1233796,-0.2725925,-0.21331471,0.45468533], [-0.12901938,-0.5375645,-0.07981183,-0.18903717], [0.2276715,0.6950712,0.06780873,0.121172115]] ) let resetRecurrentKernelForward = Tensor<Float>( [[-0.38362607,-0.03403465,-0.032581285,0.18508019], [-0.35768405,0.017118583,0.34339952,-0.015158445], [0.42593452,-0.51679564,-0.13895734,-0.2845649], [0.15196995,-0.4617733,-0.03934008,-0.038054474]] ) let outputRecurrentKernelForward = Tensor<Float>( [[-0.3531419,0.04921763,-0.050379246,-0.26801136], [-0.34328082,0.5067098,0.031886574,-0.19034609], [-0.020022772,0.16366726,0.021551719,-0.27538475], [0.002952166,0.31402355,-0.22738007,-0.23688485]] ) let updateBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateKernelBackward = Tensor<Float>( [[-0.38552743,0.30379778,-0.015429676,0.47474676], [0.24909449,-0.6272373,-0.17192209,0.08274299], [-0.41769588,-0.32856578,0.5987498,0.6109175]] ) let resetKernelBackward = Tensor<Float>( [[-0.11749339,-0.61405337,0.26505172,-0.17011762], [-0.23611891,0.18858898,0.6282174,-0.5656544], [-0.5848755,-0.014772236,0.007604778,0.5725722]] ) let outputKernelBackward = Tensor<Float>( [[0.10227531,0.5070258,-0.46571168,0.056879938], [0.49441308,-0.29395455,-0.07509631,0.29984736], [0.47141522,0.18345171,0.1791873,0.4368046]] ) let updateRecurrentKernelBackward = Tensor<Float>( [[0.3819934,0.37764925,0.015312237,-0.17769441], [-0.30984464,0.0024376288,-0.3083459,0.6083385], [-0.035942614,-0.24049878,0.19538112,-0.22652327], [0.06525053,0.14899497,-0.36888042,-0.2775943]] ) let resetRecurrentKernelBackward = Tensor<Float>( [[0.2151401,-0.21178766,-0.15712889,-0.078161664], [0.54615974,0.025927158,-0.061987586,-0.13631916], [0.61778206,-0.12979838,-0.19998191,0.32677993], [0.3122218,-0.3348464,-0.029183073,-0.08691845]] ) let outputRecurrentKernelBackward = Tensor<Float>( [[-0.64042187,0.34098455,-0.10449011,-0.14277793], [-0.07292092,0.24773169,0.21102233,0.07893403], [-0.029284794,-0.45729926,0.09502104,-0.29511455], [0.49253088,0.07420389,-0.48452082,0.2440229]] ) let updateBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.90076077,-0.7541278,-0.025081873], [0.37973404,-0.26513243,0.10235357], [0.3545239,-0.14615154,-0.540749], [-0.70222735,-0.34035724,-0.8451414]]] ) let initialForwardLayerState = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialBackwardLayerState = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let expectedSum = Tensor<Float>( -0.32895058 ) let expectedStates = Tensor<Float>( [[[0.04792786,-0.13482755,-0.22637701,-0.17096016], [0.005248314,-0.06652843,-0.095485054,-0.10619393], [-0.051071964,-0.14824535,-0.014771455,-0.0697825], [-0.067678906,-0.37781745,0.014962049,0.10158371]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those two and test it. // let expectedFinalStateForward = Tensor<Float>( // [[0.087087676,0.49491018,0.019275311,-0.13219076]] // ) // let expectedFinalStateBackward = Tensor<Float>( // [[-0.328244,-0.30765843,0.35560328,-0.37002444]] // ) let expectedGradX = Tensor<Float>( [[[-0.0045455527,-0.020066032,0.0030737333], [0.040171646,0.049551535,-0.0197279], [0.05888499,0.1390787,0.007269824], [0.0767434,0.15354612,-0.019848084]]] ) let expectedGradInitialStateForward = Tensor<Float>( [[0.07075158,-0.173892,0.09029196,-0.13666949]] ) let expectedGradUpdateKernelForward = Tensor<Float>( [[0.012366264,-0.08216441,-0.008099017,0.12655589], [0.00005636626,-0.0324539,0.02747383,0.117940515], [-0.0014967625,-0.07796255,0.040063504,0.12748465]] ) let expectedGradResetKernelForward = Tensor<Float>( [[-0.0076980656,-0.00063710264,0.0027035254,-0.0046277456], [-0.004731113,0.0055333427,0.0041351225,-0.0024739115], [-0.011927827,0.0085395295,0.0036171544,-0.0051743267]] ) let expectedGradOutputKernelForward = Tensor<Float>( [[0.20785503,-0.001673013,-0.25896353,0.10652162], [0.14713746,0.10674674,-0.23975003,0.18590957], [0.37952816,0.2001083,-0.46228534,0.25734156]] ) let expectedGradUpdateRecurrentKernelForward = Tensor<Float>( [[-0.0014494247,0.010546453,0.005384476,0.011515614], [0.0034076856,0.019562693,-0.035582643,-0.09373548], [-0.0065402063,0.0038736751,0.043143254,0.10498153], [0.004144326,0.011323398,-0.039187685,-0.13013235]] ) let expectedGradResetRecurrentKernelForward = Tensor<Float>( [[0.0012057752,0.0007886884,0.00077032676,0.00046306645], [0.00456115,-0.0072078817,-0.0036669155,0.001852406], [-0.0016002035,0.008008988,0.0047597894,-0.00071795564], [0.0024727562,-0.0071561057,-0.0052759107,0.0015336934]] ) let expectedGradOutputRecurrentKernelForward = Tensor<Float>( [[-0.019984528,0.0067213336,0.012130001,0.011362088], [-0.08117275,-0.06644401,0.1340633,-0.10929223], [0.032181997,0.07354428,-0.09417313,0.11926204], [-0.045114394,-0.06297048,0.10899238,-0.1180308]] ) let expectedGradUpdateBiasForward = Tensor<Float>( [0.009944006,0.076615654,-0.10517438,-0.28469688] ) let expectedGradResetBiasForward = Tensor<Float>( [0.015496891,-0.021194058,-0.010666848,0.0065090316] ) let expectedGradOutputBiasForward = Tensor<Float>( [-0.5120879,-0.4268308,0.7647575,-0.58130544] ) let expectedGradUpdateRecurrentBiasForward = Tensor<Float>( [0.009944006,0.076615654,-0.10517438,-0.28469688] ) let expectedGradResetRecurrentBiasForward = Tensor<Float>( [0.015496891,-0.021194058,-0.010666848,0.0065090316] ) let expectedGradOutputRecurrentBiasForward = Tensor<Float>( [-0.27554107,-0.19721822,0.42974865,-0.3239422] ) let expectedGradInitialStateBackward = Tensor<Float>( [[0.072507605,0.20855014,-0.011596381,-0.024698015]] ) let expectedGradUpdateKernelBackward = Tensor<Float>( [[0.007001178,-0.010822684,-0.002055459,-0.007135414], [0.0033933478,-0.0052455645,-0.0009962448,-0.0034584096], [0.0084260255,-0.013025266,-0.0024737765,-0.00858758]] ) let expectedGradResetKernelBackward = Tensor<Float>( [[-0.00057027227,0.016574344,-0.0006430624,-0.0044022617], [-0.00027640094,0.008033292,-0.00031168104,-0.0021336987], [-0.0006863314,0.019947477,-0.00077393546,-0.0052981894]] ) let expectedGradOutputKernelBackward = Tensor<Float>( [[-0.019521821,-0.07323406,-0.0046532946,0.03843088], [-0.0094618825,-0.035495263,-0.0022553701,0.018626772], [-0.023494812,-0.08813832,-0.005600312,0.046252154]] ) let expectedGradUpdateRecurrentKernelBackward = Tensor<Float>( [[0.0097614415,-0.015089602,-0.0028658381,-0.009948601], [0.0067881015,-0.010493302,-0.0019929025,-0.0069182524], [-0.010315799,0.01594655,0.0030285907,0.010513588], [0.0106320055,-0.016435353,-0.003121425,-0.010835856]] ) let expectedGradResetRecurrentKernelBackward = Tensor<Float>( [[-0.00079510605,0.023108894,-0.00089659425,-0.006137884], [-0.0005529164,0.016069913,-0.0006234912,-0.0042682816], [0.00084026065,-0.024421262,0.00094751234,0.0064864582], [-0.0008660168,0.025169836,-0.0009765561,-0.006685285]] ) let expectedGradOutputRecurrentKernelBackward = Tensor<Float>( [[-0.016170435,-0.07027604,-0.0026253306,0.032441556], [-0.011244912,-0.048869923,-0.0018256537,0.022559844], [0.017088763,0.07426706,0.0027744249,-0.034283932], [-0.017612576,-0.07654353,-0.002859468,0.035334826]] ) let expectedGradUpdateBiasBackward = Tensor<Float>( [-0.009969959,0.015411937,0.0029270563,0.010161117] ) let expectedGradResetBiasBackward = Tensor<Float>( [0.00081209064,-0.023602532,0.0009157467,0.0062689977] ) let expectedGradOutputBiasBackward = Tensor<Float>( [0.027799858,0.10428825,0.006626479,-0.05472712] ) let expectedGradUpdateRecurrentBiasBackward = Tensor<Float>( [-0.009969959,0.015411937,0.0029270563,0.010161117] ) let expectedGradResetRecurrentBiasBackward = Tensor<Float>( [0.00081209064,-0.023602532,0.0009157467,0.0062689977] ) let expectedGradOutputRecurrentBiasBackward = Tensor<Float>( [0.016515857,0.07177723,0.0026814113,-0.033134554] ) // END GENERATED CODE withTensorLeakChecking { var gru = BidirectionalGRU<Float>( GRUCell(inputSize: 3, hiddenSize: 4), mergeFunction: GRUCell<Float>.State.multiply ) XCTAssertEqual(gru.forward.cell.updateKernel.shape, updateKernelForward.shape) XCTAssertEqual(gru.forward.cell.updateRecurrentKernel.shape, updateRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.resetKernel.shape, resetKernelForward.shape) XCTAssertEqual(gru.forward.cell.resetRecurrentKernel.shape, resetRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.outputKernel.shape, outputKernelForward.shape) XCTAssertEqual(gru.forward.cell.outputRecurrentKernel.shape, outputRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.updateBias.shape, updateBiasForward.shape) XCTAssertEqual(gru.forward.cell.updateRecurrentBias.shape, updateRecurrentBiasForward.shape) XCTAssertEqual(gru.forward.cell.resetBias.shape, resetBiasForward.shape) XCTAssertEqual(gru.forward.cell.resetRecurrentBias.shape, resetRecurrentBiasForward.shape) XCTAssertEqual(gru.forward.cell.outputBias.shape, outputBiasForward.shape) XCTAssertEqual(gru.forward.cell.outputRecurrentBias.shape, outputRecurrentBiasForward.shape) XCTAssertEqual(gru.backward.cell.updateKernel.shape, updateKernelBackward.shape) XCTAssertEqual(gru.backward.cell.updateRecurrentKernel.shape, updateRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.resetKernel.shape, resetKernelBackward.shape) XCTAssertEqual(gru.backward.cell.resetRecurrentKernel.shape, resetRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.outputKernel.shape, outputKernelBackward.shape) XCTAssertEqual(gru.backward.cell.outputRecurrentKernel.shape, outputRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.updateBias.shape, updateBiasBackward.shape) XCTAssertEqual(gru.backward.cell.updateRecurrentBias.shape, updateRecurrentBiasBackward.shape) XCTAssertEqual(gru.backward.cell.resetBias.shape, resetBiasBackward.shape) XCTAssertEqual(gru.backward.cell.resetRecurrentBias.shape, resetRecurrentBiasBackward.shape) XCTAssertEqual(gru.backward.cell.outputBias.shape, outputBiasBackward.shape) XCTAssertEqual(gru.backward.cell.outputRecurrentBias.shape, outputRecurrentBiasBackward.shape) gru.forward.cell.updateKernel = updateKernelForward gru.forward.cell.updateRecurrentKernel = updateRecurrentKernelForward gru.forward.cell.resetKernel = resetKernelForward gru.forward.cell.resetRecurrentKernel = resetRecurrentKernelForward gru.forward.cell.outputKernel = outputKernelForward gru.forward.cell.outputRecurrentKernel = outputRecurrentKernelForward gru.forward.cell.updateBias = updateBiasForward gru.forward.cell.updateRecurrentBias = updateRecurrentBiasForward gru.forward.cell.resetBias = resetBiasForward gru.forward.cell.resetRecurrentBias = resetRecurrentBiasForward gru.forward.cell.outputBias = outputBiasForward gru.forward.cell.outputRecurrentBias = outputRecurrentBiasForward gru.backward.cell.updateKernel = updateKernelBackward gru.backward.cell.updateRecurrentKernel = updateRecurrentKernelBackward gru.backward.cell.resetKernel = resetKernelBackward gru.backward.cell.resetRecurrentKernel = resetRecurrentKernelBackward gru.backward.cell.outputKernel = outputKernelBackward gru.backward.cell.outputRecurrentKernel = outputRecurrentKernelBackward gru.backward.cell.updateBias = updateBiasBackward gru.backward.cell.updateRecurrentBias = updateRecurrentBiasBackward gru.backward.cell.resetBias = resetBiasBackward gru.backward.cell.resetRecurrentBias = resetRecurrentBiasBackward gru.backward.cell.outputBias = outputBiasBackward gru.backward.cell.outputRecurrentBias = outputRecurrentBiasBackward let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = GRUCell<Float>.State(initialForwardLayerState) let initialBackwardLayerState = GRUCell<Float>.State(initialBackwardLayerState) let outputs = gru( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ) assertEqual( Tensor(concatenating: outputs), expectedStates, accuracy: 1e-6) let (outputSum, (gradGRU)) = valueWithGradient(at: gru) { gru in gru.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateKernel, expectedGradUpdateKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetKernel, expectedGradResetKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputKernel, expectedGradOutputKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateRecurrentKernel, expectedGradUpdateRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetRecurrentKernel, expectedGradResetRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputRecurrentKernel, expectedGradOutputRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateBias, expectedGradUpdateBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetBias, expectedGradResetBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputBias, expectedGradOutputBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateRecurrentBias, expectedGradUpdateRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetRecurrentBias, expectedGradResetRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputRecurrentBias, expectedGradOutputRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateKernel, expectedGradUpdateKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetKernel, expectedGradResetKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputKernel, expectedGradOutputKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateRecurrentKernel, expectedGradUpdateRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetRecurrentKernel, expectedGradResetRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputRecurrentKernel, expectedGradOutputRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateBias, expectedGradUpdateBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetBias, expectedGradResetBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputBias, expectedGradOutputBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateRecurrentBias, expectedGradUpdateRecurrentBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetRecurrentBias, expectedGradResetRecurrentBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputRecurrentBias, expectedGradOutputRecurrentBiasBackward, accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in gru.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward, expectedGradInitialStateForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward, expectedGradInitialStateBackward, accuracy: 1e-6) } #endif } func testBidirectionalGRUStackMerge() { #if !SR15884_WORKAROUND_1 // Data generated by "Utilities/ReferenceImplementations/bidirectional_gru.py --merge-mode none". // BEGIN GENERATED CODE let updateKernelForward = Tensor<Float>( [[-0.26313293,-0.37116733,0.044766128,0.07748526], [0.09139812,-0.17107481,-0.1005373,0.16451049], [0.22751534,0.04139793,0.32446748,-0.572471]] ) let resetKernelForward = Tensor<Float>( [[-0.10539937,0.38937503,-0.008569658,0.6300892], [0.5234366,0.20446932,0.42181438,-0.5262561], [-0.5687402,0.31843305,-0.4139892,-0.23788527]] ) let outputKernelForward = Tensor<Float>( [[0.24885243,-0.4738691,0.26539946,0.2054413], [-0.27858475,-0.6128201,0.28634238,0.33588284], [-0.2638935,-0.5053163,-0.42289674,0.34110242]] ) let updateRecurrentKernelForward = Tensor<Float>( [[0.27225327,-0.04530505,0.20488906,-0.70477146], [0.1233796,-0.2725925,-0.21331471,0.45468533], [-0.12901938,-0.5375645,-0.07981183,-0.18903717], [0.2276715,0.6950712,0.06780873,0.121172115]] ) let resetRecurrentKernelForward = Tensor<Float>( [[-0.38362607,-0.03403465,-0.032581285,0.18508019], [-0.35768405,0.017118583,0.34339952,-0.015158445], [0.42593452,-0.51679564,-0.13895734,-0.2845649], [0.15196995,-0.4617733,-0.03934008,-0.038054474]] ) let outputRecurrentKernelForward = Tensor<Float>( [[-0.3531419,0.04921763,-0.050379246,-0.26801136], [-0.34328082,0.5067098,0.031886574,-0.19034609], [-0.020022772,0.16366726,0.021551719,-0.27538475], [0.002952166,0.31402355,-0.22738007,-0.23688485]] ) let updateBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputRecurrentBiasForward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateKernelBackward = Tensor<Float>( [[-0.38552743,0.30379778,-0.015429676,0.47474676], [0.24909449,-0.6272373,-0.17192209,0.08274299], [-0.41769588,-0.32856578,0.5987498,0.6109175]] ) let resetKernelBackward = Tensor<Float>( [[-0.11749339,-0.61405337,0.26505172,-0.17011762], [-0.23611891,0.18858898,0.6282174,-0.5656544], [-0.5848755,-0.014772236,0.007604778,0.5725722]] ) let outputKernelBackward = Tensor<Float>( [[0.10227531,0.5070258,-0.46571168,0.056879938], [0.49441308,-0.29395455,-0.07509631,0.29984736], [0.47141522,0.18345171,0.1791873,0.4368046]] ) let updateRecurrentKernelBackward = Tensor<Float>( [[0.3819934,0.37764925,0.015312237,-0.17769441], [-0.30984464,0.0024376288,-0.3083459,0.6083385], [-0.035942614,-0.24049878,0.19538112,-0.22652327], [0.06525053,0.14899497,-0.36888042,-0.2775943]] ) let resetRecurrentKernelBackward = Tensor<Float>( [[0.2151401,-0.21178766,-0.15712889,-0.078161664], [0.54615974,0.025927158,-0.061987586,-0.13631916], [0.61778206,-0.12979838,-0.19998191,0.32677993], [0.3122218,-0.3348464,-0.029183073,-0.08691845]] ) let outputRecurrentKernelBackward = Tensor<Float>( [[-0.64042187,0.34098455,-0.10449011,-0.14277793], [-0.07292092,0.24773169,0.21102233,0.07893403], [-0.029284794,-0.45729926,0.09502104,-0.29511455], [0.49253088,0.07420389,-0.48452082,0.2440229]] ) let updateBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let updateRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let resetRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let outputRecurrentBiasBackward = Tensor<Float>( [0.0,0.0,0.0,0.0] ) let x = Tensor<Float>( [[[-0.90076077,-0.7541278,-0.025081873], [0.37973404,-0.26513243,0.10235357], [0.3545239,-0.14615154,-0.540749], [-0.70222735,-0.34035724,-0.8451414]]] ) let initialForwardLayerState = Tensor<Float>( [[-0.22500783,0.3640524,-0.76411664,1.0557337]] ) let initialBackwardLayerState = Tensor<Float>( [[-0.9790854,-0.6808555,1.0346882,-1.0664041]] ) let expectedSum = Tensor<Float>( -1.0636933 ) let expectedStatesForward = Tensor<Float>( [[[-0.1460129,0.4382378,-0.6365999,0.46202397], [-0.0246071,0.29749468,-0.35770136,0.2921221], [0.10575074,0.28877518,-0.03438914,0.12433955], [0.087087676,0.49491018,0.019275311,-0.13219076]]] ) let expectedStatesBackward = Tensor<Float>( [[[-0.328244,-0.30765843,0.35560328,-0.37002444], [-0.21328454,-0.22362898,0.2669407,-0.36352584], [-0.48294663,-0.51335907,0.4295384,-0.5612253], [-0.7771353,-0.7634061,0.77622867,-0.768463]]] ) // TODO: Modify BidirectionalRecurrentLayer to return those two and test it. // let expectedFinalStateForward = Tensor<Float>( // [[0.087087676,0.49491018,0.019275311,-0.13219076]] // ) // let expectedFinalStateBackward = Tensor<Float>( // [[-0.328244,-0.30765843,0.35560328,-0.37002444]] // ) let expectedGradX = Tensor<Float>( [[[0.016884292,0.031954587,-0.03463035], [-0.03014597,-0.03283064,-0.09927187], [0.010677524,-0.065554164,-0.24680781], [0.36794654,0.22227536,0.035613716]]] ) let expectedGradInitialStateForward = Tensor<Float>( [[-0.07189825,0.2649164,0.021249592,0.0997324]] ) let expectedGradUpdateKernelForward = Tensor<Float>( [[-0.014633491,0.11262925,-0.012467325,-0.14178306], [-0.0015309689,0.04380424,0.026814379,-0.11768658], [0.00066331076,0.10263122,0.050961565,-0.15763284]] ) let expectedGradResetKernelForward = Tensor<Float>( [[0.010167455,0.001237556,0.0016463955,0.005614992], [0.005910287,-0.007958792,0.0032499037,0.0029476206], [0.015130447,-0.011363849,0.0046043447,0.006548183]] ) let expectedGradOutputKernelForward = Tensor<Float>( [[-0.27720484,0.011210179,-0.31191894,-0.15031563], [-0.17816868,-0.1504507,-0.267022,-0.19132887], [-0.47820407,-0.2667625,-0.59290844,-0.3111684]] ) let expectedGradUpdateRecurrentKernelForward = Tensor<Float>( [[0.0013306538,-0.013751614,0.0037764874,-0.0035531232], [-0.0023589553,-0.02471057,-0.03806296,0.09600505], [0.005533043,-0.0055813985,0.042736374,-0.091018684], [-0.0028463867,-0.01618819,-0.037352134,0.116344094]] ) let expectedGradResetRecurrentKernelForward = Tensor<Float>( [[-0.0016176908,-0.0013255395,0.00032072363,-0.0006573718], [-0.0055763978,0.010337391,-0.0034352664,-0.0023184754], [0.0016612076,-0.011832551,0.0036965827,0.00072100235], [-0.0028628542,0.010542514,-0.0038019945,-0.0016213773]] ) let expectedGradOutputRecurrentKernelForward = Tensor<Float>( [[0.027280932,-0.011064238,0.022760907,-0.0044778143], [0.09789747,0.09476159,0.15628885,0.109026045], [-0.03227183,-0.10743488,-0.09318911,-0.10548531], [0.05016677,0.09146461,0.10986483,0.107886836]] ) let expectedGradUpdateBiasForward = Tensor<Float>( [-0.0071913204,-0.09881051,-0.11562111,0.2993651] ) let expectedGradResetBiasForward = Tensor<Float>( [-0.019118855,0.0300491,-0.010341872,-0.008104472] ) let expectedGradOutputBiasForward = Tensor<Float>( [0.61583984,0.5973235,0.9004895,0.605246] ) let expectedGradUpdateRecurrentBiasForward = Tensor<Float>( [-0.0071913204,-0.09881051,-0.11562111,0.2993651] ) let expectedGradResetRecurrentBiasForward = Tensor<Float>( [-0.019118855,0.0300491,-0.010341872,-0.008104472] ) let expectedGradOutputRecurrentBiasForward = Tensor<Float>( [0.33583188,0.27820933,0.5110848,0.33206433] ) let expectedGradInitialStateBackward = Tensor<Float>( [[0.43691894,0.39781284,0.48556933,0.3400339]] ) let expectedGradUpdateKernelBackward = Tensor<Float>( [[0.080392286,-0.02186797,-0.106636874,0.05397816], [0.038964726,-0.010599021,-0.051685017,0.026162265], [0.09675335,-0.026318438,-0.12833911,0.06496355]] ) let expectedGradResetKernelBackward = Tensor<Float>( [[-0.006548254,0.033489596,-0.03336197,0.033302337], [-0.0031738235,0.016231818,-0.016169962,0.016141057], [-0.007880924,0.040305246,-0.04015165,0.040079877]] ) let expectedGradOutputKernelBackward = Tensor<Float>( [[-0.22416282,-0.14797445,-0.24141216,-0.29072288], [-0.10864778,-0.071720615,-0.11700823,-0.14090827], [-0.2697834,-0.17808953,-0.29054326,-0.34988946]] ) let expectedGradUpdateRecurrentKernelBackward = Tensor<Float>( [[0.11208751,-0.03048957,-0.14867921,0.07525943], [0.0779456,-0.021202432,-0.10339145,0.05233537], [-0.118453026,0.03222109,0.15712279,-0.07953346], [0.12208392,-0.03320875,-0.16193901,0.08197136]] ) let expectedGradResetRecurrentKernelBackward = Tensor<Float>( [[-0.009129949,0.046693105,-0.046515163,0.04643202], [-0.006348962,0.032470364,-0.03234662,0.032288805], [0.009648444,-0.049344834,0.04915679,-0.04906892], [-0.009944194,0.05085738,-0.050663568,0.05057301]] ) let expectedGradOutputRecurrentKernelBackward = Tensor<Float>( [[-0.18567993,-0.14199756,-0.13620174,-0.24541469], [-0.12912174,-0.09874504,-0.09471462,-0.17066126], [0.1962248,0.1500617,0.14393671,0.25935194], [-0.2022396,-0.15466146,-0.14834875,-0.26730174]] ) let expectedGradUpdateBiasBackward = Tensor<Float>( [-0.11448185,0.03114087,0.1518552,-0.076867074] ) let expectedGradResetBiasBackward = Tensor<Float>( [0.009324977,-0.047690533,0.04750879,-0.04742387] ) let expectedGradOutputBiasBackward = Tensor<Float>( [0.31921688,0.21072157,0.34378064,0.41400108] ) let expectedGradUpdateRecurrentBiasBackward = Tensor<Float>( [-0.11448185,0.03114087,0.1518552,-0.076867074] ) let expectedGradResetRecurrentBiasBackward = Tensor<Float>( [0.009324977,-0.047690533,0.04750879,-0.04742387] ) let expectedGradOutputRecurrentBiasBackward = Tensor<Float>( [0.1896463,0.14503083,0.13911119,0.25065708] ) // END GENERATED CODE withTensorLeakChecking { var gru = BidirectionalGRU<Float>( GRUCell(inputSize: 3, hiddenSize: 4), mergeFunction: GRUCell<Float>.State.stack ) XCTAssertEqual(gru.forward.cell.updateKernel.shape, updateKernelForward.shape) XCTAssertEqual(gru.forward.cell.updateRecurrentKernel.shape, updateRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.resetKernel.shape, resetKernelForward.shape) XCTAssertEqual(gru.forward.cell.resetRecurrentKernel.shape, resetRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.outputKernel.shape, outputKernelForward.shape) XCTAssertEqual(gru.forward.cell.outputRecurrentKernel.shape, outputRecurrentKernelForward.shape) XCTAssertEqual(gru.forward.cell.updateBias.shape, updateBiasForward.shape) XCTAssertEqual(gru.forward.cell.updateRecurrentBias.shape, updateRecurrentBiasForward.shape) XCTAssertEqual(gru.forward.cell.resetBias.shape, resetBiasForward.shape) XCTAssertEqual(gru.forward.cell.resetRecurrentBias.shape, resetRecurrentBiasForward.shape) XCTAssertEqual(gru.forward.cell.outputBias.shape, outputBiasForward.shape) XCTAssertEqual(gru.forward.cell.outputRecurrentBias.shape, outputRecurrentBiasForward.shape) XCTAssertEqual(gru.backward.cell.updateKernel.shape, updateKernelBackward.shape) XCTAssertEqual(gru.backward.cell.updateRecurrentKernel.shape, updateRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.resetKernel.shape, resetKernelBackward.shape) XCTAssertEqual(gru.backward.cell.resetRecurrentKernel.shape, resetRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.outputKernel.shape, outputKernelBackward.shape) XCTAssertEqual(gru.backward.cell.outputRecurrentKernel.shape, outputRecurrentKernelBackward.shape) XCTAssertEqual(gru.backward.cell.updateBias.shape, updateBiasBackward.shape) XCTAssertEqual(gru.backward.cell.updateRecurrentBias.shape, updateRecurrentBiasBackward.shape) XCTAssertEqual(gru.backward.cell.resetBias.shape, resetBiasBackward.shape) XCTAssertEqual(gru.backward.cell.resetRecurrentBias.shape, resetRecurrentBiasBackward.shape) XCTAssertEqual(gru.backward.cell.outputBias.shape, outputBiasBackward.shape) XCTAssertEqual(gru.backward.cell.outputRecurrentBias.shape, outputRecurrentBiasBackward.shape) gru.forward.cell.updateKernel = updateKernelForward gru.forward.cell.updateRecurrentKernel = updateRecurrentKernelForward gru.forward.cell.resetKernel = resetKernelForward gru.forward.cell.resetRecurrentKernel = resetRecurrentKernelForward gru.forward.cell.outputKernel = outputKernelForward gru.forward.cell.outputRecurrentKernel = outputRecurrentKernelForward gru.forward.cell.updateBias = updateBiasForward gru.forward.cell.updateRecurrentBias = updateRecurrentBiasForward gru.forward.cell.resetBias = resetBiasForward gru.forward.cell.resetRecurrentBias = resetRecurrentBiasForward gru.forward.cell.outputBias = outputBiasForward gru.forward.cell.outputRecurrentBias = outputRecurrentBiasForward gru.backward.cell.updateKernel = updateKernelBackward gru.backward.cell.updateRecurrentKernel = updateRecurrentKernelBackward gru.backward.cell.resetKernel = resetKernelBackward gru.backward.cell.resetRecurrentKernel = resetRecurrentKernelBackward gru.backward.cell.outputKernel = outputKernelBackward gru.backward.cell.outputRecurrentKernel = outputRecurrentKernelBackward gru.backward.cell.updateBias = updateBiasBackward gru.backward.cell.updateRecurrentBias = updateRecurrentBiasBackward gru.backward.cell.resetBias = resetBiasBackward gru.backward.cell.resetRecurrentBias = resetRecurrentBiasBackward gru.backward.cell.outputBias = outputBiasBackward gru.backward.cell.outputRecurrentBias = outputRecurrentBiasBackward let inputs = x.squeezingShape(at: 0).unstacked().map { $0.rankLifted() } let initialForwardLayerState = GRUCell<Float>.State(initialForwardLayerState) let initialBackwardLayerState = GRUCell<Float>.State(initialBackwardLayerState) let outputs = gru( inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).map { $0.unstacked(alongAxis: 0) } assertEqual( Tensor(concatenating: outputs.map { $0[0] }), expectedStatesForward, accuracy: 1e-6) assertEqual( Tensor(concatenating: outputs.map { $0[1] }), expectedStatesBackward, accuracy: 1e-6) let (outputSum, (gradGRU)) = valueWithGradient(at: gru) { gru in gru.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( outputSum, expectedSum, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateKernel, expectedGradUpdateKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetKernel, expectedGradResetKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputKernel, expectedGradOutputKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateRecurrentKernel, expectedGradUpdateRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetRecurrentKernel, expectedGradResetRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputRecurrentKernel, expectedGradOutputRecurrentKernelForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateBias, expectedGradUpdateBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetBias, expectedGradResetBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputBias, expectedGradOutputBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.updateRecurrentBias, expectedGradUpdateRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.resetRecurrentBias, expectedGradResetRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.forward.cell.outputRecurrentBias, expectedGradOutputRecurrentBiasForward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateKernel, expectedGradUpdateKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetKernel, expectedGradResetKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputKernel, expectedGradOutputKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateRecurrentKernel, expectedGradUpdateRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetRecurrentKernel, expectedGradResetRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputRecurrentKernel, expectedGradOutputRecurrentKernelBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateBias, expectedGradUpdateBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetBias, expectedGradResetBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputBias, expectedGradOutputBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.updateRecurrentBias, expectedGradUpdateRecurrentBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.resetRecurrentBias, expectedGradResetRecurrentBiasBackward, accuracy: 1e-6) assertEqual( gradGRU.backward.cell.outputRecurrentBias, expectedGradOutputRecurrentBiasBackward, accuracy: 1e-6) let (gradInputs, gradInitialStateForward, gradInitialStateBackward) = gradient(at: inputs, initialForwardLayerState, initialBackwardLayerState) { inputs, initialForwardLayerState, initialBackwardLayerState in gru.lastOutput( from: inputs, initialForwardLayerState: initialForwardLayerState, initialBackwardLayerState: initialBackwardLayerState ).sum() } assertEqual( Tensor(concatenating: gradInputs.map { $0 }), expectedGradX, accuracy: 1e-6) assertEqual( gradInitialStateForward, expectedGradInitialStateForward, accuracy: 1e-6) assertEqual( gradInitialStateBackward, expectedGradInitialStateBackward, accuracy: 1e-6) } #endif } func testFunction() { let tanhLayer = Function<Tensor<Float>, Tensor<Float>>(tanh) let input = Tensor(shape: [5, 1], scalars: (0..<5).map(Float.init)) let output = tanhLayer.inferring(from: input) let expected = Tensor<Float>([[0.0], [0.7615942], [0.9640276], [0.9950547], [0.9993292]]) assertEqual(output, expected, accuracy: 1e-6) } func testBatchNorm() { let x = Tensor<Float>([ [-1.0474433, -0.11914538, -0.08634827, 0.15446888, 1.0572497], [1.5165012, 0.3753972, -0.30856386, -0.3100725, -1.9584457], [0.006384419, 1.4424847, 0.91568077, 0.66328526, -1.0794537], [1.056803, 0.14263044, -1.8308276, 0.4189805, 0.6933893], [0.30175626, -0.16121633, -0.4191958, -0.53092813, -0.029484272], ]) let bnLayer = BatchNorm<Float>(featureCount: 5, axis: 0) Context.local.learningPhase = .training withTensorLeakChecking { let output = bnLayer(x) let grad = gradient(at: x, bnLayer) { $1($0).squared().sum() } // The expected values and gradients were computed using the following Python code: // ``` // import tensorflow as tf // x = tf.constant( // [[ -1.0474433, -0.11914538, -0.08634827, 0.15446888, 1.0572497], // [ 1.5165012, 0.3753972, -0.30856386, -0.3100725, -1.9584457], // [ 0.006384419, 1.4424847, 0.91568077, 0.66328526, -1.0794537], // [ 1.056803, 0.14263044, -1.8308276, 0.4189805, 0.6933893], // [ 0.30175626, -0.16121633, -0.4191958, -0.53092813, -0.029484272]]) // scale = tf.reshape(tf.constant([1., 1., 1., 1., 1.]), [5, 1]) // offset = tf.reshape(tf.constant([0., 0., 0., 0., 0.]), [5, 1]) // (mean, var) = tf.nn.moments(x, axes=1, keepdims=True) // bn = tf.nn.batch_normalization(x, mean, var, offset=offset, scale=scale, // variance_epsilon=0.001) // scaled = tf.reduce_sum(tf.square(bn)) // g = tf.gradients(scaled, [x, offset, scale]) // init = tf.initialize_all_variables() // with tf.Session() as sess: // sess.run(init) // print(sess.run([bn, g])) // ``` assertEqual( output, [ [-1.5439795, -0.16477099, -0.11604305, 0.24174842, 1.5830451], [1.4639764, 0.45368853, -0.15186328, -0.15319899, -1.6126028], [-0.44139984, 1.2124169, 0.60574806, 0.3150888, -1.6918538], [0.9507547, 0.04595902, -1.9072568, 0.31947452, 0.5910686], [1.5834246, 0.02224666, -0.8476793, -1.2244489, 0.46645695], ], accuracy: 1e-5) assertEqual( grad.0, [ [-1.0127544e-02, -1.0807812e-03, -7.6115131e-04, 1.5857220e-03, 1.0383606e-02], [2.0323221e-03, 6.2976527e-04, -2.1077941e-04, -2.1265696e-04, -2.2384699e-03], [-1.3483668e-03, 3.7030075e-03, 1.8500184e-03, 9.6232636e-04, -5.1673558e-03], [1.8438101e-03, 8.9146197e-05, -3.6990643e-03, 6.1964989e-04, 1.1463165e-03], [1.2142579e-01, 1.7060755e-03, -6.5005139e-02, -9.3897656e-02, 3.5770576e-02], ], accuracy: 1e-5) assertEqual(grad.1.offset, [0.0, 0.0, 0.0, 0.0, 0.0], accuracy: 1e-5) assertEqual( grad.1.scale, [9.977925, 9.992161, 9.986738, 9.990202, 9.886292], accuracy: 1e-5) } } func testBatchNormInference() { Context.local.learningPhase = .inference // This tests for a specific failure that had impacted the MiniGo model. let miniGoTensor = Tensor<Float>(randomUniform: [2, 19, 19, 256]) let miniGoBatchNorm = BatchNorm<Float>(featureCount: 256, momentum: 0.95, epsilon: 1e-5) let miniGoResult = miniGoBatchNorm(miniGoTensor) XCTAssertEqual(miniGoTensor.shape, miniGoResult.shape) let x = Tensor<Float>(rangeFrom: 0, to: 20, stride: 1).reshaped(to: [4, 5]) let epsilon: Float = 0.001 let bnLayer = BatchNorm<Float>(featureCount: 5, axis: 1, epsilon: epsilon) // Test inference before any training. assertEqual(bnLayer.inferring(from: x), x / TensorFlow.sqrt(Tensor<Float>(1 + epsilon)), accuracy: 1e-5) // Perform one training step, updating the running mean and variance. Context.local.learningPhase = .training _ = bnLayer(x) // This line is important and cannot be removed. // Test inference after training step. // The expected value was computed using the following Python code: // ``` // import tensorflow as tf // x = tf.reshape(tf.range(20, dtype=tf.float32), [4,5]) // bn = tf.nn.batch_normalization(x, mean, var, offset=offset, scale=scale, // variance_epsilon=0.001) // y_train = bnLayer(x, training=True) // y = bnLayer(x, training=False) // print(y) // ``` assertEqual( bnLayer.inferring(from: x), [ [-0.06569097, 0.8014299, 1.6685508, 2.5356717, 3.4027927], [4.3137074, 5.180828, 6.0479493, 6.91507, 7.7821913], [8.693106, 9.560227, 10.427347, 11.294469, 12.16159], [13.072505, 13.939626, 14.806746, 15.673867, 16.540987], ], accuracy: 1e-5) } func testLayerNorm() { let x = Tensor<Float>([ [2.736876, -0.8932728, -0.11240143, 1.252899, -0.35648823], [-0.43356904, -0.5147881, 0.8055815, 0.97228354, 1.4561518], [0.56300443, -0.87069905, -0.20677163, 1.1823419, 1.0455104], [-0.8246169, 1.4249208, 1.2131604, 1.1445689, -0.94032115], ]) let lnLayer = LayerNorm<Float>(featureCount: 5, axis: 1) let value = lnLayer(x) let grad = gradient(at: x, lnLayer) { $1($0).squared().sum() } // The expected values and gradients were computed using the following Python code: // ``` // import tensorflow as tf // x = tf.constant([[ 2.736876 , -0.8932728 , -0.11240143, 1.252899 , -0.35648823], // [-0.43356904, -0.5147881 , 0.8055815 , 0.97228354, 1.4561518 ], // [ 0.56300443, -0.87069905, -0.20677163, 1.1823419 , 1.0455104 ], // [-0.8246169 , 1.4249208 , 1.2131604 , 1.1445689 , -0.94032115]]) // lnLayer = tf.keras.layers.LayerNormalization(axis=1, epsilon=0.001) // with tf.GradientTape() as tape: // tape.watch(x) // y = lnLayer(x) // z = tf.math.reduce_sum(tf.math.square(y)) // print(y, tape.gradient(z, [x] + lnLayer.trainable_variables)) // ``` assertEqual( value, [ [1.6839857, -1.0804383, -0.4857906, 0.5539104, -0.6716671], [-1.1261504, -1.228839, 0.44055927, 0.6513276, 1.2631025], [0.28318238, -1.5595294, -0.70619607, 1.079205, 0.9033381], [-1.1639192, 0.96795416, 0.7672701, 0.70226634, -1.2735714], ], accuracy: 1e-5) assertEqual( grad.0, [ [0.00148721, -0.00095408, -0.00042902, 0.00048913, -0.00059323], [-0.00455132, -0.00496664, 0.00178061, 0.00263247, 0.00510535], [0.0012024, -0.00662184, -0.00299847, 0.00458241, 0.00383568], [-0.0019815, 0.00164783, 0.00130618, 0.00119543, -0.00216818], ], accuracy: 1e-5) assertEqual( grad.1.offset, [-0.645803, -5.8017054, 0.03168535, 5.973418, 0.44240427], accuracy: 1e-5) assertEqual( grad.1.scale, [11.077844, 12.092919, 3.0350027, 4.7778125, 8.969137], accuracy: 1e-5) } func testLayerNormInference() { Context.local.learningPhase = .inference // This tests for a specific failure that had impacted the Transformer model. let transformerTensor = Tensor<Float>(randomUniform: [1, 1, 768]) let transformerLayerNorm = LayerNorm<Float>(featureCount: 768, axis: -1, epsilon: 1e-5) let transformerResult = transformerLayerNorm(transformerTensor) XCTAssertEqual(transformerTensor.shape, transformerResult.shape) } func testGroupNorm() { // The expected values were computed using the following Python code: // ``` // import tensorflow as tf // import tensorflow_addons as tfa // x = tf.reshape(tf.range(24, dtype=tf.float32), [2, 2, 1, 6]) // layer = tfa.layers.GroupNormalization(groups=2) // with tf.GradientTape() as tape: // tape.watch(x) // y = layer(x) // z = tf.math.reduce_sum(tf.math.square(y)) // print(y, tape.gradient(z, [x] + layer.trainable_variables)) // ``` let tensor = Tensor<Float>(rangeFrom: 0, to: 24, stride: 1) .reshaped(to: [2, 2, 1, 6]) let layer = GroupNorm<Float>(featureCount: 6, groupCount: 2) let output = layer(tensor) let expectedOutput: Tensor<Float> = [ [ [[-1.2864685, -0.9648514, -0.64323425, -1.2864685, -0.9648514, -0.64323425]], [[0.64323425, 0.9648514, 1.2864685, 0.64323425, 0.9648514, 1.2864685]] ], [ [[-1.2864685, -0.9648514, -0.64323425, -1.2864685, -0.9648514, -0.64323425]], [[0.64323425, 0.9648514, 1.2864685, 0.64323425, 0.9648514, 1.2864685]] ] ] XCTAssert(output.isAlmostEqual(to: expectedOutput)) let grad = gradient(at: tensor, layer) { $1($0).squared().sum() } let expectedGrad: Tensor<Float> = [ [[[-8.5592270e-05, -6.4194202e-05, -4.2796135e-05, -8.5592270e-05, -6.4194202e-05, -4.2796135e-05]], [[4.2796135e-05, 6.4194202e-05, 8.5592270e-05, 4.2796135e-05, 6.4194202e-05, 8.5592270e-05]]], [[[-8.5592270e-05, -6.4194202e-05, -4.2796135e-05, -8.5592270e-05, -6.4194202e-05, -4.2796135e-05]], [[4.2796135e-05, 6.4194202e-05, 8.5592270e-05, 4.2796135e-05, 6.4194202e-05, 8.5592270e-05]]] ] XCTAssert(grad.0.isAlmostEqual(to: expectedGrad)) XCTAssert( grad.1.scale.isAlmostEqual(to: [ 8.275006, 7.4475055, 8.275006, 8.275006, 7.4475055, 8.275006 ])) XCTAssert( grad.1.offset.isAlmostEqual(to: [ -2.572937, 0, 2.572937, -2.572937, 0, 2.572937 ])) } func testInstanceNorm() { // The expected values were computed using the following Python code: // ``` // import tensorflow as tf // import tensorflow_addons as tfa // x = tf.reshape(tf.range(24, dtype=tf.float32), [2, 2, 1, 6]) // layer = tfa.layers.InstanceNormalization() // with tf.GradientTape() as tape: // tape.watch(x) // y = layer(x) // z = tf.math.reduce_sum(tf.math.square(y)) // print(y, tape.gradient(z, [x] + layer.trainable_variables)) // ``` let tensor = Tensor<Float>(rangeFrom: 0, to: 24, stride: 1) .reshaped(to: [2, 2, 1, 6]) let layer = InstanceNorm<Float>(featureCount: 6) let output = layer(tensor) let expected: Tensor<Float> = [ [ [[-0.99994445, -0.99994445, -0.9999444, -0.99994445, -0.9999443, -0.99994445]], [[0.99994445, 0.9999443, 0.99994445, 0.99994445, 0.99994445, 0.99994445]] ], [ [[-0.9999442, -0.9999442, -0.9999447, -0.9999447, -0.9999442, -0.9999442]], [[0.9999447, 0.9999442, 0.9999442, 0.9999442, 0.9999447, 0.9999447]] ] ] XCTAssertEqual(output, expected) let grad = gradient(at: tensor, layer) { $1($0).squared().sum() } let expectedGrad: Tensor<Float> = [ [[[-7.4148178e-05, -7.4108444e-05, -7.4108444e-05, -7.4088573e-05, -7.4068703e-05, -7.4148178e-05]], [[7.4148178e-05, 7.4068703e-05, 7.4128307e-05, 7.4088573e-05, 7.4108444e-05, 7.4148178e-05]]], [[[-7.4128300e-05, -7.4207783e-05, -7.4108451e-05, -7.4048847e-05, -7.4128300e-05, -7.4128300e-05]], [[7.4108451e-05, 7.4207783e-05, 7.4128300e-05, 7.4068696e-05, 7.4108451e-05, 7.4108451e-05]]] ] XCTAssert(grad.0.isAlmostEqual(to: expectedGrad)) XCTAssert( grad.1.delegate.scale .isAlmostEqual(to: [ 7.999111, 7.9991093, 7.9991107, 7.9991117, 7.999111, 7.99911 ])) XCTAssert( grad.1.delegate.offset .isAlmostEqual(to: [ 9.5367432e-07, -2.3841858e-07, -8.3446503e-07, -9.5367432e-07, 1.1920929e-06, 9.5367432e-07 ])) } func testGaussianNoise() { Context.local.learningPhase = .inference let gaussianNoise = GaussianNoise<Float>(standardDeviation: 1.0) let x = Tensor<Float>(repeating: 1.0, shape: [5, 5]) XCTAssertEqual(gaussianNoise(x), x) withLearningPhase(LearningPhase.inference) { XCTAssertEqual(gaussianNoise(x), x) withLearningPhase(LearningPhase.training) { XCTAssertNotEqual(gaussianNoise(x), x) } XCTAssertEqual(gaussianNoise(x), x) } XCTAssertEqual(gaussianNoise(x), x) } func testGaussianDropout() { Context.local.learningPhase = .inference let dropout = GaussianDropout<Float>(probability: 0.5) let x = Tensor<Float>(repeating: 1.0, shape: [5, 5]) XCTAssertEqual(dropout(x), x) withLearningPhase(LearningPhase.inference) { XCTAssertEqual(dropout(x), x) withLearningPhase(LearningPhase.training) { XCTAssertNotEqual(dropout(x), x) } XCTAssertEqual(dropout(x), x) } XCTAssertEqual(dropout(x), x) } func testAlphaDropout() { Context.local.learningPhase = .inference let dropout = AlphaDropout<Float>(probability: 0.5) let x = Tensor<Float>(repeating: 1.0, shape: [4, 4]) XCTAssertEqual(dropout(x), x) withLearningPhase(LearningPhase.inference) { XCTAssertEqual(dropout(x), x) withLearningPhase(LearningPhase.training) { XCTAssertNotEqual(dropout(x), x) } XCTAssertEqual(dropout(x), x) } XCTAssertEqual(dropout(x), x) } func testDilation2D() { let filter = Tensor(shape: [2, 2, 3], scalars: (0..<12).map(Float.init)) let layer = Dilation2D<Float>( filter: filter, strides: (2, 2), padding: .valid) let input = Tensor(shape: [2, 2, 2, 3], scalars: (0..<24).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>( shape: [2, 1, 1, 3], scalars: [18, 20, 22, 30, 32, 34]) XCTAssertEqual(output, expected) } func testDilation2DGradient() { let filter = Tensor(shape: [3, 2, 4], scalars: (0..<24).map(Float.init)) let layer = Dilation2D<Float>( filter: filter, strides: (1, 1), rates: (1, 1), padding: .valid) let input = Tensor(shape: [2, 4, 4, 4], scalars: (0..<128).map(Float.init)) let grads = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // filters = tf.reshape(tf.range(24, dtype=tf.float32), [3, 2, 4]) // image = tf.reshape(tf.range(128, dtype=tf.float32), [2, 4, 4, 4]) // with tf.GradientTape() as tape: // tape.watch([image, filters]) // y = tf.nn.dilation2d( // image, filters, [1, 1, 1, 1], "VALID", "NHWC", [1, 1, 1, 1], name=None) // print(tape.gradient(y, [image, filters])) // ``` XCTAssertEqual( grads.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, 0, 0, 0]], [[0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]], [[[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, 0, 0]], [[0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]] ] ) XCTAssertEqual( grads.1.filter, [ [[0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [12, 12, 12, 12]], ] ) } func testErosion2D() { let filter = Tensor(shape: [2, 2, 3], scalars: (0..<12).map(Float.init)) let layer = Erosion2D<Float>( filter: filter, strides: (2, 2), padding: .valid) let input = Tensor(shape: [2, 2, 2, 3], scalars: (0..<24).map(Float.init)) let output = layer.inferring(from: input) let expected = Tensor<Float>( shape: [2, 1, 1, 3], scalars: [-9, -9, -9, 3, 3, 3]) XCTAssertEqual(output, expected) } func testErosion2DGradient() { let filter = Tensor(shape: [3, 2, 4], scalars: (0..<24).map(Float.init)) let layer = Erosion2D<Float>( filter: filter, strides: (1, 1), rates: (1, 1), padding: .valid) let input = Tensor(shape: [2, 4, 4, 4], scalars: (0..<128).map(Float.init)) let grads = gradient(at: input, layer) { $1($0).sum() } // The expected value of the gradient was computed using the following Python code: // ``` // filters = tf.reshape(tf.range(24, dtype=tf.float32), [3, 2, 4]) // image = tf.reshape(tf.range(128, dtype=tf.float32), [2, 4, 4, 4]) // with tf.GradientTape() as tape: // tape.watch([image, filters]) // y = tf.nn.erosion2d( // image, filters, [1, 1, 1, 1], "VALID", "NHWC", [1, 1, 1, 1], name=None) // print(tape.gradient(y, [image, filters])) // ``` XCTAssertEqual( grads.0, [[[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [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, 0, 0], [0, 0, 0, 0]]], [[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [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, 0, 0], [0, 0, 0, 0]]]] ) XCTAssertEqual( grads.1.filter, [[[0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [-12, -12, -12, -12]], ] ) } static var allTests = [ ("testConv1D", testConv1D), ("testConv1DDilation", testConv1DDilation), ("testConv2D", testConv2D), ("testConv2DGradient", testConv2DGradient), ("testConv2DDilation", testConv2DDilation), ("testConv3D", testConv3D), ("testConv3DGradient", testConv3DGradient), ("testTransposedConv1D", testTransposedConv1D), ("testTransposedConv2D", testTransposedConv2D), ("testTransposedConv2DGradient", testTransposedConv2DGradient), ("testTransposedConv3D", testTransposedConv3D), ("testDepthwiseConv2D", testDepthwiseConv2D), ("testDepthwiseConv2DGradient", testDepthwiseConv2DGradient), ("testSeparableConv1D", testSeparableConv1D), ("testSeparableConv2D", testSeparableConv2D), ("testSeparableConv2DGradient", testSeparableConv2DGradient), ("testZeroPadding1D", testZeroPadding1D), ("testZeroPadding1DGradient", testZeroPadding1DGradient), ("testZeroPadding2D", testZeroPadding2D), ("testZeroPadding2DGradient", testZeroPadding2DGradient), ("testZeroPadding3D", testZeroPadding3D), ("testZeroPadding3DGradient", testZeroPadding3DGradient), ("testMaxPool1D", testMaxPool1D), ("testMaxPool1DGradient", testMaxPool1DGradient), ("testMaxPool2D", testMaxPool2D), ("testMaxPool2DGradient", testMaxPool2DGradient), ("testMaxPool3D", testMaxPool3D), ("testMaxPool3DGradient", testMaxPool3DGradient), ("testAvgPool1D", testAvgPool1D), ("testAvgPool1DGradient", testAvgPool1DGradient), ("testAvgPool2D", testAvgPool2D), ("testAvgPool2DGradient", testAvgPool2DGradient), ("testAvgPool3D", testAvgPool3D), ("testAvgPool3DGradient", testAvgPool3DGradient), ("testGlobalAvgPool1D", testGlobalAvgPool1D), ("testGlobalAvgPool1DGradient", testGlobalAvgPool1DGradient), ("testGlobalAvgPool2D", testGlobalAvgPool2D), ("testGlobalAvgPool2DGradient", testGlobalAvgPool2DGradient), ("testGlobalAvgPool3D", testGlobalAvgPool3D), ("testGlobalAvgPool3DGradient", testGlobalAvgPool3DGradient), ("testGlobalMaxPool1D", testGlobalMaxPool1D), ("testGlobalMaxPool1DGradient", testGlobalMaxPool1DGradient), ("testGlobalMaxPool2D", testGlobalMaxPool2D), ("testGlobalMaxPool2DGradient", testGlobalMaxPool2DGradient), ("testGlobalMaxPool3D", testGlobalMaxPool3D), ("testGlobalMaxPool3DGradient", testGlobalMaxPool3DGradient), ("testFractionalMaxPool2D", testFractionalMaxPool2D), ("testFractionalMaxPool2DGradient", testFractionalMaxPool2DGradient), ("testUpSampling1D", testUpSampling1D), ("testUpSampling1DGradient", testUpSampling1DGradient), ("testUpSampling2D", testUpSampling2D), ("testUpSampling2DGradient", testUpSampling2DGradient), ("testUpSampling3D", testUpSampling3D), ("testUpSampling3DGradient", testUpSampling3DGradient), ("testReshape", testReshape), ("testReshapeGradient", testReshapeGradient), ("testFlatten", testFlatten), ("testFlattenGradient", testFlattenGradient), ("testEmbedding", testEmbedding), ("testEmbeddingGradient", testEmbeddingGradient), ("testBasicRNNCell", testBasicRNNCell), ("testDense", testDense), ("testDenseGradient", testDenseGradient), ("testRNN", testRNN), ("testBidirectionalBasicRNNSumMerge", testBidirectionalBasicRNNSumMerge), ("testBidirectionalBasicRNNConcatenateMerge", testBidirectionalBasicRNNConcatenateMerge), ("testBidirectionalBasicRNNAverageMerge", testBidirectionalBasicRNNAverageMerge), ("testBidirectionalBasicRNNMultiplyMerge", testBidirectionalBasicRNNMultiplyMerge), ("testBidirectionalBasicRNNStackMerge", testBidirectionalBasicRNNStackMerge), ("testLSTM", testLSTM), ("testBidirectionalLSTMSumMerge", testBidirectionalLSTMSumMerge), ("testBidirectionalLSTMConcatenateMerge", testBidirectionalLSTMConcatenateMerge), ("testBidirectionalLSTMAverageMerge", testBidirectionalLSTMAverageMerge), ("testBidirectionalLSTMMultiplyMerge", testBidirectionalLSTMMultiplyMerge), ("testBidirectionalLSTMStackMerge", testBidirectionalLSTMStackMerge), ("testGRU", testGRU), ("testBidirectionalGRUSumMerge", testBidirectionalGRUSumMerge), ("testBidirectionalGRUConcatenateMerge", testBidirectionalGRUConcatenateMerge), ("testBidirectionalGRUAverageMerge", testBidirectionalGRUAverageMerge), ("testBidirectionalGRUMultiplyMerge", testBidirectionalGRUMultiplyMerge), ("testBidirectionalGRUStackMerge", testBidirectionalGRUStackMerge), ("testFunction", testFunction), ("testBatchNorm", testBatchNorm), ("testBatchNormInference", testBatchNormInference), ("testLayerNorm", testLayerNorm), ("testLayerNormInference", testLayerNormInference), ("testGroupNorm", testGroupNorm), ("testInstanceNorm", testInstanceNorm), ("testGaussianNoise", testGaussianNoise), ("testGaussianDropout", testGaussianDropout), ("testAlphaDropout", testAlphaDropout), ("testDilation2D", testDilation2D), ("testDilation2DGradient", testDilation2DGradient), ("testErosion2D", testErosion2D), ("testErosion2DGradient", testErosion2DGradient) ] }
41.543035
119
0.639273
dbb14a4ebae7956ad1dad57e3e724a2739a939c5
280
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "Switch", products: [ .library( name: "Switch", targets: ["Switch"]), ], dependencies: [ ], targets: [ .target( name: "Switch", dependencies: []), ] )
14.736842
27
0.553571
4699a329106199e61db9f668a756a352a2a3d1e5
405
// // GymWorkoutUITests.swift // GymWorkoutUITests // // Created by Daniela Ferreira da Cunha on 04/10/19. // Copyright © 2019 Adrian de Almeida. All rights reserved. // import XCTest class BaseTests: XCTestCase { let app = XCUIApplication() override func setUp() { continueAfterFailure = false app.launch() } override func tearDown() { app.terminate() } }
17.608696
60
0.649383
9c76ae929022758d7940db0ccd5c2e608afc596d
4,957
// // String.swift // MeetingBar // // Created by Jens Goldhammer on 29.12.20. // Copyright © 2020 Andrii Leitsius. All rights reserved. // import Foundation extension String { enum TruncationPosition { case head case middle case tail } /// Returns a truncated version of the string, limited to the specified length /// in characters, indicating the truncating with an optional truncation mark. /// - Parameters: /// - limit: Desired maximum length of the string. /// - position: The position where the truncation should be applied. /// - truncationMark: A string that will be placed at the truncation position. /// - Returns: The truncated string, if applicable. func truncated(to limit: Int, at position: TruncationPosition = .tail, truncationMark: String = "…") -> String { guard self.count > limit else { return self } switch position { case .head: return truncationMark + self.suffix(limit) case .middle: let headCharactersCount = Int(ceil(Float(limit - truncationMark.count) / 2.0)) let tailCharactersCount = Int(floor(Float(limit - truncationMark.count) / 2.0)) return "\(self.prefix(headCharactersCount))\(truncationMark)\(self.suffix(tailCharactersCount))" case .tail: return self.prefix(limit) + truncationMark } } /// Returns a version of the first occurence of `target` is replaced by `replacement`. /// - Parameters: /// - target: The string to search for. /// - replacement: The replacement string. /// - Returns: The string with the replacement, if any. func replacingFirstOccurrence(of target: String, with replacement: String) -> String { if let range = self.range(of: target) { return self.replacingCharacters(in: range, with: replacement) } return self } /// A Boolean value indicating whether the string contains HTML tags. var containsHTML: Bool { let htmlRange = self.range(of: #"</?[A-z][ \t\S]*>"#, options: .regularExpression) return htmlRange != nil } /// Returns a version of the string with all HTML tags removed, if any. /// - Returns: The string without HTML tags. func htmlTagsStripped() -> String { if self.containsHTML, let data = self.data(using: .utf16), let attributedSelf = NSAttributedString( html: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil ) { return attributedSelf.string } return self } func encodeUrl() -> String? { self.addingPercentEncoding( withAllowedCharacters: NSCharacterSet.urlQueryAllowed) } func decodeUrl() -> String? { self.removingPercentEncoding } func loco() -> String { I18N.instance.localizedString(for: self) } func loco(_ arg: CVarArg) -> String { I18N.instance.localizedString(for: self, arg) } func loco(_ firstArg: CVarArg, _ secondArg: CVarArg) -> String { I18N.instance.localizedString(for: self, firstArg, secondArg) } func loco(_ firstArg: CVarArg, _ secondArg: CVarArg, _ thirdArg: CVarArg) -> String { I18N.instance.localizedString(for: self, firstArg, secondArg, thirdArg) } } extension String { func splitWithNewLineString(with attributes: [NSAttributedString.Key: Any], maxWidth: CGFloat) -> String { let words = self.split(separator: " ").map { String($0) } var lineWidth: CGFloat = 0.0 var thisLine = "" var lines: [String] = [] func width(for string: String) -> CGFloat { string.boundingRect(with: NSSize.zero, options: [ .usesLineFragmentOrigin, .usesFontLeading], attributes: attributes).width } func addToAllLines(_ text: String) { lines.append(text) thisLine = "" lineWidth = 0.0 } for (idx, word) in words.enumerated() { thisLine = thisLine.appending("\(word) ") lineWidth = width(for: thisLine) let isLastWord = idx + 1 >= words.count if isLastWord { addToAllLines(thisLine) } else { let nextWord = words[idx + 1] if lineWidth + width(for: nextWord) >= maxWidth { addToAllLines(thisLine) } } } return lines.joined(separator: "\n") } func splitWithNewLineAttributedString(with attributes: [NSAttributedString.Key: Any], maxWidth: CGFloat) -> NSAttributedString { let output = self.splitWithNewLineString(with: attributes, maxWidth: maxWidth) let attributedString = NSAttributedString(string: output, attributes: attributes) return attributedString } }
34.186207
135
0.615695
1e333a5b802b8fd7084d370947f0f7054b48bb8a
1,056
// Copyright © 2021 SpotHero, Inc. All rights reserved. import Foundation public enum UBNetworkError: Error { case invalidContentType(String) case invalidURLString(String) case invalidURLResponse case unableToDecode(String, DecodingError?) case unexpectedError } extension UBNetworkError: LocalizedError { public var errorDescription: String? { switch self { case let .invalidContentType(contentType): return "Invalid content type '\(contentType)'." case let .invalidURLString(urlString): return "Invalid URL string '\(urlString)'." case .invalidURLResponse: return "Invalid URL Response." case let .unableToDecode(objectName, .some(underlyingError)): return "Unable to decode '\(objectName)'. \(underlyingError.cleanedDescription)" case let .unableToDecode(objectName, _): return "Unable to decode '\(objectName)'." case .unexpectedError: return "An unexpected error has occurred." } } }
34.064516
92
0.666667
9b95715eaaca5438809638030383919c3d0e06c9
2,295
/* MIT License Copyright (c) 2017-2019 MessageKit Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import UIKit open class MediaMessageSizeCalculator: MessageSizeCalculator { open override func messageContainerSize(for message: MessageType) -> CGSize { let maxWidth = messageContainerMaxWidth(for: message) let sizeForMediaItem = { (maxWidth: CGFloat, size: CGSize) -> CGSize in if maxWidth < size.width { // Maintain the ratio if width is too great let height = maxWidth * size.height / size.width return CGSize(width: maxWidth, height: height) } return size } switch message.kind { case .photo(let item): return sizeForMediaItem(maxWidth, item.size) case .video(let item): return sizeForMediaItem(maxWidth, item.size) case .wallet(let item): return sizeForMediaItem(maxWidth, item.size) case .gift(let item): return sizeForMediaItem(maxWidth, item.size) case .auth(let item): return sizeForMediaItem(maxWidth, item.size) default: fatalError("messageContainerSize received unhandled MessageDataType: \(message.kind)") } } }
40.982143
98
0.700654
f4faea90f4d852bd284f9379eab13347444179b3
1,666
import XCTest import Mockingbird @testable import CarthageExample class PersonTests: XCTestCase { var bird: BirdMock! // Build the test target (⇧⌘U) to generate this mock override func setUp() { bird = mock(Bird.self) } // MARK: - Flying func testReleaseBird() { given(bird.canFly).willReturn(true) // Given a bird that can fly Person().release(bird) // When a person releases the bird verify(bird.fly()).wasCalled() // Then the bird flies away } func testReleaseNonFlyingBird() { given(bird.canFly).willReturn(false) // Given a bird that _cannot_ fly Person().release(bird) // When a person releases the bird verify(bird.fly()).wasNeverCalled() // Then the bird doesn't fly } // MARK: - Eating func testFeedBird() { given(bird.canEat(any())).willReturn(true) // Given a bird that eats anything Person().feed(bird: bird, fruit: Apple()) // When feeding the bird an apple Person().feed(bird: bird, fruit: Watermelon()) // and a watermelon verify(bird.eat(any())).wasCalled(twice) // Then the bird eats twice } func testFeedPickyBird() { given(bird.canEat(any(where: { // Given a bird that only eats small fruits $0.size < 42 }))).willReturn(true) bird.useDefaultValues(from: .standardProvider) // (return `false` by default) Person().feed(bird: bird, fruit: Apple()) // When feeding the bird an apple Person().feed(bird: bird, fruit: Watermelon()) // and a watermelon verify(bird.eat(any())).wasCalled(once) // Then the bird only eats once } }
36.217391
95
0.629652
fe089dd9f3642456747855992d8238211bb5460e
3,349
import Foundation import XCTest import Nimble private protocol TestProtocol {} private class TestClassConformingToProtocol: TestProtocol {} private struct TestStructConformingToProtocol: TestProtocol {} final class BeAnInstanceOfTest: XCTestCase, XCTestCaseProvider { static var allTests: [(String, (BeAnInstanceOfTest) -> () throws -> Void)] { return [ ("testPositiveMatch", testPositiveMatch), ("testPositiveMatchSwiftTypes", testPositiveMatchSwiftTypes), ("testFailureMessages", testFailureMessages), ("testFailureMessagesSwiftTypes", testFailureMessagesSwiftTypes), ] } func testPositiveMatch() { expect(NSNull()).to(beAnInstanceOf(NSNull.self)) expect(NSNumber(value:1)).toNot(beAnInstanceOf(NSDate.self)) } enum TestEnum { case one, two } func testPositiveMatchSwiftTypes() { expect(1).to(beAnInstanceOf(Int.self)) expect("test").to(beAnInstanceOf(String.self)) expect(TestEnum.one).to(beAnInstanceOf(TestEnum.self)) let testProtocolClass = TestClassConformingToProtocol() expect(testProtocolClass).to(beAnInstanceOf(TestClassConformingToProtocol.self)) expect(testProtocolClass).toNot(beAnInstanceOf(TestProtocol.self)) expect(testProtocolClass).toNot(beAnInstanceOf(TestStructConformingToProtocol.self)) let testProtocolStruct = TestStructConformingToProtocol() expect(testProtocolStruct).to(beAnInstanceOf(TestStructConformingToProtocol.self)) expect(testProtocolStruct).toNot(beAnInstanceOf(TestProtocol.self)) expect(testProtocolStruct).toNot(beAnInstanceOf(TestClassConformingToProtocol.self)) } func testFailureMessages() { failsWithErrorMessageForNil("expected to not be an instance of NSNull, got <nil>") { expect(nil as NSNull?).toNot(beAnInstanceOf(NSNull.self)) } failsWithErrorMessageForNil("expected to be an instance of NSString, got <nil>") { expect(nil as NSString?).to(beAnInstanceOf(NSString.self)) } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) let numberTypeName = "__NSCFNumber" #else let numberTypeName = "NSNumber" #endif failsWithErrorMessage("expected to be an instance of NSString, got <\(numberTypeName) instance>") { expect(NSNumber(value:1)).to(beAnInstanceOf(NSString.self)) } failsWithErrorMessage("expected to not be an instance of \(numberTypeName), got <\(numberTypeName) instance>") { expect(NSNumber(value:1)).toNot(beAnInstanceOf(type(of: NSNumber(value:1)))) } } func testFailureMessagesSwiftTypes() { failsWithErrorMessage("expected to not be an instance of Int, got <Int instance>") { expect(1).toNot(beAnInstanceOf(Int.self)) } let testClass = TestClassConformingToProtocol() failsWithErrorMessage("expected to be an instance of \(String(describing: TestProtocol.self)), got <\(String(describing: TestClassConformingToProtocol.self)) instance>") { expect(testClass).to(beAnInstanceOf(TestProtocol.self)) } failsWithErrorMessage("expected to be an instance of String, got <Int instance>") { expect(1).to(beAnInstanceOf(String.self)) } } }
41.8625
179
0.693938
fc4407fc429a430e3005ea32a4a2b0845624c9e1
3,158
// // UIFontExtension.swift // MemoryChainKit // // Created by Zhao Meiru on 2020/4/9. // Copyright © 2020 Marc Steven(https://github.com/MarcSteven). All rights reserved. // import UIKit extension UIFont { public enum Trait { case normal case italic case monospace } public static func systemFont(size: CGFloat, weight: Weight = .regular, trait: Trait = .normal) -> UIFont { switch trait { case .normal: return systemFont(ofSize: size, weight: weight) case .italic: return italicSystemFont(ofSize: size) case .monospace: return monospacedDigitSystemFont(ofSize: size, weight: weight) } } } extension UIFont { func apply(_ trait: Trait) -> UIFont { trait == .monospace ? monospacedDigitFont : self } /// Returns a font matching the given font descriptor. /// /// - Parameter traits: The new symbolic traits. /// - Returns: The new font matching the given font descriptor. public func traits(_ traits: UIFontDescriptor.SymbolicTraits...) -> UIFont? { guard let descriptor = fontDescriptor.withSymbolicTraits(UIFontDescriptor.SymbolicTraits(traits)) else { return nil } return UIFont(descriptor: descriptor, size: 0) } public func bold() -> UIFont? { traits(.traitBold) } public func italic() -> UIFont? { traits(.traitItalic) } public func monospace() -> UIFont? { traits(.traitMonoSpace) } } extension UIFont { public var monospacedDigitFont: UIFont { let featureSettings = [[ UIFontDescriptor.FeatureKey.featureIdentifier: kNumberSpacingType, UIFontDescriptor.FeatureKey.typeIdentifier: kMonospacedNumbersSelector ]] let attributes = [UIFontDescriptor.AttributeName.featureSettings: featureSettings] let oldDescriptor = fontDescriptor let newDescriptor = oldDescriptor.addingAttributes(attributes) return UIFont(descriptor: newDescriptor, size: 0) } } extension UIFont { public static func printAvailableFontNames() { for family in familyNames { let count = fontNames(forFamilyName: family).count print("▿ \(family) (\(count) \(count == 1 ? "font" : "fonts"))") for name in fontNames(forFamilyName: family) { print(" - \(name)") } } } } extension UIFont.TextStyle: CaseIterable { public static var allCases: [UIFont.TextStyle] = { [ .largeTitle, .title1, .title2, .title3, .headline, .subheadline, .body, .callout, .footnote, .caption1, .caption2 ] }() private static var headerStyles: [UIFont.TextStyle] = { [ .largeTitle, .title1, .title2, .title3, .headline ] }() public var isTitle: Bool { UIFont.TextStyle.headerStyles.contains(self) } }
25.885246
112
0.582014
1e7f7c1c734d3b52e776c1e7de987c1e2586f16b
9,017
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import UIKit protocol AttachmentCaptionToolbarDelegate: class { func attachmentCaptionToolbarDidEdit(_ attachmentCaptionToolbar: AttachmentCaptionToolbar) func attachmentCaptionToolbarDidComplete() } // MARK: - class AttachmentCaptionToolbar: UIView, UITextViewDelegate { private let kMaxCaptionCharacterCount = 240 weak var attachmentCaptionToolbarDelegate: AttachmentCaptionToolbarDelegate? var messageText: String? { get { return textView.text } set { textView.text = newValue } } // Layout Constants let kMinTextViewHeight: CGFloat = 38 var maxTextViewHeight: CGFloat { // About ~4 lines in portrait and ~3 lines in landscape. // Otherwise we risk obscuring too much of the content. return UIDevice.current.orientation.isPortrait ? 160 : 100 } var textViewHeightConstraint: NSLayoutConstraint! var textViewHeight: CGFloat // MARK: - Initializers init() { self.textViewHeight = kMinTextViewHeight super.init(frame: CGRect.zero) // Specifying autorsizing mask and an intrinsic content size allows proper // sizing when used as an input accessory view. self.autoresizingMask = .flexibleHeight self.translatesAutoresizingMaskIntoConstraints = false self.backgroundColor = UIColor.clear textView.delegate = self // Layout let kToolbarMargin: CGFloat = 8 self.textViewHeightConstraint = textView.autoSetDimension(.height, toSize: kMinTextViewHeight) lengthLimitLabel.setContentHuggingHigh() lengthLimitLabel.setCompressionResistanceHigh() let contentView = UIStackView(arrangedSubviews: [textContainer, lengthLimitLabel]) // We have to wrap the toolbar items in a content view because iOS (at least on iOS10.3) assigns the inputAccessoryView.layoutMargins // when resigning first responder (verified by auditing with `layoutMarginsDidChange`). // The effect of this is that if we were to assign these margins to self.layoutMargins, they'd be blown away if the // user dismisses the keyboard, giving the input accessory view a wonky layout. contentView.layoutMargins = UIEdgeInsets(top: kToolbarMargin, left: kToolbarMargin, bottom: kToolbarMargin, right: kToolbarMargin) contentView.axis = .vertical addSubview(contentView) contentView.autoPinEdgesToSuperviewEdges() } required init?(coder aDecoder: NSCoder) { notImplemented() } // MARK: - UIView Overrides override var intrinsicContentSize: CGSize { get { // Since we have `self.autoresizingMask = UIViewAutoresizingFlexibleHeight`, we must specify // an intrinsicContentSize. Specifying CGSize.zero causes the height to be determined by autolayout. return CGSize.zero } } // MARK: - Subviews private lazy var lengthLimitLabel: UILabel = { let lengthLimitLabel = UILabel() // Length Limit Label shown when the user inputs too long of a message lengthLimitLabel.textColor = .white lengthLimitLabel.text = NSLocalizedString("ATTACHMENT_APPROVAL_MESSAGE_LENGTH_LIMIT_REACHED", comment: "One-line label indicating the user can add no more text to the media message field.") lengthLimitLabel.textAlignment = .center // Add shadow in case overlayed on white content lengthLimitLabel.layer.shadowColor = UIColor.black.cgColor lengthLimitLabel.layer.shadowOffset = .zero lengthLimitLabel.layer.shadowOpacity = 0.8 lengthLimitLabel.layer.shadowRadius = 2.0 lengthLimitLabel.isHidden = true return lengthLimitLabel }() lazy var textView: UITextView = { let textView = buildTextView() textView.returnKeyType = .done textView.scrollIndicatorInsets = UIEdgeInsets(top: 5, left: 0, bottom: 5, right: 3) return textView }() private lazy var textContainer: UIView = { let textContainer = UIView() textContainer.clipsToBounds = true textContainer.addSubview(textView) textView.autoPinEdgesToSuperviewEdges() return textContainer }() private func buildTextView() -> UITextView { let textView = AttachmentTextView() textView.keyboardAppearance = Theme.darkThemeKeyboardAppearance textView.backgroundColor = .clear textView.tintColor = Theme.darkThemePrimaryColor textView.font = UIFont.ows_dynamicTypeBody textView.textColor = Theme.darkThemePrimaryColor textView.textContainerInset = UIEdgeInsets(top: 7, left: 7, bottom: 7, right: 7) return textView } // MARK: - UITextViewDelegate public func textViewDidChange(_ textView: UITextView) { updateHeight(textView: textView) attachmentCaptionToolbarDelegate?.attachmentCaptionToolbarDidEdit(self) } public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if !FeatureFlags.sendingMediaWithOversizeText { let existingText: String = textView.text ?? "" let proposedText: String = (existingText as NSString).replacingCharacters(in: range, with: text) // Don't complicate things by mixing media attachments with oversize text attachments guard proposedText.utf8.count < kOversizeTextMessageSizeThreshold else { Logger.debug("long text was truncated") self.lengthLimitLabel.isHidden = false // `range` represents the section of the existing text we will replace. We can re-use that space. // Range is in units of NSStrings's standard UTF-16 characters. Since some of those chars could be // represented as single bytes in utf-8, while others may be 8 or more, the only way to be sure is // to just measure the utf8 encoded bytes of the replaced substring. let bytesAfterDelete: Int = (existingText as NSString).replacingCharacters(in: range, with: "").utf8.count // Accept as much of the input as we can let byteBudget: Int = Int(kOversizeTextMessageSizeThreshold) - bytesAfterDelete if byteBudget >= 0, let acceptableNewText = text.truncated(toByteCount: UInt(byteBudget)) { textView.text = (existingText as NSString).replacingCharacters(in: range, with: acceptableNewText) } return false } self.lengthLimitLabel.isHidden = true // After verifying the byte-length is sufficiently small, verify the character count is within bounds. guard proposedText.count < kMaxCaptionCharacterCount else { Logger.debug("hit attachment message body character count limit") self.lengthLimitLabel.isHidden = false // `range` represents the section of the existing text we will replace. We can re-use that space. let charsAfterDelete: Int = (existingText as NSString).replacingCharacters(in: range, with: "").count // Accept as much of the input as we can let charBudget: Int = Int(kMaxCaptionCharacterCount) - charsAfterDelete if charBudget >= 0 { let acceptableNewText = String(text.prefix(charBudget)) textView.text = (existingText as NSString).replacingCharacters(in: range, with: acceptableNewText) } return false } } // Though we can wrap the text, we don't want to encourage multline captions, plus a "done" button // allows the user to get the keyboard out of the way while in the attachment approval view. if text == "\n" { attachmentCaptionToolbarDelegate?.attachmentCaptionToolbarDidComplete() return false } else { return true } } // MARK: - Helpers private func updateHeight(textView: UITextView) { // compute new height assuming width is unchanged let currentSize = textView.frame.size let newHeight = clampedTextViewHeight(fixedWidth: currentSize.width) if newHeight != textViewHeight { Logger.debug("TextView height changed: \(textViewHeight) -> \(newHeight)") textViewHeight = newHeight textViewHeightConstraint?.constant = textViewHeight invalidateIntrinsicContentSize() } } private func clampedTextViewHeight(fixedWidth: CGFloat) -> CGFloat { let contentSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude)) return CGFloatClamp(contentSize.height, kMinTextViewHeight, maxTextViewHeight) } }
40.254464
197
0.675945
46c687649993ed10aad2350e121b4c8e434d509f
4,747
// // PresenceSubsystemCap.swift // // Generated on 20/09/18 /* * Copyright 2019 Arcus Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import RxSwift import PromiseKit // MARK: Constants extension Constants { public static var presenceSubsystemNamespace: String = "subspres" public static var presenceSubsystemName: String = "PresenceSubsystem" } // MARK: Attributes fileprivate struct Attributes { static let presenceSubsystemOccupied: String = "subspres:occupied" static let presenceSubsystemOccupiedConf: String = "subspres:occupiedConf" static let presenceSubsystemPeopleAtHome: String = "subspres:peopleAtHome" static let presenceSubsystemPeopleAway: String = "subspres:peopleAway" static let presenceSubsystemDevicesAtHome: String = "subspres:devicesAtHome" static let presenceSubsystemDevicesAway: String = "subspres:devicesAway" static let presenceSubsystemAllDevices: String = "subspres:allDevices" } public protocol ArcusPresenceSubsystemCapability: class, RxArcusService { /** Estimate as to whether the home is occupied */ func getPresenceSubsystemOccupied(_ model: SubsystemModel) -> Bool? /** Confidence in occupied estimate */ func getPresenceSubsystemOccupiedConf(_ model: SubsystemModel) -> Any? /** Set of the addresses of people who are in this place */ func getPresenceSubsystemPeopleAtHome(_ model: SubsystemModel) -> [String]? /** Set of address of people that are away from this place */ func getPresenceSubsystemPeopleAway(_ model: SubsystemModel) -> [String]? /** Set of addresses of presence capable devices not associated with people in this place */ func getPresenceSubsystemDevicesAtHome(_ model: SubsystemModel) -> [String]? /** Set of addresses of presence capable devices not associated with people that are away from this place */ func getPresenceSubsystemDevicesAway(_ model: SubsystemModel) -> [String]? /** Set of addresses of all presence capable devices */ func getPresenceSubsystemAllDevices(_ model: SubsystemModel) -> [String]? /** Presence analysis describes, for each person, whether the subsystem thinks the person is at home or not and how it came to that conclusion. */ func requestPresenceSubsystemGetPresenceAnalysis(_ model: SubsystemModel) throws -> Observable<ArcusSessionEvent> } extension ArcusPresenceSubsystemCapability { public func getPresenceSubsystemOccupied(_ model: SubsystemModel) -> Bool? { let attributes: [String: AnyObject] = model.get() return attributes[Attributes.presenceSubsystemOccupied] as? Bool } public func getPresenceSubsystemOccupiedConf(_ model: SubsystemModel) -> Any? { let attributes: [String: AnyObject] = model.get() return attributes[Attributes.presenceSubsystemOccupiedConf] as? Any } public func getPresenceSubsystemPeopleAtHome(_ model: SubsystemModel) -> [String]? { let attributes: [String: AnyObject] = model.get() return attributes[Attributes.presenceSubsystemPeopleAtHome] as? [String] } public func getPresenceSubsystemPeopleAway(_ model: SubsystemModel) -> [String]? { let attributes: [String: AnyObject] = model.get() return attributes[Attributes.presenceSubsystemPeopleAway] as? [String] } public func getPresenceSubsystemDevicesAtHome(_ model: SubsystemModel) -> [String]? { let attributes: [String: AnyObject] = model.get() return attributes[Attributes.presenceSubsystemDevicesAtHome] as? [String] } public func getPresenceSubsystemDevicesAway(_ model: SubsystemModel) -> [String]? { let attributes: [String: AnyObject] = model.get() return attributes[Attributes.presenceSubsystemDevicesAway] as? [String] } public func getPresenceSubsystemAllDevices(_ model: SubsystemModel) -> [String]? { let attributes: [String: AnyObject] = model.get() return attributes[Attributes.presenceSubsystemAllDevices] as? [String] } public func requestPresenceSubsystemGetPresenceAnalysis(_ model: SubsystemModel) throws -> Observable<ArcusSessionEvent> { let request: PresenceSubsystemGetPresenceAnalysisRequest = PresenceSubsystemGetPresenceAnalysisRequest() request.source = model.address return try sendRequest(request) } }
42.765766
148
0.764904
1d48d244210caaa5d3ebd1bf63028567b449d4cb
350
// // ColorExtension.swift // ArcBlockTimeline // // Created by lee on 2021/7/5. // Copyright © 2021 com.arc.block. All rights reserved. // import UIColor_Hex_Swift extension UIColor { class var cF4F6F9: UIColor { return UIColor("#F4F6F9") } class var c46A3FF: UIColor { return UIColor("#46A3FF") } }
15.909091
56
0.62
38b49c3aea0fae2df3faf442903f6b319e058441
5,721
// // CoreDataStack.swift // // // Created by Fernando Rodríguez Romero on 21/02/16. // Copyright © 2016 udacity.com. All rights reserved. // import CoreData struct CoreDataStack { // MARK: - Properties private let model : NSManagedObjectModel private let coordinator : NSPersistentStoreCoordinator private let modelURL : NSURL private let dbURL : NSURL private let persistingContext : NSManagedObjectContext private let backgroundContext : NSManagedObjectContext let context : NSManagedObjectContext // MARK: - Initializers init?(modelName: String){ // Assumes the model is in the main bundle guard let modelURL = NSBundle.mainBundle().URLForResource(modelName, withExtension: "momd") else { print("Unable to find \(modelName)in the main bundle") return nil} self.modelURL = modelURL // Try to create the model from the URL guard let model = NSManagedObjectModel(contentsOfURL: modelURL) else { print("unable to create a model from \(modelURL)") return nil } self.model = model // Create the store coordinator coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) // Create a persistingContext (private queue) and a child one (main queue) // create a context and add connect it to the coordinator persistingContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) persistingContext.persistentStoreCoordinator = coordinator context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) context.parentContext = persistingContext // Create a background context child of main context backgroundContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) backgroundContext.parentContext = context // Add a SQLite store located in the documents folder let fm = NSFileManager.defaultManager() guard let docUrl = fm.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first else{ print("Unable to reach the documents folder") return nil } self.dbURL = docUrl.URLByAppendingPathComponent("model.sqlite") let options = [NSInferMappingModelAutomaticallyOption: true, NSMigratePersistentStoresAutomaticallyOption: true] do{ try addStoreCoordinator(NSSQLiteStoreType, configuration: nil, storeURL: dbURL, options: options) }catch{ print("unable to add store at \(dbURL)") } } // MARK: - Utils func addStoreCoordinator(storeType: String, configuration: String?, storeURL: NSURL, options : [NSObject : AnyObject]?) throws{ try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: dbURL, options: nil) } } // MARK: - Removing data //extension CoreDataStack { // func dropAllData() throws{ // // delete all the objects in the db. This won't delete the files, it will // // just leave empty tables. // try coordinator.destroyPersistentStoreAtURL(dbURL, withType:NSSQLiteStoreType , options: nil) // // try addStoreCoordinator(NSSQLiteStoreType, configuration: nil, storeURL: dbURL, options: nil) // } //} // MARK: - Batch processing in the background //extension CoreDataStack{ // typealias Batch=(workerContext: NSManagedObjectContext) -> () // // func performBackgroundBatchOperation(batch: Batch){ // backgroundContext.performBlock(){ // batch(workerContext: self.backgroundContext) // // // Save it to the parent context, so normal saving // // can work // do{ // try self.backgroundContext.save() // }catch{ // fatalError("Error while saving backgroundContext: \(error)") // } // } // } //} // MARK: - Save extension CoreDataStack { func save() { // We call this synchronously, but it's a very fast // operation (it doesn't hit the disk). We need to know // when it ends so we can call the next save (on the persisting // context). This last one might take some time and is done // in a background queue context.performBlockAndWait(){ if self.context.hasChanges{ do{ try self.context.save() }catch{ fatalError("Error while saving main context: \(error)") } // now we save in the background self.persistingContext.performBlock(){ do{ try self.persistingContext.save() }catch{ fatalError("Error while saving persisting context: \(error)") } } } } } // func autoSave(delayInSeconds : Int){ // if delayInSeconds > 0 { // print("Autosaving") // save() // // let delayInNanoSeconds = UInt64(delayInSeconds) * NSEC_PER_SEC // let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInNanoSeconds)) // // dispatch_after(time, dispatch_get_main_queue(), { // self.autoSave(delayInSeconds) // }) // } // } }
32.505682
115
0.591855
4ab4cef01a439f43f0b258d9f263c5fd92b887a4
2,081
// // CalendarService.swift // OutreachApp // // Created by Demicheli, Stefano on 9/3/2563 BE. // Copyright © 2563 NECSI. All rights reserved. // import EventKit protocol CalendarService { func addEventToCalendarWith(title: String, description: String?, startDate: Date, endDate: Date, location: String?, completion: @escaping ((Result<Bool, Error>) -> Void)) } final class CalendarServiceImpl: CalendarService { func addEventToCalendarWith(title: String, description: String?, startDate: Date, endDate: Date, location: String?, completion: @escaping ((Result<Bool, Error>) -> Void)) { let eventStore = EKEventStore() eventStore.requestAccess(to: .event) { (granted, error) in if let error = error { completion(Result.failure(error)) return } if granted { let alarm = EKAlarm(relativeOffset: -3600.0) let event = EKEvent(eventStore: eventStore) event.title = title event.startDate = startDate event.endDate = endDate event.notes = description event.alarms = [alarm] event.location = location event.calendar = eventStore.defaultCalendarForNewEvents do { try eventStore.save(event, span: .thisEvent) } catch let error { completion(Result.failure(error)) return } completion(Result.success(true)) } else { completion(Result.failure(CalendarError.failedToAddEvent)) } } } } fileprivate enum CalendarError: Error { case failedToAddEvent }
33.031746
88
0.49063
f77ad5b0e76b8ba880a184fa8a67a655a1b74b86
2,889
// // Updateable.swift // Cryptor // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// /// A protocol for calculations that can be updated with incremental data buffers. /// public protocol Updatable { /// Status of the calculation. var status: Status { get } /// /// Low-level update routine. /// Updates the calculation with the contents of a data buffer. /// /// - Parameters: /// - buffer: Pointer to the data buffer /// - byteCount: Length of the buffer in bytes /// /// - Returns: `Self` if no error for optional chaining, nil otherwise /// func update(from buffer: UnsafeRawPointer, byteCount: size_t) -> Self? } /// /// Factors out common update code from Digest, HMAC and Cryptor. /// extension Updatable { /// /// Updates the current calculation with data contained in an `NSData` object. /// /// - Parameters data: The `NSData` object /// /// - Returns: Optional `Self` or nil /// public func update(data: NSData) -> Self? { _ = update(from: data.bytes, byteCount: size_t(data.length)) return self.status == .success ? self : nil } /// /// Updates the current calculation with data contained in an `Data` object. /// /// - Parameters data: The `Data` object /// /// - Returns: Optional `Self` or nil /// public func update(data: Data) -> Self? { _ = data.withUnsafeBytes() { (buffer: UnsafePointer<UInt8>) in _ = update(from: buffer, byteCount: size_t(data.count)) } return self.status == .success ? self : nil } /// /// Updates the current calculation with data contained in a byte array. /// /// - Parameters byteArray: The byte array /// /// - Returns: Optional `Self` or nil /// public func update(byteArray: [UInt8]) -> Self? { _ = update(from: byteArray, byteCount: size_t(byteArray.count)) return self.status == .success ? self : nil } /// /// Updates the current calculation with data contained in a String. /// The corresponding data will be generated using UTF8 encoding. /// /// - Parameters string: The string of data /// /// - Returns: Optional `Self` or nil /// public func update(string: String) -> Self? { _ = update(from: string, byteCount: size_t(string.utf8.count)) return self.status == .success ? self : nil } }
28.60396
82
0.646244
d989c4147c889ba5f6dd91468ca5bb44fc729562
512
// // ViewController.swift // AmadaCocoa // // Created by hprietoamada on 03/11/2020. // Copyright (c) 2020 hprietoamada. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20.48
80
0.675781
e48270b9d977b0aebb1410cdbb7f08f7a54d4ab2
2,559
// // ZHNloadingProgressView.swift // zhnbilibili // // Created by zhn on 16/12/11. // Copyright © 2016年 zhn. All rights reserved. // import UIKit class ZHNloadingProgressView: UIView { var progress: Int = 0{ didSet{ progressLabel.text = "\(progress)%" } } // MARK: - 懒加载控件 fileprivate lazy var rotaingImageView: UIImageView = { let rotaingImageView = UIImageView() rotaingImageView.image = #imageLiteral(resourceName: "play_loading") return rotaingImageView }() fileprivate lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.text = "正在缓冲:" titleLabel.font = UIFont.systemFont(ofSize: 12) titleLabel.textColor = UIColor.white return titleLabel }() fileprivate lazy var progressLabel: UILabel = { let progressLabel = UILabel() progressLabel.text = "0%" progressLabel.textColor = UIColor.white progressLabel.font = UIFont.systemFont(ofSize: 12) return progressLabel }() // MARK: - life cycle override init(frame: CGRect) { super.init(frame: frame) self.addSubview(rotaingImageView) self.addSubview(titleLabel) self.addSubview(progressLabel) self.backgroundColor = UIColor.ysColor(red: 0, green: 0, blue: 0, alpha: 0.7) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() rotaingImageView.snp.makeConstraints { (make) in make.centerY.equalTo(self) make.left.equalTo(self).offset(10) make.size.equalTo(CGSize(width: 15, height: 15)) } titleLabel.snp.makeConstraints { (make) in make.centerY.equalTo(self) make.left.equalTo(rotaingImageView.snp.right).offset(10) } progressLabel.snp.makeConstraints { (make) in make.centerY.equalTo(self) make.left.equalTo(titleLabel.snp.right).offset(5) } } } extension ZHNloadingProgressView { func startRotaing() { let rotaAnimation = CABasicAnimation(keyPath: "transform.rotation") rotaAnimation.toValue = M_PI * 8 rotaAnimation.repeatCount = MAXFLOAT rotaAnimation.duration = 3 rotaingImageView.layer.add(rotaAnimation, forKey: "rotaanimation") } func endRotaing() { rotaingImageView.layer.removeAllAnimations() } }
29.413793
85
0.626417
1453245142572df5f394635d89d35a30d52e721a
654
// // PKMMove+Utils.swift // Pokedex // // Created by Marlon David Ruiz Arroyave on 7/03/21. // import Foundation import PokemonAPI extension PKMMove { static func moveMock() -> PKMMove? { guard let path = Bundle.main.path(forResource: "stompMove", ofType: "json") else { return nil } guard let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) else { print("failed data") return nil } guard let move: PKMMove = try? PKMMove.decoder.decode(PKMMove.self, from: jsonData) else { print("failed decoder") return nil } return move } }
22.551724
103
0.602446
d75087bf5b05ba9072019c19f103aab2ad169a26
2,765
// // User.swift // YSTinder // // Created by jozen on 2019/1/9. // Copyright © 2019 liurenrui. All rights reserved. // import UIKit struct YSUser: ProducesCardViewModel { // properties var name: String? var uid: String? var age: Int? var profession: String? var imageUrls: [String]? var city: String? var caption: String? var minSeekingAge: Int? var maxSeekingAge: Int? //将一个User中需要展示到View的内容都转成一个ViewModel func toCardViewModel() -> YSCardViewModel{ let attributedText = NSMutableAttributedString(string: name ?? "", attributes: [.font:UIFont.systemFont(ofSize: 32, weight: .heavy)]) attributedText.append(NSAttributedString(string: " \(age ?? 18)", attributes: [.font:UIFont.systemFont(ofSize: 24, weight: .regular)])) attributedText.append(NSAttributedString(string: "\n\(profession ?? "")", attributes: [.font:UIFont.systemFont(ofSize: 20, weight: .regular)])) attributedText.append(NSAttributedString(string: "\n\(city ?? "")", attributes: [.font:UIFont.systemFont(ofSize: 20, weight: .regular)])) let captionAttributedStr = NSMutableAttributedString(string: name ?? "", attributes: [.font:UIFont.systemFont(ofSize: 32, weight: .heavy)]) captionAttributedStr.append(NSAttributedString(string: " \(age ?? 18)", attributes: [.font:UIFont.systemFont(ofSize: 24, weight: .regular)])) captionAttributedStr.append(NSAttributedString(string: "\n\(caption ?? "")", attributes: [.font: UIFont.systemFont(ofSize: 20, weight: .regular)])) return YSCardViewModel(uid: self.uid ?? "", imageUrls: imageUrls ?? [], attributedString: attributedText, textAlignment: .left, captionStr: captionAttributedStr) } init(dictionary: [String:Any]) { self.name = dictionary["name"] as? String self.age = dictionary["age"] as? Int self.profession = dictionary["profession"] as? String self.imageUrls = dictionary["imageUrls"] as? [String] self.city = dictionary["city"] as? String self.caption = dictionary["caption"] as? String self.uid = dictionary["uid"] as? String self.minSeekingAge = dictionary["minSeekingAge"] as? Int self.maxSeekingAge = dictionary["maxSeekingAge"] as? Int } func toUserDictionary() -> [String:Any]{ let dic : [String: Any] = [ "name": name ?? "", "uid": uid ?? "", "profession": profession ?? "", "age": age ?? 18, "city": city ?? "", "caption": caption ?? "", "imageUrls": imageUrls ?? [], "minSeekingAge": minSeekingAge ?? 18, "maxSeekingAge": maxSeekingAge ?? 80 ] return dic } }
43.203125
169
0.624955