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
0801666e19d3754e67f2912e95985b5b8a7d1284
265
// // URLRequest+Resource.swift // Demo // // Created by Josue Hernandez on 17/03/22. // import Foundation extension URLRequest { init(_ resource: Resource) { self.init(url: resource.url) self.httpMethod = resource.method } }
14.722222
43
0.618868
792434bb26c299957c39baea34056a03d64c1ebc
1,414
// // KMeansTests.swift // KMeansTests // // Created by Tatsuya Tanaka on 20171207. // Copyright © 2017年 tattn. All rights reserved. // import XCTest @testable import KMeans struct Vector3: KMeansElement { let x, y, z: Float static var zeroValue: Vector3 { return .init(x: 0, y: 0, z: 0) } func squareDistance(to vector: Vector3) -> Float { return pow(x - vector.x, 2) + pow(y - vector.y, 2) + pow(z - vector.z, 2) } static func +(left: Vector3, right: Vector3) -> Vector3 { return .init(x: left.x + right.x, y: left.y + right.y, z: left.z + right.z) } static func /(left: Vector3, right: Int) -> Vector3 { return .init(x: left.x / Float(right), y: left.y / Float(right), z: left.z / Float(right)) } } class KMeansTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testPerformanceExample() { var random: Float { return Float(arc4random()) / Float(UInt32.max) } let vectors = (1...100).map { _ in Vector3(x: random, y: random, z: random) } self.measure { let kMean = KMeans(elements: vectors, numberOfCentroids: 5, maxIteration: 300, convergeDistance: 0.001) print(kMean.centroids) } } }
26.185185
115
0.55587
330fac630f6ceefbfb8f98a04850e2441d5799d3
6,968
// // LoggerUtility.swift // UltimateLog // // Created by Peigen.Liu on 1/15/19. // Copyright © 2019 Peigen.Liu. All rights reserved. // import Foundation struct LoggerUtility { static func printInitInfo() { UltimateLog.v(msg: "=========== Ultimate Log - Init Infomation ===========") UltimateLog.v(msg: "Device Name : " + UIDevice.current.name) UltimateLog.v(msg: "System Version : " + UIDevice.current.systemVersion) UltimateLog.v(msg: "Device Model : " + UIDevice.current.model) UltimateLog.v(msg: "Model Name: " + UIDevice.current.modelName) let infoDic = Bundle.main.infoDictionary UltimateLog.v(msg: "App Version : " + (infoDic?["CFBundleShortVersionString"] as? String ?? "")) UltimateLog.v(msg: "Build Version : " + (infoDic?["CFBundleVersion"] as? String ?? "")) UltimateLog.v(msg: "App Identifier : " + (infoDic?["CFBundleIdentifier"] as? String ?? "")) UltimateLog.v(msg: "App Name : " + (infoDic?["CFBundleName"] as? String ?? "")) UltimateLog.v(msg: "=========== Ultimate Log - Init Infomation Done ===========") UltimateLog.v(msg: "\n\n\n\n") startMemoryMonitor() setCrashHandler() } static func startMemoryMonitor() { let deadlineTime = DispatchTime.now() + .seconds(30) DispatchQueue.main.asyncAfter(deadline: deadlineTime) { reportMemory() } } static func reportMemory() { var info = mach_task_basic_info() let MACH_TASK_BASIC_INFO_COUNT = MemoryLayout<mach_task_basic_info>.stride/MemoryLayout<natural_t>.stride var count = mach_msg_type_number_t(MACH_TASK_BASIC_INFO_COUNT) let kerr: kern_return_t = withUnsafeMutablePointer(to: &info) { $0.withMemoryRebound(to: integer_t.self, capacity: MACH_TASK_BASIC_INFO_COUNT) { task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count) } } UltimateLog.v(msg: "=========== Ultimate Log - Memory Infomation ===========") if kerr == KERN_SUCCESS { UltimateLog.v(msg: String(format: "Memory Usage : %ld MB(%ld KB) ", info.resident_size/1024/1024, info.resident_size/1024)) } else { UltimateLog.v(msg: "Error with task_info(): " + (String(cString: mach_error_string(kerr), encoding: String.Encoding.ascii) ?? "unknown error")) } UltimateLog.v(msg: "=========== Ultimate Log - Memory Infomation Done ===========") UltimateLog.v(msg: "\n\n\n\n") } static func setCrashHandler() { reportMemory() NSSetUncaughtExceptionHandler { (exception) in let arr:NSArray = exception.callStackSymbols as NSArray let reason:String = exception.reason! let name:String = exception.name.rawValue let date:NSDate = NSDate() let timeFormatter = DateFormatter() timeFormatter.dateFormat = "YYYY/MM/dd hh:mm:ss SS" let strNowTime = timeFormatter.string(from: date as Date) as String let url:String = String.init(format: "\n❌❌❌❌❌❌❌❌ FATAL ERROR ❌❌❌❌❌❌❌❌\nTime:%@\nName:%@\nReason:\n%@\nCallStackSymbols:\n%@",strNowTime,name,reason,arr.componentsJoined(by: "\n")) UltimateLog.e(msg: url) } } } public extension UIDevice { var modelName: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone8,4": return "iPhone SE" case "iPhone10,1", "iPhone10,4": return "iPhone 8" case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": return "iPhone X" case "iPhone11,2": return "iPhone Xs" case "iPhone11,4", "iPhone11,6": return "iPhone Xs Max" case "iPhone11,8": return "iPhone XR" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4": return "iPad Pro 9 Inch" case "iPad6,7", "iPad6,8": return "iPad Pro 12 Inch" case "iPad7,1", "iPad7,2": return "iPad Pro 12 Inch2" case "iPad7,3", "iPad7,4": return "iPad Pro 10 Inch" case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4": return "iPad Pro 11 Inch" case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8": return "iPad Pro 12 Inch3" case "AppleTV5,3": return "Apple TV" case "i386", "x86_64": return "Simulator" default: return identifier } } }
44.954839
193
0.516361
4bea943a8de3b7f40b36a703e565b58d54212b36
738
// // RxTableViewDataSourceType.swift // RxCocoa // // Created by Krunoslav Zaher on 6/26/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit import RxSwift /// Marks data source as `UITableView` reactive data source enabling it to be used with one of the `bindTo` methods. public protocol RxTableViewDataSourceType /*: UITableViewDataSource*/ { /// Type of elements that can be bound to table view. associatedtype Element /// New observable sequence event observed. /// /// - parameter tableView: Bound table view. /// - parameter observedEvent: Event func tableView(_ tableView: UITableView, observedEvent: Event<Element>) -> Void } #endif
26.357143
116
0.701897
1a2ac5ac1a2526979aa1ff46405feaeb199abe3c
4,170
// // ArrayExtensionsTests.swift // SwifterSwift // // Created by Omar Albeik on 8/26/16. // Copyright © 2016 SwifterSwift // import XCTest @testable import SwifterSwift private struct Person: Equatable { var name: String var age: Int? static func == (lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name && lhs.age == rhs.age } } final class ArrayExtensionsTests: XCTestCase { func testPrepend() { var arr = [2, 3, 4, 5] arr.prepend(1) XCTAssertEqual(arr, [1, 2, 3, 4, 5]) } func testSafeSwap() { var array: [Int] = [1, 2, 3, 4, 5] array.safeSwap(from: 3, to: 0) XCTAssertEqual(array[3], 1) XCTAssertEqual(array[0], 4) var newArray = array newArray.safeSwap(from: 1, to: 1) XCTAssertEqual(newArray, array) newArray = array newArray.safeSwap(from: 1, to: 12) XCTAssertEqual(newArray, array) let emptyArray: [Int] = [] var swappedEmptyArray = emptyArray swappedEmptyArray.safeSwap(from: 1, to: 3) XCTAssertEqual(swappedEmptyArray, emptyArray) } func testDivided() { let input = [0, 1, 2, 3, 4, 5] let (even, odd) = input.divided { $0 % 2 == 0 } XCTAssertEqual(even, [0, 2, 4]) XCTAssertEqual(odd, [1, 3, 5]) // Parameter names + indexes let tuple = input.divided { $0 % 2 == 0 } XCTAssertEqual(tuple.matching, [0, 2, 4]) XCTAssertEqual(tuple.0, [0, 2, 4]) XCTAssertEqual(tuple.nonMatching, [1, 3, 5]) XCTAssertEqual(tuple.1, [1, 3, 5]) } func testKeyPathSorted() { let array = [Person(name: "James", age: 32), Person(name: "Wade", age: 36), Person(name: "Rose", age: 29)] XCTAssertEqual(array.sorted(by: \Person.name), [Person(name: "James", age: 32), Person(name: "Rose", age: 29), Person(name: "Wade", age: 36)]) XCTAssertEqual(array.sorted(by: \Person.name, ascending: false), [Person(name: "Wade", age: 36), Person(name: "Rose", age: 29), Person(name: "James", age: 32)]) // Testing Optional keyPath XCTAssertEqual(array.sorted(by: \Person.age), [Person(name: "Rose", age: 29), Person(name: "James", age: 32), Person(name: "Wade", age: 36)]) XCTAssertEqual(array.sorted(by: \Person.age, ascending: false), [Person(name: "Wade", age: 36), Person(name: "James", age: 32), Person(name: "Rose", age: 29)]) // Testing Mutating var mutableArray = [Person(name: "James", age: 32), Person(name: "Wade", age: 36), Person(name: "Rose", age: 29)] mutableArray.sort(by: \Person.name) XCTAssertEqual(mutableArray, [Person(name: "James", age: 32), Person(name: "Rose", age: 29), Person(name: "Wade", age: 36)]) // Testing Mutating Optional keyPath mutableArray.sort(by: \Person.age) XCTAssertEqual(mutableArray, [Person(name: "Rose", age: 29), Person(name: "James", age: 32), Person(name: "Wade", age: 36)]) // Testing nil path let nilArray = [Person(name: "James", age: nil), Person(name: "Wade", age: nil)] XCTAssertEqual(nilArray.sorted(by: \Person.age), [Person(name: "James", age: nil), Person(name: "Wade", age: nil)]) } func testRemoveAll() { var arr = [0, 1, 2, 0, 3, 4, 5, 0, 0] arr.removeAll(0) XCTAssertEqual(arr, [1, 2, 3, 4, 5]) arr = [] arr.removeAll(0) XCTAssertEqual(arr, []) } func testRemoveAllItems() { var arr = [0, 1, 2, 2, 0, 3, 4, 5, 0, 0] arr.removeAll([0, 2]) XCTAssertEqual(arr, [1, 3, 4, 5]) arr.removeAll([]) XCTAssertEqual(arr, [1, 3, 4, 5]) arr = [] arr.removeAll([]) XCTAssertEqual(arr, []) } func testRemoveDuplicates() { var array = [1, 1, 2, 2, 3, 3, 3, 4, 5] array.removeDuplicates() XCTAssertEqual(array, [1, 2, 3, 4, 5]) } func testWithoutDuplicates() { XCTAssertEqual([1, 1, 2, 2, 3, 3, 3, 4, 5].withoutDuplicates(), [1, 2, 3, 4, 5]) XCTAssertEqual(["h", "e", "l", "l", "o"].withoutDuplicates(), ["h", "e", "l", "o"]) } }
35.042017
168
0.568106
ff2128229a3e52975f46c9f66b97ba1b09c54584
4,145
// // Copyright (C) 2020 Twilio, 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 Nimble import Quick @testable import VideoApp class PasscodeComponentsSpec: QuickSpec { override func spec() { var sut: PasscodeComponents? describe("init") { context("when string is new format") { context("when string length is 14") { beforeEach { sut = try? PasscodeComponents(string: "65897412385467") } it("sets passcode to entire string") { expect(sut?.passcode).to(equal("65897412385467")) } it("sets appID to characters at indices 6 to 9") { expect(sut?.appID).to(equal("1238")) } it("sets serverlessID to last 4 characters") { expect(sut?.serverlessID).to(equal("5467")) } } context("when string length is 20") { beforeEach { sut = try? PasscodeComponents(string: "59846823174859632894") } it("sets passcode to entire string") { expect(sut?.passcode).to(equal("59846823174859632894")) } it("sets appID to characters at indices 6 to 9") { expect(sut?.appID).to(equal("2317")) } it("sets serverlessID to last 10 characters") { expect(sut?.serverlessID).to(equal("4859632894")) } } } context("when string is old format") { context("when string length is 10") { beforeEach { sut = try? PasscodeComponents(string: "5987462314") } it("sets passcode to entire string") { expect(sut?.passcode).to(equal("5987462314")) } it("sets appID to nil") { expect(sut?.appID).to(beNil()) } it("sets serverlessID to last 4 characters") { expect(sut?.serverlessID).to(equal("2314")) } } context("when string length is 13") { beforeEach { sut = try? PasscodeComponents(string: "9874652871365") } it("sets passcode to entire string") { expect(sut?.passcode).to(equal("9874652871365")) } it("sets appID to nil") { expect(sut?.appID).to(beNil()) } it("sets serverlessID to last 7 characters") { expect(sut?.serverlessID).to(equal("2871365")) } } } context("when string is invalid") { context("when string length is 6") { it("throws passcodeIncorrect error") { expect({ try PasscodeComponents(string: "256984") }).to(throwError(AuthError.passcodeIncorrect)) } } } } } }
36.359649
120
0.446562
6a619e6854ec2950a58a1f0478efafda5dec7623
2,171
// // AppDelegate.swift // Ejianqian // // Created by wangjiayu on 2018/6/13. // Copyright © 2018年 wangjiayu. All rights reserved. // 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 } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.191489
285
0.755873
4bfb348f641cdaa3fcac47fad75bac31d338ddfc
1,108
// 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: "AiryLayout", platforms: [ .iOS(.v9), ], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "AiryLayout", targets: ["AiryLayout"]), ], 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: "AiryLayout", dependencies: []), .testTarget( name: "AiryLayoutTests", dependencies: ["AiryLayout"]), ], swiftLanguageVersions: [.v5] )
33.575758
122
0.612816
ac4dded53beb9112217fb0bb016b601e0f6ec94e
8,848
// // MXTableManager.swift // CrossFit Affiliates // // Created by Henrique Morbin on 11/10/15. // Copyright © 2015 Morbix. All rights reserved. // import UIKit public class TableManager: NSObject { public let tableView : UITableView public var sections = [Section]() public var visibleSections :[Section] { return sections.filter({ (section) -> Bool in return section.visible }) } public var stateRows : StateRowsTuple? public var state : ScreenState = .None { didSet { self.tableView.reloadData() } } static let kDefaultIdentifier = "TableManager_Default_Cell" public init(tableView : UITableView){ self.tableView = tableView super.init() self.tableView.delegate = self self.tableView.dataSource = self self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: TableManager.kDefaultIdentifier) } // MARK: Methods public func reloadData(){ tableView.reloadData() } public func rowForIndexPath(indexPath: NSIndexPath) -> Row{ if let stateRows = stateRows{ switch state { case .Loading: return stateRows.loading case .Empty: return stateRows.empty case .Error: return stateRows.error default: return visibleSections[indexPath.section].visibleRows[indexPath.row] } }else{ return visibleSections[indexPath.section].visibleRows[indexPath.row] } } public func sectionForIndex(index: Int) -> Section { if visibleSections.count > index{ return visibleSections[index] }else{ return Section() } } // MARK: Default State Rows public static func getDefaultStateRows() -> StateRowsTuple{ let handler :ConfigureCellBlock = { (object, cell, indexPath) -> Void in if let object = object as? String { cell.textLabel?.text = object cell.textLabel?.textAlignment = .Center cell.selectionStyle = .None } } let loadingRow = Row(identifier: TableManager.kDefaultIdentifier, object: "Loading...", configureCell: handler) let emptyRow = Row(identifier: TableManager.kDefaultIdentifier, object: "Empty", configureCell: handler) let errorRow = Row(identifier: TableManager.kDefaultIdentifier, object: "Error", configureCell: handler) return (loadingRow, emptyRow, errorRow) } } // MARK: UITableViewDataSource extension TableManager : UITableViewDataSource { public func numberOfSectionsInTableView(tableView: UITableView) -> Int { if stateRows != nil && state != .None { return 1 }else{ return visibleSections.count } } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if stateRows != nil && state != .None { return 1 }else{ return visibleSections.count > section ? visibleSections[section].visibleRows.count : 0 } } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //let row = visibleSections[indexPath.section].visibleRows[indexPath.row] let row = rowForIndexPath(indexPath) if let cellForRowAtIndexPath = row.cellForRowAtIndexPath { return cellForRowAtIndexPath(row: row, tableView: tableView, indexPath: indexPath) } let cell = tableView.dequeueReusableCellWithIdentifier(row.identifier, forIndexPath: indexPath) if let configureCell = row.configureCell { configureCell(object: row.object, cell: cell, indexPath: indexPath) }else if let cell = cell as? ConfigureCell { cell.configureCell(row.object, target: self, indexPath: indexPath) } return cell } public func tableView(tableView: UITableView, heightForHeaderInSection index: Int) -> CGFloat { let section = sectionForIndex(index) if let heightForHeaderInSection = section.heightForHeaderInSection { return heightForHeaderInSection(section: section, tableView: tableView, index: index) } return CGFloat(section.heightForStaticHeader) } public func tableView(tableView: UITableView, titleForHeaderInSection index: Int) -> String? { let section = sectionForIndex(index) if let titleForHeaderInSection = section.titleForHeaderInSection { return titleForHeaderInSection(section: section, tableView: tableView, index: index) } if let titleForStaticHeader = section.titleForStaticHeader { return titleForStaticHeader } return nil } public func tableView(tableView: UITableView, viewForHeaderInSection index: Int) -> UIView? { let section = sectionForIndex(index) if let viewForHeaderInSection = section.viewForHeaderInSection { return viewForHeaderInSection(section: section, tableView: tableView, index: index) } if let viewForStaticHeader = section.viewForStaticHeader { return viewForStaticHeader } return nil } } // MARK: UITableViewDelegate extension TableManager : UITableViewDelegate { public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let row = rowForIndexPath(indexPath) if let didSelectRowAtIndexPath = row.didSelectRowAtIndexPath { didSelectRowAtIndexPath(row: row, tableView: tableView, indexPath: indexPath) } } } // MARK: Classes public class Section: NSObject { public var visible = true public var rows = [Row]() public var visibleRows :[Row] { return rows.filter({ (row) -> Bool in return row.visible }) } public var heightForStaticHeader = 0.0 public var heightForHeaderInSection : HeightForHeaderInSectionBlock? public var titleForStaticHeader : String? public var titleForHeaderInSection : TitleForHeaderInSectionBlock? public var viewForStaticHeader : UIView? public var viewForHeaderInSection : ViewForHeaderInSectionBlock? } public class Row: NSObject { public let identifier : String public var visible = true public var object : AnyObject? public var configureCell : (ConfigureCellBlock)? public var cellForRowAtIndexPath : (CellForRowAtIndexPathBlock)? public var didSelectRowAtIndexPath : (DidSelectRowAtIndexPath)? public init(identifier: String){ self.identifier = identifier } public convenience init(identifier:String, object:AnyObject?, configureCell:ConfigureCellBlock?) { self.init(identifier: identifier) self.object = object self.configureCell = configureCell } } // MARK: Type Alias public typealias StateRowsTuple = (loading: Row, empty: Row, error: Row) public typealias ConfigureCellBlock = (object:Any?, cell:UITableViewCell, indexPath: NSIndexPath) -> Void public typealias CellForRowAtIndexPathBlock = (row: Row, tableView: UITableView, indexPath: NSIndexPath) -> UITableViewCell public typealias HeightForHeaderInSectionBlock = (section: Section, tableView: UITableView, index: Int) -> CGFloat public typealias ViewForHeaderInSectionBlock = (section: Section, tableView: UITableView, index: Int) -> UIView public typealias TitleForHeaderInSectionBlock = (section: Section, tableView: UITableView, index: Int) -> String public typealias DidSelectRowAtIndexPath = (row: Row, tableView: UITableView, indexPath: NSIndexPath) -> Void // MARK: ScreenState public enum ScreenState : String { case None = "" case Loading = "Loading..." case Empty = "No Data" case Error = "Error" public mutating func setByResultsAndErrors(results : [AnyObject], errors: [NSError]){ if (results.count > 0) { self = .None }else if (errors.count > 0) { self = .Error }else { self = .Empty } } public mutating func setByResultsAndError(results : [AnyObject], error: NSError?){ if (results.count > 0) { self = .None }else if (error != nil) { self = .Error }else { self = .Empty } } } // MARK: Protocols public protocol ConfigureCell { func configureCell(object: Any?, target: AnyObject?, indexPath: NSIndexPath?) }
33.770992
124
0.644326
5dfb956325ab4d81aa72bbb86ad14e898abf22cb
1,170
// // CharacterCellViewInspectorTest.swift // TheOneAppTests // // Created by Silvia España on 22/12/21. // @testable import TheOneApp import XCTest import ViewInspector import SwiftUI extension CharacterCellView: Inspectable { } class CharacterCellViewInspectorTest: XCTestCase { override func setUpWithError() throws { super.setUp() } override func tearDownWithError() throws { super.tearDown() } // Given let sut = CharacterCellView(id: "5cd99d4bde30eff6ebccfc07", race: "Elf", name: "Arwen", image: "https://pbs.twimg.com/profile_images/378800000054269606/3dd75f69faf233c299b7428a1c0ea811.jpeg") func testNameSetUp() { // When let tag = "characterName" let nameLabel = try! sut.inspect().find(viewWithTag: tag).text().string() // Then XCTAssertEqual(self.sut.name, nameLabel) } func testRaceSetUp() { // When let tag = "characterRace" let raceLabel = try! sut.inspect().find(viewWithTag: tag).text().string() // Then XCTAssertEqual(self.sut.race, raceLabel) } }
24.375
196
0.630769
ed9c133d35ba106c131424ade92969ceec5a0233
854
// import SwiftUI /// The extension from the article broke in Xcode 12.5 and no longer work /// properly. /// /// This updated extension is uglier but works as expected. extension NavigationLink where Label == EmptyView, Destination == AnyView { public init<V: Identifiable, Destination2: View>( item: Binding<V?>, destination: @escaping (V) -> Destination2 ) { let value: V? = item.wrappedValue let isActive: Binding<Bool> = Binding( get: { item.wrappedValue != nil }, set: { value in if !value { item.wrappedValue = nil } } ) self.init( destination: AnyView(Group { if let value = value { destination(value) } else { EmptyView() } }), isActive: isActive, label: EmptyView.init ) } }
22.473684
75
0.570258
d6cec54adee635973ca3219441cb67d02ee6b9dd
1,605
// // UITabBarAppearance+Chainable.swift // // // Created by 柴阿文 on 2021/2/6. // import UIKit @available(iOS 13.0, *) public extension ChainableWrapper where Wrapped: UITabBarAppearance { @discardableResult func stackedLayoutAppearance(_ appearance: UITabBarItemAppearance) -> Self { wrapped.stackedLayoutAppearance = appearance return self } @discardableResult func stackedItemPositioning(_ position: UITabBar.ItemPositioning) -> Self { wrapped.stackedItemPositioning = position return self } @discardableResult func stackedItemSpacing(_ spacing: CGFloat) -> Self { wrapped.stackedItemSpacing = spacing return self } @discardableResult func stackedItemWidth(_ spacing: CGFloat) -> Self { wrapped.stackedItemWidth = spacing return self } @discardableResult func inlineLayoutAppearance(_ appearance: UITabBarItemAppearance) -> Self { wrapped.inlineLayoutAppearance = appearance return self } @discardableResult func compactInlineLayoutAppearance(_ appearance: UITabBarItemAppearance) -> Self { wrapped.compactInlineLayoutAppearance = appearance return self } @discardableResult func selectionIndicatorTintColor(_ color: UIColor?) -> Self { wrapped.selectionIndicatorTintColor = color return self } @discardableResult func selectionIndicatorImage(_ image: UIImage?) -> Self { wrapped.selectionIndicatorImage = image return self } }
25.887097
86
0.675389
870760323a182e506e107dcb891b7a68de840130
6,039
// // Video.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. 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 Foundation extension Storefront { /// Represents a Shopify hosted video. open class VideoQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = Video /// A word or phrase to share the nature or contents of a media. @discardableResult open func alt(alias: String? = nil) -> VideoQuery { addField(field: "alt", aliasSuffix: alias) return self } /// Globally unique identifier. @discardableResult open func id(alias: String? = nil) -> VideoQuery { addField(field: "id", aliasSuffix: alias) return self } /// The media content type. @discardableResult open func mediaContentType(alias: String? = nil) -> VideoQuery { addField(field: "mediaContentType", aliasSuffix: alias) return self } /// The preview image for the media. @discardableResult open func previewImage(alias: String? = nil, _ subfields: (ImageQuery) -> Void) -> VideoQuery { let subquery = ImageQuery() subfields(subquery) addField(field: "previewImage", aliasSuffix: alias, subfields: subquery) return self } /// The sources for a video. @discardableResult open func sources(alias: String? = nil, _ subfields: (VideoSourceQuery) -> Void) -> VideoQuery { let subquery = VideoSourceQuery() subfields(subquery) addField(field: "sources", aliasSuffix: alias, subfields: subquery) return self } } /// Represents a Shopify hosted video. open class Video: GraphQL.AbstractResponse, GraphQLObject, Media, Node { public typealias Query = VideoQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "alt": if value is NSNull { return nil } guard let value = value as? String else { throw SchemaViolationError(type: Video.self, field: fieldName, value: fieldValue) } return value case "id": guard let value = value as? String else { throw SchemaViolationError(type: Video.self, field: fieldName, value: fieldValue) } return GraphQL.ID(rawValue: value) case "mediaContentType": guard let value = value as? String else { throw SchemaViolationError(type: Video.self, field: fieldName, value: fieldValue) } return MediaContentType(rawValue: value) ?? .unknownValue case "previewImage": if value is NSNull { return nil } guard let value = value as? [String: Any] else { throw SchemaViolationError(type: Video.self, field: fieldName, value: fieldValue) } return try Image(fields: value) case "sources": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: Video.self, field: fieldName, value: fieldValue) } return try value.map { return try VideoSource(fields: $0) } default: throw SchemaViolationError(type: Video.self, field: fieldName, value: fieldValue) } } /// A word or phrase to share the nature or contents of a media. open var alt: String? { return internalGetAlt() } func internalGetAlt(alias: String? = nil) -> String? { return field(field: "alt", aliasSuffix: alias) as! String? } /// Globally unique identifier. open var id: GraphQL.ID { return internalGetId() } func internalGetId(alias: String? = nil) -> GraphQL.ID { return field(field: "id", aliasSuffix: alias) as! GraphQL.ID } /// The media content type. open var mediaContentType: Storefront.MediaContentType { return internalGetMediaContentType() } func internalGetMediaContentType(alias: String? = nil) -> Storefront.MediaContentType { return field(field: "mediaContentType", aliasSuffix: alias) as! Storefront.MediaContentType } /// The preview image for the media. open var previewImage: Storefront.Image? { return internalGetPreviewImage() } func internalGetPreviewImage(alias: String? = nil) -> Storefront.Image? { return field(field: "previewImage", aliasSuffix: alias) as! Storefront.Image? } /// The sources for a video. open var sources: [Storefront.VideoSource] { return internalGetSources() } func internalGetSources(alias: String? = nil) -> [Storefront.VideoSource] { return field(field: "sources", aliasSuffix: alias) as! [Storefront.VideoSource] } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { var response: [GraphQL.AbstractResponse] = [] objectMap.keys.forEach { switch($0) { case "previewImage": if let value = internalGetPreviewImage() { response.append(value) response.append(contentsOf: value.childResponseObjectMap()) } case "sources": internalGetSources().forEach { response.append($0) response.append(contentsOf: $0.childResponseObjectMap()) } default: break } } return response } } }
31.952381
98
0.702269
21bd007c558f44d275ab48e481c71682a3384295
7,462
/*   Copyright 2018-2021 Prebid.org, 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 import XCTest @testable import PrebidMobile class VideoEventsTest : XCTestCase, PBMCreativeViewDelegate, PBMVideoViewDelegate { let viewController = MockViewController() let modalManager = PBMModalManager() var pbmVideoCreative:PBMVideoCreative! var expectationVideoDidComplete:XCTestExpectation! var expectationCreativeDidComplete:XCTestExpectation! var expectationDownloadCompleted:XCTestExpectation! var expectationCreativeDidDisplay:XCTestExpectation! override func setUp() { super.setUp() MockServer.shared.reset() } override func tearDown() { MockServer.shared.reset() Prebid.reset() super.tearDown() } func testTypes() { self.continueAfterFailure = true Prebid.forcedIsViewable = true defer { Prebid.reset() } self.expectationDownloadCompleted = self.expectation(description: "expectationCreativeReady") self.expectationVideoDidComplete = self.expectation(description: "expectationCreativeDidComplete") self.expectationCreativeDidDisplay = self.expectation(description: "expectationCreativeDidDisplay") //Make an PBMServerConnection and redirect its network requests to the Mock Server let connection = UtilitiesForTesting.createConnectionForMockedTest() //Change the inline response to claim that it will respond with m4v var inlineResponse = UtilitiesForTesting.loadFileAsStringFromBundle("document_with_one_inline_ad.xml")! let needle = MockServerMimeType.MP4.rawValue let replaceWith = MockServerMimeType.MP4.rawValue inlineResponse = inlineResponse.PBMstringByReplacingRegex(needle, replaceWith:replaceWith) //Rule for VAST let ruleVAST = MockServerRule(urlNeedle: "foo.com/inline", mimeType: MockServerMimeType.XML.rawValue, connectionID: connection.internalID, strResponse: inlineResponse) //Add a rule for video File let ruleVideo = MockServerRule(urlNeedle: "http://get_video_file", mimeType: MockServerMimeType.MP4.rawValue, connectionID: connection.internalID, fileName: "small.mp4") MockServer.shared.resetRules([ruleVAST, ruleVideo]) //Create adConfiguration let adConfiguration = PBMAdConfiguration() adConfiguration.adFormats = [.video] adConfiguration.winningBidAdFormat = .video // adConfiguration.domain = "foo.com/inline" //Create CreativeModel let creativeModel = PBMCreativeModel(adConfiguration:adConfiguration) creativeModel.videoFileURL = "http://get_video_file" let eventTracker = MockPBMAdModelEventTracker(creativeModel: creativeModel, serverConnection: connection) let expectationTrackEvent = expectation(description:"expectationTrackEvent") var trackEventCalled = false // Need to check general usage. Testing of particular events is performed by another test. eventTracker.mock_trackEvent = { _ in if !trackEventCalled { expectationTrackEvent.fulfill() trackEventCalled = true } } let expectationVideoAdLoaded = expectation(description:"expectationVideoAdLoaded") eventTracker.mock_trackVideoAdLoaded = { _ in expectationVideoAdLoaded.fulfill() } let expectationStartVideo = expectation(description:"expectationStartVideo") eventTracker.mock_trackStartVideo = { _, _ in expectationStartVideo.fulfill() } let expectationVolumeChanged = expectation(description:"expectationVolumeChanged") var trackVolumeChanged = false // Need to check general usage. eventTracker.mock_trackVolumeChanged = { _, _ in if !trackVolumeChanged { expectationVolumeChanged.fulfill() trackVolumeChanged = true } } creativeModel.eventTracker = eventTracker let transaction = UtilitiesForTesting.createEmptyTransaction() transaction.creativeModels = [creativeModel] //Get a Creative let creativeFactory = PBMCreativeFactory(serverConnection:connection, transaction: transaction, finishedCallback: { creatives, error in if (error != nil) { XCTFail("error: \(error?.localizedDescription ?? "")") } self.expectationDownloadCompleted.fulfill() expectationVideoAdLoaded.fulfill() guard let pbmVideoCreative = creatives?.first as? PBMVideoCreative else { XCTFail("Could not cast creative as PBMVideoCreative") return } pbmVideoCreative.creativeViewDelegate = self pbmVideoCreative.videoView.videoViewDelegate = self self.pbmVideoCreative = pbmVideoCreative DispatchQueue.main.async { self.pbmVideoCreative.display(withRootViewController: self.viewController) self.pbmVideoCreative.videoView.avPlayer.volume = 0.33 } }) DispatchQueue.global().async { creativeFactory.start() } self.waitForExpectations(timeout: 10, handler:nil) } //MARK: - CreativeViewDelegate func creativeDidComplete(_ creative: PBMAbstractCreative) { self.expectationCreativeDidComplete.fulfill() } func videoCreativeDidComplete(_ creative: PBMAbstractCreative) {} func creativeWasClicked(_ creative: PBMAbstractCreative) {} func creativeClickthroughDidClose(_ creative: PBMAbstractCreative) {} func creativeInterstitialDidClose(_ creative: PBMAbstractCreative) {} func creativeReady(toReimplant creative: PBMAbstractCreative) {} func creativeMraidDidCollapse(_ creative: PBMAbstractCreative) {} func creativeMraidDidExpand(_ creative: PBMAbstractCreative) {} func creativeInterstitialDidLeaveApp(_ creative: PBMAbstractCreative) {} func creativeDidDisplay(_ creative: PBMAbstractCreative) { self.expectationCreativeDidDisplay.fulfill() } func videoViewWasTapped() {} func learnMoreWasClicked() {} func creativeViewWasClicked(_ creative: PBMAbstractCreative) {} func creativeFullScreenDidFinish(_ creative: PBMAbstractCreative) {} // MARK: - PBMVideoViewDelegate func videoViewFailedWithError(_ error: Error) {} func videoViewReadyToDisplay() {} func videoViewCompletedDisplay() { self.expectationVideoDidComplete.fulfill() self.modalManager.popModal() } func videoWasClicked() {} }
40.775956
178
0.682927
ed587fcc54c77d9547c19220d28e5ca99ac14e2d
644
import Foundation public class iiDate { public class func toStringAsYearMonthDay(date: NSDate) -> String { let components = NSCalendar.currentCalendar().components( [NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year], fromDate: date) return "\(components.year).\(components.month).\(components.day)" } public class func fromYearMonthDay(year: Int, month: Int, day: Int) -> NSDate? { let dateComponents = NSDateComponents() dateComponents.year = year dateComponents.month = month dateComponents.day = day return NSCalendar.currentCalendar().dateFromComponents(dateComponents) } }
29.272727
82
0.726708
0e772e871e996d38cedc54cffd85873c8dcf7ef3
12,251
// // BLEPrinterService.swift // OneGreenDiary // // Originally Created - ( empty ;-) ) by Abhay Chaudhary on 1/26/16. // Reworked and made functional by V. Ganesh, added general framework for handing BLE printers // // Copyright © 2016 OneGreenDiary Software Pvt. Ltd. // // 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 CoreBluetooth import BluetoothKit class BLEPrinterService : BKPeripheralDelegate, BKCentralDelegate, BKAvailabilityObserver, BKRemotePeripheralDelegate { let peripheral = BKPeripheral() let central = BKCentral() // The UUID for the white lable BLE printer, obtained using LighBlue app. // The same may be obtained using any other Bluetooth explorer app. var serviceUUID = NSUUID(UUIDString: "E7810A71-73AE-499D-8C15-FAA9AEF0C3F2") var characteristicUUID = NSUUID(UUIDString: "BEF8D6C9-9C21-4C9E-B632-BD58C1009F9F") var deviceReady = false; var connectedDevice:BKRemotePeripheral?; internal init() { self.initCentral() } // set a new service UUID, need to call initCentral() after this func setServiceUUID(suid: NSUUID) { self.serviceUUID = suid } // set a new characteristic UUID, need to call initCentral() after this func setCharacteristicUUID(cuid: NSUUID) { self.characteristicUUID = cuid } func isDeviceReady() -> Bool { return self.deviceReady } func initCentral() { do { central.delegate = self; central.addAvailabilityObserver(self) let configuration = BKConfiguration(dataServiceUUID: serviceUUID!, dataServiceCharacteristicUUID: characteristicUUID!) try central.startWithConfiguration(configuration) } catch let error { print("ERROR - initCentral") print(error) } } // helper function to convert a hext string to NSData func hexToNSData(string: String) -> NSData { let length = string.characters.count let rawData = UnsafeMutablePointer<CUnsignedChar>.alloc(length/2) var rawIndex = 0 for var index = 0; index < length; index+=2{ let single = NSMutableString() single.appendString(string.substringWithRange(Range(start:string.startIndex.advancedBy(index), end:string.startIndex.advancedBy(index+2)))) rawData[rawIndex] = UInt8(single as String, radix:16)! rawIndex++ } let data:NSData = NSData(bytes: rawData, length: length/2) rawData.dealloc(length/2) return data } func printLine(line: String) { if !self.deviceReady { return } let lineFeed = self.hexToNSData("0A") let printer = self.connectedDevice!.getPeripheral()! printer.writeValue(line.dataUsingEncoding(NSUTF8StringEncoding)!, forCharacteristic: self.connectedDevice!.getCharacteristic()!, type: CBCharacteristicWriteType.WithResponse) printer.writeValue(lineFeed, forCharacteristic: self.connectedDevice!.getCharacteristic()!, type: CBCharacteristicWriteType.WithResponse) } func printToBuffer(line: String) { if !self.deviceReady { return } let printer = self.connectedDevice!.getPeripheral()! printer.writeValue(line.dataUsingEncoding(NSUTF8StringEncoding)!, forCharacteristic: self.connectedDevice!.getCharacteristic()!, type: CBCharacteristicWriteType.WithResponse) } func printTab() { if !self.deviceReady { return } let tabFeed = self.hexToNSData("09") let printer = self.connectedDevice!.getPeripheral()! printer.writeValue(tabFeed, forCharacteristic: self.connectedDevice!.getCharacteristic()!, type: CBCharacteristicWriteType.WithResponse) } func printLineFeed() { if !self.deviceReady { return } let lineFeed = self.hexToNSData("0A") let printer = self.connectedDevice!.getPeripheral()! printer.writeValue(lineFeed, forCharacteristic: self.connectedDevice!.getCharacteristic()!, type: CBCharacteristicWriteType.WithResponse) } // actual scan function func scan() { central.scanContinuouslyWithChangeHandler({ changes, discoveries in print("Discovery List") print(discoveries) // assume that the first discovery is the printer we desire to connect, // in ideal world this is true, but in reality you may have additional checks to make if let firstPrinter = discoveries.first { if (self.connectedDevice != firstPrinter.remotePeripheral) { // if we are not already connected, connect to the printer device self.central.connect(30, remotePeripheral: firstPrinter.remotePeripheral) { remotePeripheral, error in if error == nil { self.deviceReady = false; self.connectedDevice = nil; print("Connection DONE") print(remotePeripheral) print(error) remotePeripheral.delegate = self if remotePeripheral.state == BKRemotePeripheral.State.Connected { print("REMOTE connected") print(remotePeripheral.identifier) print(remotePeripheral.getConfiguration()) // once connected, set appropriate flags self.deviceReady = true self.connectedDevice = firstPrinter.remotePeripheral } } } } } else if discoveries.count == 0 && self.connectedDevice != nil { self.deviceReady = true // print("WRITING") // self.printLine("OneGreenDiary") // print("DONE WRITING") } }, stateHandler: { newState in if newState == .Scanning { print("Scanning") } else if newState == .Stopped { print("Stopped") } }, duration: 5, inBetweenDelay: 10, errorHandler: { error in print("ERROR - scan") print(error) }) } func peripheral(peripheral: BKPeripheral, remoteCentralDidConnect remoteCentral: BKRemoteCentral) { //print("CONNECT") //print(peripheral) } func peripheral(peripheral: BKPeripheral, remoteCentralDidDisconnect remoteCentral: BKRemoteCentral) { //print("DISCONNECT") //print(peripheral) } func central(central: BKCentral, remotePeripheralDidDisconnect remotePeripheral: BKRemotePeripheral) { //print("CENTRAL") //print(central) } func availabilityObserver(availabilityObservable: BKAvailabilityObservable, availabilityDidChange availability: BKAvailability) { print("AVAILABLE - 1") // scan auto starts on availability of the bluetooth device scan() } func availabilityObserver(availabilityObservable: BKAvailabilityObservable, unavailabilityCauseDidChange unavailabilityCause: BKUnavailabilityCause) { print("AVAILABLE - 2") // scan auto starts on availability of the bluetooth device scan() } func remotePeripheral(remotePeripheral: BKRemotePeripheral, didUpdateName name: String) { // print("NAME CHANGE \(name)") } func remotePeripheral(remotePeripheral: BKRemotePeripheral, didSendArbitraryData data: NSData) { // print("REMOTE DATA") // print(remotePeripheral) // print(data) } // helper functions var CHARS_PER_LINE = 30 func centerText(text: String, spaceChar: NSString = " ") -> String { let nChars = text.length // print(String(format: "Item%22s%3s", " ".cStringUsingEncoding(NSASCIIStringEncoding), "Qty".cStringUsingEncoding(NSASCIIStringEncoding))) if nChars >= CHARS_PER_LINE { return text.substringToIndex(text.startIndex.advancedBy(CHARS_PER_LINE)) } else { let totalSpaces = CHARS_PER_LINE - nChars let spacesOnEachSide = totalSpaces / 2 let spacesString = "%\(spacesOnEachSide)s" let centeredString = String(format: spacesString + text + spacesString, spaceChar.cStringUsingEncoding(NSASCIIStringEncoding), spaceChar.cStringUsingEncoding(NSASCIIStringEncoding)) return centeredString } } func rowText(colText: [String], colWidth: [Int], padSpace: [String], spaceChar: NSString = " ") -> String { let nCols = colText.count if nCols != colWidth.count { return "" } if nCols != padSpace.count { return "" } let totalColWidth = colWidth.reduce(0, combine: +) if totalColWidth > CHARS_PER_LINE { return "" } var rowLine = "" for var cidx=0; cidx<nCols; cidx++ { let ct = colText[cidx] let cw = colWidth[cidx] let ctw = ct.length if ctw > cw { // simply truncate text to fit let cutText = ct.substringToIndex(ct.startIndex.advancedBy(cw+1)) rowLine += cutText } else { var totalSpaces = cw - ctw + 1 var spacesString = "%\(totalSpaces)s" // this is normally padded right, left aligned if padSpace[cidx] == "R" { let colLineText = String(format: ct + spacesString, spaceChar.cStringUsingEncoding(NSASCIIStringEncoding)) rowLine += colLineText } else if padSpace[cidx] == "L" { let colLineText = String(format: spacesString + ct, spaceChar.cStringUsingEncoding(NSASCIIStringEncoding)) rowLine += colLineText } else if padSpace[cidx] == "C" { let spacesOnEachSide = totalSpaces / 2 spacesString = "%\(spacesOnEachSide)s" let colLineText = String(format: spacesString + ct + spacesString, spaceChar.cStringUsingEncoding(NSASCIIStringEncoding), spaceChar.cStringUsingEncoding(NSASCIIStringEncoding)) rowLine += colLineText } } } return rowLine } }
40.299342
196
0.591788
edac5b3193dcaa0cc87eec0ba9078b5f72570d35
2,481
class Socket { private static let singleton = Socket() private static var sioSocket: SIOSocket? private static var isConnected = false static var onReceiveLocation: ((String, Double, Double) -> (Void)) = {_, _, _ in} /// current location static var getCurrentLocation: ((Void) -> (CLLocation?)) = {nil} private init() { SIOSocket.socketWithHost("http://localhost:3000") {socket in // TODO config Socket.sioSocket = socket socket.onConnect = { Socket.onConnect() } socket.onDisconnect = { Socket.isConnected = false } socket.onReconnect = {numberOfAttempts in Socket.onConnect() } socket.on(EventName.Message.rawValue) {args in if let userID = args[0] as? String { if let text = args[1] as? String { MessageReceiver.receiveMessage(userID, text: text) } } } socket.on(EventName.Location.rawValue) {args in if let userID = args[0] as? String { if let latitude = args[1] as? Double { if let longitude = args[2] as? Double { Socket.onReceiveLocation(userID, latitude, longitude) } } } } } } private func noop() { // instance method to be called only to make sure `singleton` is instantiated } private class func onConnect() { singleton.noop() Socket.isConnected = true Socket.sioSocket?.emit(EventName.ID.rawValue, args: [PersistentStorage.getMyself().id]) Socket.updateLocation() } class func updateLocation() { singleton.noop() if Socket.isConnected { if let l = Socket.getCurrentLocation() { Socket.sioSocket?.emit(EventName.Location.rawValue, args: [l.coordinate.latitude, l.coordinate.longitude]) } } } class func sendMessage(neighbor: User, message: Message) { singleton.noop() Socket.sioSocket?.emit(EventName.Message.rawValue, args: [neighbor.id, message.text]) } } enum EventName: String { case ID = "id" case Location = "location" case Message = "message" }
31.405063
122
0.527207
e8308c753355d675507601f4f0a85ed79d9b74c1
475
// // MusicState.swift // ARbusters // // Created by Pedro Carrasco on 11/01/18. // Copyright © 2018 Pedro Carrasco. All rights reserved. // import Foundation // MARK: - MusicAction enum MusicAction { case start case stop } // MARK: - MusicAction enum MusicVolumeAction { case mute case unmute } extension MusicVolumeAction { func invert() -> MusicVolumeAction { if self == .mute { return .unmute } else { return .mute } } }
15.322581
57
0.637895
fcd47bc962fd989293552bef0db12c17b200d504
293
// // Thread.swift // Gorge // // Created by Joey on 05/02/2017. // Copyright © 2017 Joey. All rights reserved. // import Foundation public func delay(_ delay: Double, closure: @escaping () -> ()) { DispatchQueue.main.asyncAfter(deadline: .now() + delay) { closure() } }
18.3125
65
0.617747
9b6743f6867af497c6776e44ae7e2ce4b1da6695
1,798
// MIT license. Copyright (c) 2019 SwiftyFORM. All rights reserved. import Foundation import XCTest @testable import SwiftyFORM class PrecisionSliderTests: XCTestCase { func format0(_ value: Int) -> String { return PrecisionSliderCellFormatter.format(value: value, decimalPlaces: 0, prefix: "", suffix: "") } func format1(_ value: Int) -> String { return PrecisionSliderCellFormatter.format(value: value, decimalPlaces: 1, prefix: "", suffix: "") } func format3(_ value: Int) -> String { return PrecisionSliderCellFormatter.format(value: value, decimalPlaces: 3, prefix: "", suffix: "") } func testFormat0() { XCTAssertEqual(format0(0), "0") XCTAssertEqual(format0(1), "1") XCTAssertEqual(format0(-1), "-1") XCTAssertEqual(format0(234), "234") XCTAssertEqual(format0(-234), "-234") XCTAssertEqual(format0(1234), "1234") XCTAssertEqual(format0(-1234), "-1234") XCTAssertEqual(format0(123456), "123456") XCTAssertEqual(format0(-123456), "-123456") } func testFormat1() { XCTAssertEqual(format1(0), "0.0") XCTAssertEqual(format1(1), "0.1") XCTAssertEqual(format1(-1), "-0.1") XCTAssertEqual(format1(23_4), "23.4") XCTAssertEqual(format1(-23_4), "-23.4") XCTAssertEqual(format1(123_4), "123.4") XCTAssertEqual(format1(-123_4), "-123.4") XCTAssertEqual(format1(12345_6), "12345.6") XCTAssertEqual(format1(-12345_6), "-12345.6") } func testFormat3() { XCTAssertEqual(format3(0), "0.000") XCTAssertEqual(format3(1), "0.001") XCTAssertEqual(format3(-1), "-0.001") XCTAssertEqual(format3(234), "0.234") XCTAssertEqual(format3(-234), "-0.234") XCTAssertEqual(format3(1_234), "1.234") XCTAssertEqual(format3(-1_234), "-1.234") XCTAssertEqual(format3(123_456), "123.456") XCTAssertEqual(format3(-123_456), "-123.456") } }
32.690909
106
0.697442
911a874069c6d56b3b82eff3c83e3fa885fb32d1
1,143
// // 🦠 Corona-Warn-App // import Foundation import UIKit import OpenCombine enum HealthCertificateReissuanceError: LocalizedError { case submitFailedError case replaceHealthCertificateError(Error) case noRelation case certificateToReissueMissing case restServiceError(ServiceError<DCCReissuanceResourceError>) var errorDescription: String? { switch self { case .submitFailedError: return "\(AppStrings.HealthCertificate.Reissuance.Errors.tryAgain) (submitFailedError)" case .replaceHealthCertificateError: return "\(AppStrings.HealthCertificate.Reissuance.Errors.tryAgain) (replaceHealthCertificateError)" case .noRelation: return "\(AppStrings.HealthCertificate.Reissuance.Errors.contactSupport) (DCC_RI_NO_RELATION)" case .certificateToReissueMissing: return "\(AppStrings.HealthCertificate.Reissuance.Errors.tryAgain) (certificateToReissueMissing)" case .restServiceError(let serviceError): switch serviceError { case .receivedResourceError(let reissuanceResourceError): return reissuanceResourceError.localizedDescription default: return serviceError.localizedDescription } } } }
30.078947
102
0.810149
69761476649b38908668b46775a807998c171bb3
77,129
//===--- Array.swift ------------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// // // Three generic, mutable array-like types with value semantics. // // - `Array<Element>` is like `ContiguousArray<Element>` when `Element` is not // a reference type or an Objective-C existential. Otherwise, it may use // an `NSArray` bridged from Cocoa for storage. // //===----------------------------------------------------------------------===// /// An ordered, random-access collection. /// /// Arrays are one of the most commonly used data types in an app. You use /// arrays to organize your app's data. Specifically, you use the `Array` type /// to hold elements of a single type, the array's `Element` type. An array /// can store any kind of elements---from integers to strings to classes. /// /// Swift makes it easy to create arrays in your code using an array literal: /// simply surround a comma-separated list of values with square brackets. /// Without any other information, Swift creates an array that includes the /// specified values, automatically inferring the array's `Element` type. For /// example: /// /// // An array of 'Int' elements /// let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15] /// /// // An array of 'String' elements /// let streets = ["Albemarle", "Brandywine", "Chesapeake"] /// /// You can create an empty array by specifying the `Element` type of your /// array in the declaration. For example: /// /// // Shortened forms are preferred /// var emptyDoubles: [Double] = [] /// /// // The full type name is also allowed /// var emptyFloats: Array<Float> = Array() /// /// If you need an array that is preinitialized with a fixed number of default /// values, use the `Array(repeating:count:)` initializer. /// /// var digitCounts = Array(repeating: 0, count: 10) /// print(digitCounts) /// // Prints "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]" /// /// Accessing Array Values /// ====================== /// /// When you need to perform an operation on all of an array's elements, use a /// `for`-`in` loop to iterate through the array's contents. /// /// for street in streets { /// print("I don't live on \(street).") /// } /// // Prints "I don't live on Albemarle." /// // Prints "I don't live on Brandywine." /// // Prints "I don't live on Chesapeake." /// /// Use the `isEmpty` property to check quickly whether an array has any /// elements, or use the `count` property to find the number of elements in /// the array. /// /// if oddNumbers.isEmpty { /// print("I don't know any odd numbers.") /// } else { /// print("I know \(oddNumbers.count) odd numbers.") /// } /// // Prints "I know 8 odd numbers." /// /// Use the `first` and `last` properties for safe access to the value of the /// array's first and last elements. If the array is empty, these properties /// are `nil`. /// /// if let firstElement = oddNumbers.first, let lastElement = oddNumbers.last { /// print(firstElement, lastElement, separator: ", ") /// } /// // Prints "1, 15" /// /// print(emptyDoubles.first, emptyDoubles.last, separator: ", ") /// // Prints "nil, nil" /// /// You can access individual array elements through a subscript. The first /// element of a nonempty array is always at index zero. You can subscript an /// array with any integer from zero up to, but not including, the count of /// the array. Using a negative number or an index equal to or greater than /// `count` triggers a runtime error. For example: /// /// print(oddNumbers[0], oddNumbers[3], separator: ", ") /// // Prints "1, 7" /// /// print(emptyDoubles[0]) /// // Triggers runtime error: Index out of range /// /// Adding and Removing Elements /// ============================ /// /// Suppose you need to store a list of the names of students that are signed /// up for a class you're teaching. During the registration period, you need /// to add and remove names as students add and drop the class. /// /// var students = ["Ben", "Ivy", "Jordell"] /// /// To add single elements to the end of an array, use the `append(_:)` method. /// Add multiple elements at the same time by passing another array or a /// sequence of any kind to the `append(contentsOf:)` method. /// /// students.append("Maxime") /// students.append(contentsOf: ["Shakia", "William"]) /// // ["Ben", "Ivy", "Jordell", "Maxime", "Shakia", "William"] /// /// You can add new elements in the middle of an array by using the /// `insert(_:at:)` method for single elements and by using /// `insert(contentsOf:at:)` to insert multiple elements from another /// collection or array literal. The elements at that index and later indices /// are shifted back to make room. /// /// students.insert("Liam", at: 3) /// // ["Ben", "Ivy", "Jordell", "Liam", "Maxime", "Shakia", "William"] /// /// To remove elements from an array, use the `remove(at:)`, /// `removeSubrange(_:)`, and `removeLast()` methods. /// /// // Ben's family is moving to another state /// students.remove(at: 0) /// // ["Ivy", "Jordell", "Liam", "Maxime", "Shakia", "William"] /// /// // William is signing up for a different class /// students.removeLast() /// // ["Ivy", "Jordell", "Liam", "Maxime", "Shakia"] /// /// You can replace an existing element with a new value by assigning the new /// value to the subscript. /// /// if let i = students.firstIndex(of: "Maxime") { /// students[i] = "Max" /// } /// // ["Ivy", "Jordell", "Liam", "Max", "Shakia"] /// /// Growing the Size of an Array /// ---------------------------- /// /// Every array reserves a specific amount of memory to hold its contents. When /// you add elements to an array and that array begins to exceed its reserved /// capacity, the array allocates a larger region of memory and copies its /// elements into the new storage. The new storage is a multiple of the old /// storage's size. This exponential growth strategy means that appending an /// element happens in constant time, averaging the performance of many append /// operations. Append operations that trigger reallocation have a performance /// cost, but they occur less and less often as the array grows larger. /// /// If you know approximately how many elements you will need to store, use the /// `reserveCapacity(_:)` method before appending to the array to avoid /// intermediate reallocations. Use the `capacity` and `count` properties to /// determine how many more elements the array can store without allocating /// larger storage. /// /// For arrays of most `Element` types, this storage is a contiguous block of /// memory. For arrays with an `Element` type that is a class or `@objc` /// protocol type, this storage can be a contiguous block of memory or an /// instance of `NSArray`. Because any arbitrary subclass of `NSArray` can /// become an `Array`, there are no guarantees about representation or /// efficiency in this case. /// /// Modifying Copies of Arrays /// ========================== /// /// Each array has an independent value that includes the values of all of its /// elements. For simple types such as integers and other structures, this /// means that when you change a value in one array, the value of that element /// does not change in any copies of the array. For example: /// /// var numbers = [1, 2, 3, 4, 5] /// var numbersCopy = numbers /// numbers[0] = 100 /// print(numbers) /// // Prints "[100, 2, 3, 4, 5]" /// print(numbersCopy) /// // Prints "[1, 2, 3, 4, 5]" /// /// If the elements in an array are instances of a class, the semantics are the /// same, though they might appear different at first. In this case, the /// values stored in the array are references to objects that live outside the /// array. If you change a reference to an object in one array, only that /// array has a reference to the new object. However, if two arrays contain /// references to the same object, you can observe changes to that object's /// properties from both arrays. For example: /// /// // An integer type with reference semantics /// class IntegerReference { /// var value = 10 /// } /// var firstIntegers = [IntegerReference(), IntegerReference()] /// var secondIntegers = firstIntegers /// /// // Modifications to an instance are visible from either array /// firstIntegers[0].value = 100 /// print(secondIntegers[0].value) /// // Prints "100" /// /// // Replacements, additions, and removals are still visible /// // only in the modified array /// firstIntegers[0] = IntegerReference() /// print(firstIntegers[0].value) /// // Prints "10" /// print(secondIntegers[0].value) /// // Prints "100" /// /// Arrays, like all variable-size collections in the standard library, use /// copy-on-write optimization. Multiple copies of an array share the same /// storage until you modify one of the copies. When that happens, the array /// being modified replaces its storage with a uniquely owned copy of itself, /// which is then modified in place. Optimizations are sometimes applied that /// can reduce the amount of copying. /// /// This means that if an array is sharing storage with other copies, the first /// mutating operation on that array incurs the cost of copying the array. An /// array that is the sole owner of its storage can perform mutating /// operations in place. /// /// In the example below, a `numbers` array is created along with two copies /// that share the same storage. When the original `numbers` array is /// modified, it makes a unique copy of its storage before making the /// modification. Further modifications to `numbers` are made in place, while /// the two copies continue to share the original storage. /// /// var numbers = [1, 2, 3, 4, 5] /// var firstCopy = numbers /// var secondCopy = numbers /// /// // The storage for 'numbers' is copied here /// numbers[0] = 100 /// numbers[1] = 200 /// numbers[2] = 300 /// // 'numbers' is [100, 200, 300, 4, 5] /// // 'firstCopy' and 'secondCopy' are [1, 2, 3, 4, 5] /// /// Bridging Between Array and NSArray /// ================================== /// /// When you need to access APIs that require data in an `NSArray` instance /// instead of `Array`, use the type-cast operator (`as`) to bridge your /// instance. For bridging to be possible, the `Element` type of your array /// must be a class, an `@objc` protocol (a protocol imported from Objective-C /// or marked with the `@objc` attribute), or a type that bridges to a /// Foundation type. /// /// The following example shows how you can bridge an `Array` instance to /// `NSArray` to use the `write(to:atomically:)` method. In this example, the /// `colors` array can be bridged to `NSArray` because the `colors` array's /// `String` elements bridge to `NSString`. The compiler prevents bridging the /// `moreColors` array, on the other hand, because its `Element` type is /// `Optional<String>`, which does *not* bridge to a Foundation type. /// /// let colors = ["periwinkle", "rose", "moss"] /// let moreColors: [String?] = ["ochre", "pine"] /// /// let url = URL(fileURLWithPath: "names.plist") /// (colors as NSArray).write(to: url, atomically: true) /// // true /// /// (moreColors as NSArray).write(to: url, atomically: true) /// // error: cannot convert value of type '[String?]' to type 'NSArray' /// /// Bridging from `Array` to `NSArray` takes O(1) time and O(1) space if the /// array's elements are already instances of a class or an `@objc` protocol; /// otherwise, it takes O(*n*) time and space. /// /// When the destination array's element type is a class or an `@objc` /// protocol, bridging from `NSArray` to `Array` first calls the `copy(with:)` /// (`- copyWithZone:` in Objective-C) method on the array to get an immutable /// copy and then performs additional Swift bookkeeping work that takes O(1) /// time. For instances of `NSArray` that are already immutable, `copy(with:)` /// usually returns the same array in O(1) time; otherwise, the copying /// performance is unspecified. If `copy(with:)` returns the same array, the /// instances of `NSArray` and `Array` share storage using the same /// copy-on-write optimization that is used when two instances of `Array` /// share storage. /// /// When the destination array's element type is a nonclass type that bridges /// to a Foundation type, bridging from `NSArray` to `Array` performs a /// bridging copy of the elements to contiguous storage in O(*n*) time. For /// example, bridging from `NSArray` to `Array<Int>` performs such a copy. No /// further bridging is required when accessing elements of the `Array` /// instance. /// /// - Note: The `ContiguousArray` and `ArraySlice` types are not bridged; /// instances of those types always have a contiguous block of memory as /// their storage. @frozen public struct Array<Element>: _DestructorSafeContainer { #if _runtime(_ObjC) @usableFromInline internal typealias _Buffer = _ArrayBuffer<Element> #else @usableFromInline internal typealias _Buffer = _ContiguousArrayBuffer<Element> #endif @usableFromInline internal var _buffer: _Buffer /// Initialization from an existing buffer does not have "array.init" /// semantics because the caller may retain an alias to buffer. @inlinable internal init(_buffer: _Buffer) { self._buffer = _buffer } } //===--- private helpers---------------------------------------------------===// extension Array { /// Returns `true` if the array is native and does not need a deferred /// type check. May be hoisted by the optimizer, which means its /// results may be stale by the time they are used if there is an /// inout violation in user code. @inlinable @_semantics("array.props.isNativeTypeChecked") public // @testable func _hoistableIsNativeTypeChecked() -> Bool { return _buffer.arrayPropertyIsNativeTypeChecked } @inlinable @_semantics("array.get_count") internal func _getCount() -> Int { return _buffer.immutableCount } @inlinable @_semantics("array.get_capacity") internal func _getCapacity() -> Int { return _buffer.immutableCapacity } @inlinable @_semantics("array.make_mutable") internal mutating func _makeMutableAndUnique() { if _slowPath(!_buffer.beginCOWMutation()) { _buffer = _buffer._consumeAndCreateNew() } } /// Marks the end of an Array mutation. /// /// After a call to `_endMutation` the buffer must not be mutated until a call /// to `_makeMutableAndUnique`. @_alwaysEmitIntoClient @_semantics("array.end_mutation") internal mutating func _endMutation() { _buffer.endCOWMutation() } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. /// /// This function is not used anymore, but must stay in the library for ABI /// compatibility. @inlinable @inline(__always) internal func _checkSubscript_native(_ index: Int) { _ = _checkSubscript(index, wasNativeTypeChecked: true) } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @_semantics("array.check_subscript") public // @testable func _checkSubscript( _ index: Int, wasNativeTypeChecked: Bool ) -> _DependenceToken { #if _runtime(_ObjC) _buffer._checkInoutAndNativeTypeCheckedBounds( index, wasNativeTypeChecked: wasNativeTypeChecked) #else _buffer._checkValidSubscript(index) #endif return _DependenceToken() } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. /// /// - Precondition: The buffer must be uniquely referenced and native. @_alwaysEmitIntoClient @_semantics("array.check_subscript") internal func _checkSubscript_mutating(_ index: Int) { _buffer._checkValidSubscriptMutating(index) } /// Check that the specified `index` is valid, i.e. `0 ≤ index ≤ count`. @inlinable @_semantics("array.check_index") internal func _checkIndex(_ index: Int) { _precondition(index <= endIndex, "Array index is out of range") _precondition(index >= startIndex, "Negative Array index is out of range") } @_semantics("array.get_element") @inlinable // FIXME(inline-always) @inline(__always) public // @testable func _getElement( _ index: Int, wasNativeTypeChecked: Bool, matchingSubscriptCheck: _DependenceToken ) -> Element { #if _runtime(_ObjC) return _buffer.getElement(index, wasNativeTypeChecked: wasNativeTypeChecked) #else return _buffer.getElement(index) #endif } @inlinable @_semantics("array.get_element_address") internal func _getElementAddress(_ index: Int) -> UnsafeMutablePointer<Element> { return _buffer.firstElementAddress + index } } extension Array: _ArrayProtocol { /// The total number of elements that the array can contain without /// allocating new storage. /// /// Every array reserves a specific amount of memory to hold its contents. /// When you add elements to an array and that array begins to exceed its /// reserved capacity, the array allocates a larger region of memory and /// copies its elements into the new storage. The new storage is a multiple /// of the old storage's size. This exponential growth strategy means that /// appending an element happens in constant time, averaging the performance /// of many append operations. Append operations that trigger reallocation /// have a performance cost, but they occur less and less often as the array /// grows larger. /// /// The following example creates an array of integers from an array literal, /// then appends the elements of another collection. Before appending, the /// array allocates new storage that is large enough store the resulting /// elements. /// /// var numbers = [10, 20, 30, 40, 50] /// // numbers.count == 5 /// // numbers.capacity == 5 /// /// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10)) /// // numbers.count == 10 /// // numbers.capacity == 10 @inlinable public var capacity: Int { return _getCapacity() } /// An object that guarantees the lifetime of this array's elements. @inlinable public // @testable var _owner: AnyObject? { @inlinable // FIXME(inline-always) @inline(__always) get { return _buffer.owner } } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. @inlinable public var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? { @inline(__always) // FIXME(TODO: JIRA): Hack around test failure get { return _buffer.firstElementAddressIfContiguous } } } extension Array: RandomAccessCollection, MutableCollection { /// The index type for arrays, `Int`. public typealias Index = Int /// The type that represents the indices that are valid for subscripting an /// array, in ascending order. public typealias Indices = Range<Int> /// The type that allows iteration over an array's elements. public typealias Iterator = IndexingIterator<Array> /// The position of the first element in a nonempty array. /// /// For an instance of `Array`, `startIndex` is always zero. If the array /// is empty, `startIndex` is equal to `endIndex`. @inlinable public var startIndex: Int { return 0 } /// The array's "past the end" position---that is, the position one greater /// than the last valid subscript argument. /// /// When you need a range that includes the last element of an array, use the /// half-open range operator (`..<`) with `endIndex`. The `..<` operator /// creates a range that doesn't include the upper bound, so it's always /// safe to use with `endIndex`. For example: /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.firstIndex(of: 30) { /// print(numbers[i ..< numbers.endIndex]) /// } /// // Prints "[30, 40, 50]" /// /// If the array is empty, `endIndex` is equal to `startIndex`. @inlinable public var endIndex: Int { @inlinable get { return _getCount() } } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index immediately after `i`. @inlinable public func index(after i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + 1 } /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. @inlinable public func formIndex(after i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i += 1 } /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index immediately before `i`. @inlinable public func index(before i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i - 1 } /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. @inlinable public func formIndex(before i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i -= 1 } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. /// /// let numbers = [10, 20, 30, 40, 50] /// let i = numbers.index(numbers.startIndex, offsetBy: 4) /// print(numbers[i]) /// // Prints "50" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. @inlinable public func index(_ i: Int, offsetBy distance: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + distance } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. The /// operation doesn't require going beyond the limiting `numbers.endIndex` /// value, so it succeeds. /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.index(numbers.startIndex, /// offsetBy: 4, /// limitedBy: numbers.endIndex) { /// print(numbers[i]) /// } /// // Prints "50" /// /// The next example attempts to retrieve an index ten positions from /// `numbers.startIndex`, but fails, because that distance is beyond the /// index passed as `limit`. /// /// let j = numbers.index(numbers.startIndex, /// offsetBy: 10, /// limitedBy: numbers.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, `limit` has no effect if it is less than `i`. /// Likewise, if `distance < 0`, `limit` has no effect if it is greater /// than `i`. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) @inlinable public func index( _ i: Int, offsetBy distance: Int, limitedBy limit: Int ) -> Int? { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. let l = limit - i if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l { return nil } return i + distance } /// Returns the distance between two indices. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. @inlinable public func distance(from start: Int, to end: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return end - start } @inlinable public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } @inlinable public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } /// Accesses the element at the specified position. /// /// The following example uses indexed subscripting to update an array's /// second element. After assigning the new value (`"Butler"`) at a specific /// position, that value is immediately available at that same position. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// streets[1] = "Butler" /// print(streets[1]) /// // Prints "Butler" /// /// - Parameter index: The position of the element to access. `index` must be /// greater than or equal to `startIndex` and less than `endIndex`. /// /// - Complexity: Reading an element from an array is O(1). Writing is O(1) /// unless the array's storage is shared with another array or uses a /// bridged `NSArray` instance as its storage, in which case writing is /// O(*n*), where *n* is the length of the array. @inlinable public subscript(index: Int) -> Element { get { // This call may be hoisted or eliminated by the optimizer. If // there is an inout violation, this value may be stale so needs to be // checked again below. let wasNativeTypeChecked = _hoistableIsNativeTypeChecked() // Make sure the index is in range and wasNativeTypeChecked is // still valid. let token = _checkSubscript( index, wasNativeTypeChecked: wasNativeTypeChecked) return _getElement( index, wasNativeTypeChecked: wasNativeTypeChecked, matchingSubscriptCheck: token) } _modify { _makeMutableAndUnique() // makes the array native, too _checkSubscript_mutating(index) let address = _buffer.mutableFirstElementAddress + index yield &address.pointee _endMutation(); } } /// Accesses a contiguous subrange of the array's elements. /// /// The returned `ArraySlice` instance uses the same indices for the same /// elements as the original array. In particular, that slice, unlike an /// array, may have a nonzero `startIndex` and an `endIndex` that is not /// equal to `count`. Always use the slice's `startIndex` and `endIndex` /// properties instead of assuming that its indices start or end at a /// particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let i = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[i!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of integers. The bounds of the range must be /// valid indices of the array. @inlinable public subscript(bounds: Range<Int>) -> ArraySlice<Element> { get { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) return ArraySlice(_buffer: _buffer[bounds]) } set(rhs) { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) // If the replacement buffer has same identity, and the ranges match, // then this was a pinned in-place modification, nothing further needed. if self[bounds]._buffer.identity != rhs._buffer.identity || bounds != rhs.startIndex..<rhs.endIndex { self.replaceSubrange(bounds, with: rhs) } } } /// The number of elements in the array. @inlinable public var count: Int { return _getCount() } } extension Array: ExpressibleByArrayLiteral { // Optimized implementation for Array /// Creates an array from the given array literal. /// /// Do not call this initializer directly. It is used by the compiler /// when you use an array literal. Instead, create a new array by using an /// array literal as its value. To do this, enclose a comma-separated list of /// values in square brackets. /// /// Here, an array of strings is created from an array literal holding /// only strings. /// /// let ingredients = ["cocoa beans", "sugar", "cocoa butter", "salt"] /// /// - Parameter elements: A variadic list of elements of the new array. @inlinable public init(arrayLiteral elements: Element...) { self = elements } } extension Array: RangeReplaceableCollection { /// Creates a new, empty array. /// /// This is equivalent to initializing with an empty array literal. /// For example: /// /// var emptyArray = Array<Int>() /// print(emptyArray.isEmpty) /// // Prints "true" /// /// emptyArray = [] /// print(emptyArray.isEmpty) /// // Prints "true" @inlinable @_semantics("array.init.empty") public init() { _buffer = _Buffer() } /// Creates an array containing the elements of a sequence. /// /// You can use this initializer to create an array from any other type that /// conforms to the `Sequence` protocol. For example, you might want to /// create an array with the integers from 1 through 7. Use this initializer /// around a range instead of typing all those numbers in an array literal. /// /// let numbers = Array(1...7) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7]" /// /// You can also use this initializer to convert a complex sequence or /// collection type back to an array. For example, the `keys` property of /// a dictionary isn't an array with its own storage, it's a collection /// that maps its elements from the dictionary only when they're /// accessed, saving the time and space needed to allocate an array. If /// you need to pass those keys to a method that takes an array, however, /// use this initializer to convert that list from its type of /// `LazyMapCollection<Dictionary<String, Int>, Int>` to a simple /// `[String]`. /// /// func cacheImages(withNames names: [String]) { /// // custom image loading and caching /// } /// /// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302, /// "Gold": 50, "Cerise": 320] /// let colorNames = Array(namedHues.keys) /// cacheImages(withNames: colorNames) /// /// print(colorNames) /// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]" /// /// - Parameter s: The sequence of elements to turn into an array. @inlinable public init<S: Sequence>(_ s: S) where S.Element == Element { self = Array( _buffer: _Buffer( _buffer: s._copyToContiguousArray()._buffer, shiftedToStartIndex: 0)) } /// Creates a new array containing the specified number of a single, repeated /// value. /// /// Here's an example of creating an array initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Array(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. @inlinable @_semantics("array.init") public init(repeating repeatedValue: Element, count: Int) { var p: UnsafeMutablePointer<Element> (self, p) = Array._allocateUninitialized(count) for _ in 0..<count { p.initialize(to: repeatedValue) p += 1 } _endMutation() } @inline(never) @usableFromInline internal static func _allocateBufferUninitialized( minimumCapacity: Int ) -> _Buffer { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: 0, minimumCapacity: minimumCapacity) return _Buffer(_buffer: newBuffer, shiftedToStartIndex: 0) } /// Construct an Array of `count` uninitialized elements. @inlinable internal init(_uninitializedCount count: Int) { _precondition(count >= 0, "Can't construct Array with count < 0") // Note: Sinking this constructor into an else branch below causes an extra // Retain/Release. _buffer = _Buffer() if count > 0 { // Creating a buffer instead of calling reserveCapacity saves doing an // unnecessary uniqueness check. We disable inlining here to curb code // growth. _buffer = Array._allocateBufferUninitialized(minimumCapacity: count) _buffer.mutableCount = count } // Can't store count here because the buffer might be pointing to the // shared empty array. } /// Entry point for `Array` literal construction; builds and returns /// an Array of `count` uninitialized elements. @inlinable @_semantics("array.uninitialized") internal static func _allocateUninitialized( _ count: Int ) -> (Array, UnsafeMutablePointer<Element>) { let result = Array(_uninitializedCount: count) return (result, result._buffer.firstElementAddress) } /// Returns an Array of `count` uninitialized elements using the /// given `storage`, and a pointer to uninitialized memory for the /// first element. /// /// - Precondition: `storage is _ContiguousArrayStorage`. @inlinable @_semantics("array.uninitialized") internal static func _adoptStorage( _ storage: __owned _ContiguousArrayStorage<Element>, count: Int ) -> (Array, UnsafeMutablePointer<Element>) { let innerBuffer = _ContiguousArrayBuffer<Element>( count: count, storage: storage) return ( Array( _buffer: _Buffer(_buffer: innerBuffer, shiftedToStartIndex: 0)), innerBuffer.firstElementAddress) } /// Entry point for aborting literal construction: deallocates /// an Array containing only uninitialized elements. @inlinable internal mutating func _deallocateUninitialized() { // Set the count to zero and just release as normal. // Somewhat of a hack. _buffer.mutableCount = 0 } //===--- basic mutations ------------------------------------------------===// /// Reserves enough space to store the specified number of elements. /// /// If you are adding a known number of elements to an array, use this method /// to avoid multiple reallocations. This method ensures that the array has /// unique, mutable, contiguous storage, with space allocated for at least /// the requested number of elements. /// /// Calling the `reserveCapacity(_:)` method on an array with bridged storage /// triggers a copy to contiguous storage even if the existing storage /// has room to store `minimumCapacity` elements. /// /// For performance reasons, the size of the newly allocated storage might be /// greater than the requested capacity. Use the array's `capacity` property /// to determine the size of the new storage. /// /// Preserving an Array's Geometric Growth Strategy /// =============================================== /// /// If you implement a custom data structure backed by an array that grows /// dynamically, naively calling the `reserveCapacity(_:)` method can lead /// to worse than expected performance. Arrays need to follow a geometric /// allocation pattern for appending elements to achieve amortized /// constant-time performance. The `Array` type's `append(_:)` and /// `append(contentsOf:)` methods take care of this detail for you, but /// `reserveCapacity(_:)` allocates only as much space as you tell it to /// (padded to a round value), and no more. This avoids over-allocation, but /// can result in insertion not having amortized constant-time performance. /// /// The following code declares `values`, an array of integers, and the /// `addTenQuadratic()` function, which adds ten more values to the `values` /// array on each call. /// /// var values: [Int] = [0, 1, 2, 3] /// /// // Don't use 'reserveCapacity(_:)' like this /// func addTenQuadratic() { /// let newCount = values.count + 10 /// values.reserveCapacity(newCount) /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// The call to `reserveCapacity(_:)` increases the `values` array's capacity /// by exactly 10 elements on each pass through `addTenQuadratic()`, which /// is linear growth. Instead of having constant time when averaged over /// many calls, the function may decay to performance that is linear in /// `values.count`. This is almost certainly not what you want. /// /// In cases like this, the simplest fix is often to simply remove the call /// to `reserveCapacity(_:)`, and let the `append(_:)` method grow the array /// for you. /// /// func addTen() { /// let newCount = values.count + 10 /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// If you need more control over the capacity of your array, implement your /// own geometric growth strategy, passing the size you compute to /// `reserveCapacity(_:)`. /// /// - Parameter minimumCapacity: The requested number of elements to store. /// /// - Complexity: O(*n*), where *n* is the number of elements in the array. @inlinable @_semantics("array.mutate_unknown") public mutating func reserveCapacity(_ minimumCapacity: Int) { _reserveCapacityImpl(minimumCapacity: minimumCapacity, growForAppend: false) _endMutation() } /// Reserves enough space to store `minimumCapacity` elements. /// If a new buffer needs to be allocated and `growForAppend` is true, /// the new capacity is calculated using `_growArrayCapacity`, but at least /// kept at `minimumCapacity`. @_alwaysEmitIntoClient internal mutating func _reserveCapacityImpl( minimumCapacity: Int, growForAppend: Bool ) { let isUnique = _buffer.beginCOWMutation() if _slowPath(!isUnique || _buffer.mutableCapacity < minimumCapacity) { _createNewBuffer(bufferIsUnique: isUnique, minimumCapacity: Swift.max(minimumCapacity, _buffer.count), growForAppend: growForAppend) } _internalInvariant(_buffer.mutableCapacity >= minimumCapacity) _internalInvariant(_buffer.mutableCapacity == 0 || _buffer.isUniquelyReferenced()) } /// Creates a new buffer, replacing the current buffer. /// /// If `bufferIsUnique` is true, the buffer is assumed to be uniquely /// referenced by this array and the elements are moved - instead of copied - /// to the new buffer. /// The `minimumCapacity` is the lower bound for the new capacity. /// If `growForAppend` is true, the new capacity is calculated using /// `_growArrayCapacity`, but at least kept at `minimumCapacity`. @_alwaysEmitIntoClient internal mutating func _createNewBuffer( bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool ) { _internalInvariant(!bufferIsUnique || _buffer.isUniquelyReferenced()) _buffer = _buffer._consumeAndCreateNew(bufferIsUnique: bufferIsUnique, minimumCapacity: minimumCapacity, growForAppend: growForAppend) } /// Copy the contents of the current buffer to a new unique mutable buffer. /// The count of the new buffer is set to `oldCount`, the capacity of the /// new buffer is big enough to hold 'oldCount' + 1 elements. @inline(never) @inlinable // @specializable internal mutating func _copyToNewBuffer(oldCount: Int) { let newCount = oldCount + 1 var newBuffer = _buffer._forceCreateUniqueMutableBuffer( countForNewBuffer: oldCount, minNewCapacity: newCount) _buffer._arrayOutOfPlaceUpdate(&newBuffer, oldCount, 0) } @inlinable @_semantics("array.make_mutable") internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() { if _slowPath(!_buffer.beginCOWMutation()) { _createNewBuffer(bufferIsUnique: false, minimumCapacity: count + 1, growForAppend: true) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _reserveCapacityAssumingUniqueBuffer(oldCount: Int) { // Due to make_mutable hoisting the situation can arise where we hoist // _makeMutableAndUnique out of loop and use it to replace // _makeUniqueAndReserveCapacityIfNotUnique that precedes this call. If the // array was empty _makeMutableAndUnique does not replace the empty array // buffer by a unique buffer (it just replaces it by the empty array // singleton). // This specific case is okay because we will make the buffer unique in this // function because we request a capacity > 0 and therefore _copyToNewBuffer // will be called creating a new buffer. let capacity = _buffer.mutableCapacity _internalInvariant(capacity == 0 || _buffer.isMutableAndUniquelyReferenced()) if _slowPath(oldCount + 1 > capacity) { _createNewBuffer(bufferIsUnique: capacity > 0, minimumCapacity: oldCount + 1, growForAppend: true) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _appendElementAssumeUniqueAndCapacity( _ oldCount: Int, newElement: __owned Element ) { _internalInvariant(_buffer.isMutableAndUniquelyReferenced()) _internalInvariant(_buffer.mutableCapacity >= _buffer.mutableCount + 1) _buffer.mutableCount = oldCount + 1 (_buffer.mutableFirstElementAddress + oldCount).initialize(to: newElement) } /// Adds a new element at the end of the array. /// /// Use this method to append a single element to the end of a mutable array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(100) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// Because arrays increase their allocated capacity using an exponential /// strategy, appending a single element to an array is an O(1) operation /// when averaged over many calls to the `append(_:)` method. When an array /// has additional capacity and is not sharing its storage with another /// instance, appending an element is O(1). When an array needs to /// reallocate storage before appending or its storage is shared with /// another copy, appending is O(*n*), where *n* is the length of the array. /// /// - Parameter newElement: The element to append to the array. /// /// - Complexity: O(1) on average, over many calls to `append(_:)` on the /// same array. @inlinable @_semantics("array.append_element") public mutating func append(_ newElement: __owned Element) { // Separating uniqueness check and capacity check allows hoisting the // uniqueness check out of a loop. _makeUniqueAndReserveCapacityIfNotUnique() let oldCount = _buffer.mutableCount _reserveCapacityAssumingUniqueBuffer(oldCount: oldCount) _appendElementAssumeUniqueAndCapacity(oldCount, newElement: newElement) _endMutation() } /// Adds the elements of a sequence to the end of the array. /// /// Use this method to append the elements of a sequence to the end of this /// array. This example appends the elements of a `Range<Int>` instance /// to an array of integers. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the array. /// /// - Complexity: O(*m*) on average, where *m* is the length of /// `newElements`, over many calls to `append(contentsOf:)` on the same /// array. @inlinable @_semantics("array.append_contentsOf") public mutating func append<S: Sequence>(contentsOf newElements: __owned S) where S.Element == Element { defer { _endMutation() } let newElementsCount = newElements.underestimatedCount _reserveCapacityImpl(minimumCapacity: self.count + newElementsCount, growForAppend: true) let oldCount = _buffer.mutableCount let startNewElements = _buffer.mutableFirstElementAddress + oldCount let buf = UnsafeMutableBufferPointer( start: startNewElements, count: _buffer.mutableCapacity - oldCount) var (remainder,writtenUpTo) = buf.initialize(from: newElements) // trap on underflow from the sequence's underestimate: let writtenCount = buf.distance(from: buf.startIndex, to: writtenUpTo) _precondition(newElementsCount <= writtenCount, "newElements.underestimatedCount was an overestimate") // can't check for overflow as sequences can underestimate // This check prevents a data race writing to _swiftEmptyArrayStorage if writtenCount > 0 { _buffer.mutableCount = _buffer.mutableCount + writtenCount } if _slowPath(writtenUpTo == buf.endIndex) { // A shortcut for appending an Array: If newElements is an Array then it's // guaranteed that buf.initialize(from: newElements) already appended all // elements. It reduces code size, because the following code // can be removed by the optimizer by constant folding this check in a // generic specialization. if S.self == [Element].self { _internalInvariant(remainder.next() == nil) return } // there may be elements that didn't fit in the existing buffer, // append them in slow sequence-only mode var newCount = _buffer.mutableCount var nextItem = remainder.next() while nextItem != nil { _reserveCapacityAssumingUniqueBuffer(oldCount: newCount) let currentCapacity = _buffer.mutableCapacity let base = _buffer.mutableFirstElementAddress // fill while there is another item and spare capacity while let next = nextItem, newCount < currentCapacity { (base + newCount).initialize(to: next) newCount += 1 nextItem = remainder.next() } _buffer.mutableCount = newCount } } } @inlinable @_semantics("array.reserve_capacity_for_append") internal mutating func reserveCapacityForAppend(newElementsCount: Int) { // Ensure uniqueness, mutability, and sufficient storage. Note that // for consistency, we need unique self even if newElements is empty. _reserveCapacityImpl(minimumCapacity: self.count + newElementsCount, growForAppend: true) _endMutation() } @inlinable @_semantics("array.mutate_unknown") public mutating func _customRemoveLast() -> Element? { _makeMutableAndUnique() let newCount = _buffer.mutableCount - 1 _precondition(newCount >= 0, "Can't removeLast from an empty Array") let pointer = (_buffer.mutableFirstElementAddress + newCount) let element = pointer.move() _buffer.mutableCount = newCount _endMutation() return element } /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved up to /// close the gap. /// /// var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]" /// /// - Parameter index: The position of the element to remove. `index` must /// be a valid index of the array. /// - Returns: The element at the specified index. /// /// - Complexity: O(*n*), where *n* is the length of the array. @inlinable @discardableResult @_semantics("array.mutate_unknown") public mutating func remove(at index: Int) -> Element { _makeMutableAndUnique() let currentCount = _buffer.mutableCount _precondition(index < currentCount, "Index out of range") _precondition(index >= 0, "Index out of range") let newCount = currentCount - 1 let pointer = (_buffer.mutableFirstElementAddress + index) let result = pointer.move() pointer.moveInitialize(from: pointer + 1, count: newCount - index) _buffer.mutableCount = newCount _endMutation() return result } /// Inserts a new element at the specified position. /// /// The new element is inserted before the element currently at the specified /// index. If you pass the array's `endIndex` property as the `index` /// parameter, the new element is appended to the array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// /// print(numbers) /// // Prints "[1, 2, 3, 100, 4, 5, 200]" /// /// - Parameter newElement: The new element to insert into the array. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index of the array or equal to its `endIndex` /// property. /// /// - Complexity: O(*n*), where *n* is the length of the array. If /// `i == endIndex`, this method is equivalent to `append(_:)`. @inlinable public mutating func insert(_ newElement: __owned Element, at i: Int) { _checkIndex(i) self.replaceSubrange(i..<i, with: CollectionOfOne(newElement)) } /// Removes all elements from the array. /// /// - Parameter keepCapacity: Pass `true` to keep the existing capacity of /// the array after removing its elements. The default value is /// `false`. /// /// - Complexity: O(*n*), where *n* is the length of the array. @inlinable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { if !keepCapacity { _buffer = _Buffer() } else { self.replaceSubrange(indices, with: EmptyCollection()) } } //===--- algorithms -----------------------------------------------------===// @inlinable @available(*, deprecated, renamed: "withContiguousMutableStorageIfAvailable") public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeMutableBufferPointer { (bufferPointer) -> R in return try body(&bufferPointer) } } @inlinable public mutating func withContiguousMutableStorageIfAvailable<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeMutableBufferPointer { (bufferPointer) -> R in return try body(&bufferPointer) } } @inlinable public func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeBufferPointer { (bufferPointer) -> R in return try body(bufferPointer) } } @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { if let n = _buffer.requestNativeBuffer() { return ContiguousArray(_buffer: n) } return _copyCollectionToContiguousArray(self) } } // Implementations of + and += for same-type arrays. This combined // with the operator declarations for these operators designating this // type as a place to prefer this operator help the expression type // checker speed up cases where there is a large number of uses of the // operator in the same expression. extension Array { @inlinable public static func + (lhs: Array, rhs: Array) -> Array { var lhs = lhs lhs.append(contentsOf: rhs) return lhs } @inlinable public static func += (lhs: inout Array, rhs: Array) { lhs.append(contentsOf: rhs) } } extension Array: CustomReflectable { /// A mirror that reflects the array. public var customMirror: Mirror { return Mirror( self, unlabeledChildren: self, displayStyle: .collection) } } extension Array: CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of the array and its elements. public var description: String { return _makeCollectionDescription() } /// A textual representation of the array and its elements, suitable for /// debugging. public var debugDescription: String { // Always show sugared representation for Arrays. return _makeCollectionDescription() } } extension Array { @usableFromInline @_transparent internal func _cPointerArgs() -> (AnyObject?, UnsafeRawPointer?) { let p = _baseAddressIfContiguous if _fastPath(p != nil || isEmpty) { return (_owner, UnsafeRawPointer(p)) } let n = ContiguousArray(self._buffer)._buffer return (n.owner, UnsafeRawPointer(n.firstElementAddress)) } } extension Array { /// Implementation for Array(unsafeUninitializedCapacity:initializingWith:) /// and ContiguousArray(unsafeUninitializedCapacity:initializingWith:) @inlinable internal init( _unsafeUninitializedCapacity: Int, initializingWith initializer: ( _ buffer: inout UnsafeMutableBufferPointer<Element>, _ initializedCount: inout Int) throws -> Void ) rethrows { var firstElementAddress: UnsafeMutablePointer<Element> (self, firstElementAddress) = Array._allocateUninitialized(_unsafeUninitializedCapacity) var initializedCount = 0 var buffer = UnsafeMutableBufferPointer<Element>( start: firstElementAddress, count: _unsafeUninitializedCapacity) defer { // Update self.count even if initializer throws an error. _precondition( initializedCount <= _unsafeUninitializedCapacity, "Initialized count set to greater than specified capacity." ) _precondition( buffer.baseAddress == firstElementAddress, "Can't reassign buffer in Array(unsafeUninitializedCapacity:initializingWith:)" ) self._buffer.mutableCount = initializedCount _endMutation() } try initializer(&buffer, &initializedCount) } /// Creates an array with the specified capacity, then calls the given /// closure with a buffer covering the array's uninitialized memory. /// /// Inside the closure, set the `initializedCount` parameter to the number of /// elements that are initialized by the closure. The memory in the range /// `buffer[0..<initializedCount]` must be initialized at the end of the /// closure's execution, and the memory in the range /// `buffer[initializedCount...]` must be uninitialized. This postcondition /// must hold even if the `initializer` closure throws an error. /// /// - Note: While the resulting array may have a capacity larger than the /// requested amount, the buffer passed to the closure will cover exactly /// the requested number of elements. /// /// - Parameters: /// - unsafeUninitializedCapacity: The number of elements to allocate /// space for in the new array. /// - initializer: A closure that initializes elements and sets the count /// of the new array. /// - Parameters: /// - buffer: A buffer covering uninitialized memory with room for the /// specified number of elements. /// - initializedCount: The count of initialized elements in the array, /// which begins as zero. Set `initializedCount` to the number of /// elements you initialize. @_alwaysEmitIntoClient @inlinable public init( unsafeUninitializedCapacity: Int, initializingWith initializer: ( _ buffer: inout UnsafeMutableBufferPointer<Element>, _ initializedCount: inout Int) throws -> Void ) rethrows { self = try Array( _unsafeUninitializedCapacity: unsafeUninitializedCapacity, initializingWith: initializer) } /// Calls a closure with a pointer to the array's contiguous storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how you can iterate over the contents of the /// buffer pointer: /// /// let numbers = [1, 2, 3, 4, 5] /// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in /// var result = 0 /// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) { /// result += buffer[i] /// } /// return result /// } /// // 'sum' == 9 /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the /// pointer for later use. /// /// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that /// points to the contiguous storage for the array. If no such storage exists, it is created. If /// `body` has a return value, that value is also used as the return value /// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is /// valid only for the duration of the method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { return try _buffer.withUnsafeBufferPointer(body) } /// Calls the given closure with a pointer to the array's mutable contiguous /// storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how modifying the contents of the /// `UnsafeMutableBufferPointer` argument to `body` alters the contents of /// the array: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.withUnsafeMutableBufferPointer { buffer in /// for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) { /// buffer.swapAt(i, i + 1) /// } /// } /// print(numbers) /// // Prints "[2, 1, 4, 3, 5]" /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeMutableBufferPointer(_:)`. Do not store or /// return the pointer for later use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableBufferPointer` /// parameter that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBufferPointer(_:)` /// method. The pointer argument is valid only for the duration of the /// method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @_semantics("array.withUnsafeMutableBufferPointer") @inlinable // FIXME(inline-always) @inline(__always) // Performance: This method should get inlined into the // caller such that we can combine the partial apply with the apply in this // function saving on allocating a closure context. This becomes unnecessary // once we allocate noescape closures on the stack. public mutating func withUnsafeMutableBufferPointer<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { _makeMutableAndUnique() let count = _buffer.mutableCount // Ensure that body can't invalidate the storage or its bounds by // moving self into a temporary working array. // NOTE: The stack promotion optimization that keys of the // "array.withUnsafeMutableBufferPointer" semantics annotation relies on the // array buffer not being able to escape in the closure. It can do this // because we swap the array buffer in self with an empty buffer here. Any // escape via the address of self in the closure will therefore escape the // empty array. var work = Array() (work, self) = (self, work) // Create an UnsafeBufferPointer over work that we can pass to body let pointer = work._buffer.mutableFirstElementAddress var inoutBufferPointer = UnsafeMutableBufferPointer( start: pointer, count: count) // Put the working array back before returning. defer { _precondition( inoutBufferPointer.baseAddress == pointer && inoutBufferPointer.count == count, "Array withUnsafeMutableBufferPointer: replacing the buffer is not allowed") (work, self) = (self, work) _endMutation() } // Invoke the body. return try body(&inoutBufferPointer) } @inlinable public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { guard !self.isEmpty else { return (makeIterator(),buffer.startIndex) } // It is not OK for there to be no pointer/not enough space, as this is // a precondition and Array never lies about its count. guard var p = buffer.baseAddress else { _preconditionFailure("Attempt to copy contents into nil buffer pointer") } _precondition(self.count <= buffer.count, "Insufficient space allocated to copy array contents") if let s = _baseAddressIfContiguous { p.initialize(from: s, count: self.count) // Need a _fixLifetime bracketing the _baseAddressIfContiguous getter // and all uses of the pointer it returns: _fixLifetime(self._owner) } else { for x in self { p.initialize(to: x) p += 1 } } var it = IndexingIterator(_elements: self) it._position = endIndex return (it,buffer.index(buffer.startIndex, offsetBy: self.count)) } } extension Array { /// Replaces a range of elements with the elements in the specified /// collection. /// /// This method has the effect of removing the specified range of elements /// from the array and inserting the new elements at the same location. The /// number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of an array of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The start and end of /// a subrange must be valid indices of the array. /// - newElements: The new elements to add to the array. /// /// - Complexity: O(*n* + *m*), where *n* is length of the array and /// *m* is the length of `newElements`. If the call to this method simply /// appends the contents of `newElements` to the array, this method is /// equivalent to `append(contentsOf:)`. @inlinable @_semantics("array.mutate_unknown") public mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newElements: __owned C ) where C: Collection, C.Element == Element { _precondition(subrange.lowerBound >= self._buffer.startIndex, "Array replace: subrange start is negative") _precondition(subrange.upperBound <= _buffer.endIndex, "Array replace: subrange extends past the end") let eraseCount = subrange.count let insertCount = newElements.count let growth = insertCount - eraseCount _reserveCapacityImpl(minimumCapacity: self.count + growth, growForAppend: true) _buffer.replaceSubrange(subrange, with: insertCount, elementsOf: newElements) _endMutation() } } extension Array: Equatable where Element: Equatable { /// Returns a Boolean value indicating whether two arrays contain the same /// elements in the same order. /// /// You can use the equal-to operator (`==`) to compare any two arrays /// that store the same, `Equatable`-conforming element type. /// /// - Parameters: /// - lhs: An array to compare. /// - rhs: Another array to compare. @inlinable public static func ==(lhs: Array<Element>, rhs: Array<Element>) -> Bool { let lhsCount = lhs.count if lhsCount != rhs.count { return false } // Test referential equality. if lhsCount == 0 || lhs._buffer.identity == rhs._buffer.identity { return true } _internalInvariant(lhs.startIndex == 0 && rhs.startIndex == 0) _internalInvariant(lhs.endIndex == lhsCount && rhs.endIndex == lhsCount) // We know that lhs.count == rhs.count, compare element wise. for idx in 0..<lhsCount { if lhs[idx] != rhs[idx] { return false } } return true } } extension Array: Hashable where Element: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(count) // discriminator for element in self { hasher.combine(element) } } } extension Array { /// Calls the given closure with a pointer to the underlying bytes of the /// array's mutable contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies bytes from the `byteValues` array into /// `numbers`, an array of `Int32`: /// /// var numbers: [Int32] = [0, 0] /// var byteValues: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00] /// /// numbers.withUnsafeMutableBytes { destBytes in /// byteValues.withUnsafeBytes { srcBytes in /// destBytes.copyBytes(from: srcBytes) /// } /// } /// // numbers == [1, 2] /// /// - Note: This example shows the behavior on a little-endian platform. /// /// The pointer passed as an argument to `body` is valid only for the /// lifetime of the closure. Do not escape it from the closure for later /// use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableRawBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableRawBufferPointer` /// parameter that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBytes(_:)` method. /// The argument is valid only for the duration of the closure's /// execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public mutating func withUnsafeMutableBytes<R>( _ body: (UnsafeMutableRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeMutableBufferPointer { return try body(UnsafeMutableRawBufferPointer($0)) } } /// Calls the given closure with a pointer to the underlying bytes of the /// array's contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies the bytes of the `numbers` array into a /// buffer of `UInt8`: /// /// var numbers: [Int32] = [1, 2, 3] /// var byteBuffer: [UInt8] = [] /// numbers.withUnsafeBytes { /// byteBuffer.append(contentsOf: $0) /// } /// // byteBuffer == [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0] /// /// - Note: This example shows the behavior on a little-endian platform. /// /// - Parameter body: A closure with an `UnsafeRawBufferPointer` parameter /// that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeBytes(_:)` method. The /// argument is valid only for the duration of the closure's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeBufferPointer { try body(UnsafeRawBufferPointer($0)) } } } #if _runtime(_ObjC) // We isolate the bridging of the Cocoa Array -> Swift Array here so that // in the future, we can eagerly bridge the Cocoa array. We need this function // to do the bridging in an ABI safe way. Even though this looks useless, // DO NOT DELETE! @usableFromInline internal func _bridgeCocoaArray<T>(_ _immutableCocoaArray: AnyObject) -> Array<T> { return Array(_buffer: _ArrayBuffer(nsArray: _immutableCocoaArray)) } extension Array { @inlinable public // @SPI(Foundation) func _bridgeToObjectiveCImpl() -> AnyObject { return _buffer._asCocoaArray() } /// Tries to downcast the source `NSArray` as our native buffer type. /// If it succeeds, creates a new `Array` around it and returns that. /// Returns `nil` otherwise. // Note: this function exists here so that Foundation doesn't have // to know Array's implementation details. @inlinable public static func _bridgeFromObjectiveCAdoptingNativeStorageOf( _ source: AnyObject ) -> Array? { // If source is deferred, we indirect to get its native storage let maybeNative = (source as? __SwiftDeferredNSArray)?._nativeStorage ?? source return (maybeNative as? _ContiguousArrayStorage<Element>).map { Array(_ContiguousArrayBuffer($0)) } } /// Private initializer used for bridging. /// /// Only use this initializer when both conditions are true: /// /// * it is statically known that the given `NSArray` is immutable; /// * `Element` is bridged verbatim to Objective-C (i.e., /// is a reference type). @inlinable public init(_immutableCocoaArray: AnyObject) { self = _bridgeCocoaArray(_immutableCocoaArray) } } #endif extension Array: _HasCustomAnyHashableRepresentation where Element: Hashable { public __consuming func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(_box: _ArrayAnyHashableBox(self)) } } internal protocol _ArrayAnyHashableProtocol: _AnyHashableBox { var count: Int { get } subscript(index: Int) -> AnyHashable { get } } internal struct _ArrayAnyHashableBox<Element: Hashable> : _ArrayAnyHashableProtocol { internal let _value: [Element] internal init(_ value: [Element]) { self._value = value } internal var _base: Any { return _value } internal var count: Int { return _value.count } internal subscript(index: Int) -> AnyHashable { return _value[index] as AnyHashable } func _isEqual(to other: _AnyHashableBox) -> Bool? { guard let other = other as? _ArrayAnyHashableProtocol else { return nil } guard _value.count == other.count else { return false } for i in 0 ..< _value.count { if self[i] != other[i] { return false } } return true } var _hashValue: Int { var hasher = Hasher() _hash(into: &hasher) return hasher.finalize() } func _hash(into hasher: inout Hasher) { hasher.combine(_value.count) // discriminator for i in 0 ..< _value.count { hasher.combine(self[i]) } } func _rawHashValue(_seed: Int) -> Int { var hasher = Hasher(_seed: _seed) self._hash(into: &hasher) return hasher._finalize() } internal func _unbox<T: Hashable>() -> T? { return _value as? T } internal func _downCastConditional<T>( into result: UnsafeMutablePointer<T> ) -> Bool { guard let value = _value as? T else { return false } result.initialize(to: value) return true } } extension Array: ConcurrentValue, UnsafeConcurrentValue where Element: ConcurrentValue { }
38.758291
101
0.667233
090074bfdd8d12aa33e43d899cab4bea045a27a2
10,841
// // SimplicialComplexOperations.swift // SwiftyAlgebra // // Created by Taketo Sano on 2017/11/06. // Copyright © 2017年 Taketo Sano. All rights reserved. // import Foundation import SwiftyAlgebra // Operations public extension SimplicialComplex { public func star(_ v: Vertex) -> SimplicialComplex { return star( Simplex(v) ) } public func star(_ s: Simplex) -> SimplicialComplex { return SimplicialComplex(name: "St\(s)", cells: maximalCells.filter{ $0.contains(s) } ) } public func link(_ v: Vertex) -> SimplicialComplex { return (star(v) - v).named("Lk\(v)") } public func link(_ s: Simplex) -> SimplicialComplex { let cells = star(s).maximalCells.flatMap { s1 in SimplicialComplex.subtract(s1, s, strict: true) } return SimplicialComplex(name: "Lk\(s)", cells: cells, filterMaximalCells: true) } public var boundary: SimplicialComplex { let set = Set( maximalCells.flatMap{ $0.faces() } ) .filter { s in let st = star(s) let lk = st.link(s) return !st.isOrientable(relativeTo: lk) } return SimplicialComplex(name: "∂\(name)", cells: set) } public var boundaryVertices: [Vertex] { return vertices.filter { v in !link(v).isOrientable } } public func identifyVertices(_ pairs: [(Vertex, Vertex)]) -> SimplicialComplex { let table = Dictionary(pairs: pairs) return identifyVertices(table) } public func identifyVertices(_ table: [Vertex : Vertex]) -> SimplicialComplex { let map = SimplicialMap { v in table[v] ?? v } return map.image(of: self) } public static func +(K1: SimplicialComplex, K2: SimplicialComplex) -> SimplicialComplex { let cells = (K1.maximalCells + K2.maximalCells).unique() return SimplicialComplex(name: "\(K1) + \(K2)", cells: cells) } // Returns maximal faces of s1 that are not contained in s2. // If strict, no intersections are allowed. public static func subtract(_ s1: Simplex, _ s2: Simplex, strict: Bool = false) -> [Simplex] { let n = s1 ∩ s2 if (!strict && n.dim < s2.dim) || (strict && n.isEmpty) { return [s1] } else if s2.contains(s1) { return [] } else { return s1.faces().flatMap{ t1 in subtract(t1, s2, strict: strict) } } } public static func -(K1: SimplicialComplex, v: Vertex) -> SimplicialComplex { return K1 - Simplex(v) } public static func -(K1: SimplicialComplex, s2: Simplex) -> SimplicialComplex { let cells = K1.maximalCells.flatMap{ s1 in subtract(s1, s2) } return SimplicialComplex(name: "\(K1.name) - \(s2)", cells: cells, filterMaximalCells: true) } public static func -(K1: SimplicialComplex, K2: SimplicialComplex) -> SimplicialComplex { let subtr = K2.maximalCells let cells = K1.maximalCells.flatMap { s1 in subtr.reduce([s1]) { (list, s2) in list.flatMap{ t1 in subtract(t1, s2) } } } return SimplicialComplex(name: "\(K1.name) - \(K2.name)", cells: cells, filterMaximalCells: true) } // product complex public static func ×(K1: SimplicialComplex, K2: SimplicialComplex) -> SimplicialComplex { let pcells = productSimplices(K1.maximalCells, K2.maximalCells) return SimplicialComplex(name: "\(K1.name) × \(K2.name)", cells: pcells) } public static func ×(K1: SimplicialComplex, v2: Vertex) -> SimplicialComplex { let K2 = SimplicialComplex(name: v2.label, cells: Simplex([v2])) return K1 × K2 } public static func ×(v1: Vertex, K2: SimplicialComplex) -> SimplicialComplex { let K1 = SimplicialComplex(name: v1.label, cells: Simplex([v1])) return K1 × K2 } internal static func productSimplices(_ ss: [Simplex], _ ts: [Simplex]) -> [Simplex] { return ss.allCombinations(with: ts).flatMap{ (s, t) in productSimplices(s, t) } } internal static func productSimplices(_ s: Simplex, _ t: Simplex) -> [Simplex] { let (n, m) = (s.dim, t.dim) // generate array of (n + m)-dim product simplices by the zig-zag method. let combis = (n + m).choose(n) let vPairs = combis.map{ c -> [(Vertex, Vertex)] in let start = [(s.vertices[0], t.vertices[0])] var (i, j) = (0, 0) return start + (0 ..< (n + m)).map { k -> (Vertex, Vertex) in if c.contains(k) { defer { i += 1 } } else { defer { j += 1 } } return (s.vertices[i], t.vertices[j]) } } return vPairs.map { list -> Simplex in let vertices = list.map { (v, w) in v × w } return Simplex(vertices) } } public func pow(_ n: Int) -> SimplicialComplex { let cells = maximalCells let pcells = (1 ..< n).reduce(cells) { (pow, _) -> [Simplex] in SimplicialComplex.productSimplices(pow, cells) } return SimplicialComplex(name: "\(name)^\(n)", cells: pcells) } public static func /(K1: SimplicialComplex, K2: SimplicialComplex) -> SimplicialComplex { let vs = Set(K2.vertices) let v0 = vs.anyElement! let map = SimplicialMap { v in vs.contains(v) ? v0 : v } return map.image(of: K1).named("\(K1.name) / \(K2.name)") } public static func ∩(K1: SimplicialComplex, K2: SimplicialComplex) -> SimplicialComplex { let cells = K1.maximalCells.flatMap { s -> [Simplex] in K2.maximalCells.flatMap{ t -> Simplex? in let x = s ∩ t return (x.dim >= 0) ? x : nil } }.unique() return SimplicialComplex(name: "\(K1.name) ∩ \(K2.name)", cells: cells, filterMaximalCells: true) } public static func ∨(K1: SimplicialComplex, K2: SimplicialComplex) -> SimplicialComplex { let (v1, v2) = (K1.vertices[0], K2.vertices[0]) let K = K1 + K2 let map = SimplicialMap([v2 : v1]) return map.image(of: K).named("\(K1.name) ∨ \(K2.name)") } public static func ∧(K1: SimplicialComplex, K2: SimplicialComplex) -> SimplicialComplex { let (v1, v2) = (K1.vertices[0], K2.vertices[0]) return (K1 × K2) / ( (K1 × v2) ∨ (v1 × K2) ) } public func cone(intervalVertices n: Int = 2) -> SimplicialComplex { let K = self let I = SimplicialComplex.interval(vertices: n) return ( (K × I) / (K × I.vertices[0]) ).named("C(\(K.name))") } public func suspension(intervalVertices n: Int = 3) -> SimplicialComplex { let K = self let I = SimplicialComplex.interval(vertices: n) return ( (K × I) / (K × I.vertices[0]) / (K × I.vertices[n - 1]) ).named("S(\(K.name))") } public func connectedSum(with K2: SimplicialComplex) -> SimplicialComplex { let K1 = self assert(K1.dim == K2.dim) let (s1, s2) = (K1.cells(ofDim: K1.dim).anyElement!, K2.cells(ofDim: K1.dim).anyElement!) return ((K1 + K2) - s1 - s2).identifyVertices(s1.vertices.enumerated().map{ (i, v) in (v, s2.vertices[i])}) } public var barycentricSubdivision: SimplicialComplex { return _barycentricSubdivision().0 } internal func _barycentricSubdivision() -> (SimplicialComplex, s2b: [Simplex: Vertex], b2s: [Vertex: Simplex]) { var bcells = Set<Simplex>() var b2s: [Vertex: Simplex] = [:] var s2b: [Simplex: Vertex] = [:] func generate(cells: [Simplex], barycenters: [Vertex]) { let s = cells.last! let v = s2b[s] ?? { let v = (s.dim > 0) ? Vertex(prefix: "b") : s.vertices.first! b2s[v] = s s2b[s] = v return v }() if s.dim > 0 { for t in s.faces() { generate(cells: cells + [t], barycenters: barycenters + [v]) } } else { let bcell = Simplex(barycenters + [v]) bcells.insert(bcell) } } for s in self.maximalCells { generate(cells: [s], barycenters: []) } return (SimplicialComplex(name: "Sd(\(name))", cells: bcells), s2b, b2s) } public var dualComplex: CellularComplex? { if isOrientable { return nil } let (K, n) = (self, dim) let (SdK, s2b, b2s) = K._barycentricSubdivision() var cellsList = [[CellularCell]]() var s2d = [Simplex : CellularCell]() var d2s = [CellularCell : Simplex]() for i in K.validDims.reversed() { let bcells = SdK.cells(ofDim: n - i) let dcells = K.cells(ofDim: i).map { s -> CellularCell in let chain: SimplicialChain<𝐙> = { let b = s2b[s]! let star = SimplicialComplex(cells: bcells.filter{ (bcell) in bcell.contains(b) && bcell.vertices.forAll{ b2s[$0]!.contains(s) } }) let link = star - b return star.orientationCycle(relativeTo: link)! }() let z = chain.boundary() let boundary = CellularChain( K.cofaces(ofCell: s).map{ t -> (CellularCell, 𝐙) in let dcell = s2d[t]! let t0 = dcell.simplices.basis[0] // take any simplex to detect orientation let e = (dcell.simplices[t0] == z[t0]) ? 1 : -1 return (dcell, e) }) let d = CellularCell(chain, boundary) s2d[s] = d d2s[d] = s return d } cellsList.append(dcells) } return CellularComplex(SdK, cellsList) } } public extension Vertex { public var asComplex: SimplicialComplex { return Simplex(self).asComplex.named(label) } public func join(_ K: SimplicialComplex) -> SimplicialComplex { let cells = K.maximalCells.map{ s in self.join(s) } return SimplicialComplex(name: "\(self) * \(K.name)", cells: cells) } } public extension Simplex { public var asComplex: SimplicialComplex { return SimplicialComplex(name: "△^\(dim)", cells: self) } }
36.501684
116
0.53805
50ba0e9701d95dea0ac15e8aa60ce9698aebdb07
3,504
// // KeychainManager.swift // Catch Bat // // Created by 梁怀宇 on 2020/4/4. // Copyright © 2020 lhy. All rights reserved. // import Foundation import Cocoa class KeychainManager: NSObject { // TODO: 创建查询条件 class func createQuaryMutableDictionary(identifier:String)->NSMutableDictionary{ // 创建一个条件字典 let keychainQuaryMutableDictionary = NSMutableDictionary.init(capacity: 0) // 设置条件存储的类型 keychainQuaryMutableDictionary.setValue(kSecClassInternetPassword/*kSecClassGenericPassword*/, forKey: kSecClass as String) // 设置存储数据的标记 keychainQuaryMutableDictionary.setValue(identifier, forKey: kSecAttrService as String) keychainQuaryMutableDictionary.setValue(identifier, forKey: kSecAttrAccount as String) // 设置数据访问属性 keychainQuaryMutableDictionary.setValue(kSecAttrAccessibleAfterFirstUnlock, forKey: kSecAttrAccessible as String) // 返回创建条件字典 return keychainQuaryMutableDictionary } // TODO: 存储数据 class func keyChainSaveData(data:Any ,withIdentifier identifier:String)->Bool { // 获取存储数据的条件 let keyChainSaveMutableDictionary = self.createQuaryMutableDictionary(identifier: identifier) // 删除旧的存储数据 SecItemDelete(keyChainSaveMutableDictionary) // 设置数据 keyChainSaveMutableDictionary.setValue(NSKeyedArchiver.archivedData(withRootObject: data), forKey: kSecValueData as String) // 进行存储数据 let saveState = SecItemAdd(keyChainSaveMutableDictionary, nil) if saveState == noErr { return true } return false } // TODO: 更新数据 class func keyChainUpdata(data:Any ,withIdentifier identifier:String)->Bool { // 获取更新的条件 let keyChainUpdataMutableDictionary = self.createQuaryMutableDictionary(identifier: identifier) // 创建数据存储字典 let updataMutableDictionary = NSMutableDictionary.init(capacity: 0) // 设置数据 updataMutableDictionary.setValue(NSKeyedArchiver.archivedData(withRootObject: data), forKey: kSecValueData as String) // 更新数据 let updataStatus = SecItemUpdate(keyChainUpdataMutableDictionary, updataMutableDictionary) if updataStatus == noErr { return true } return false } // TODO: 获取数据 class func keyChainReadData(identifier:String)-> Any { var idObject:Any? // 获取查询条件 let keyChainReadmutableDictionary = self.createQuaryMutableDictionary(identifier: identifier) // 提供查询数据的两个必要参数 keyChainReadmutableDictionary.setValue(kCFBooleanTrue, forKey: kSecReturnData as String) keyChainReadmutableDictionary.setValue(kSecMatchLimitOne, forKey: kSecMatchLimit as String) // 创建获取数据的引用 var queryResult: AnyObject? // 通过查询是否存储在数据 let readStatus = withUnsafeMutablePointer(to: &queryResult) { SecItemCopyMatching(keyChainReadmutableDictionary, UnsafeMutablePointer($0))} if readStatus == errSecSuccess { if let data = queryResult as! NSData? { idObject = NSKeyedUnarchiver.unarchiveObject(with: data as Data) as Any } } return idObject as Any } // TODO: 删除数据 class func keyChianDelete(identifier:String)->Void{ // 获取删除的条件 let keyChainDeleteMutableDictionary = self.createQuaryMutableDictionary(identifier: identifier) // 删除数据 SecItemDelete(keyChainDeleteMutableDictionary) } }
38.505495
147
0.69492
69c3e0ce3fc7c3a237552a6d6e14a65d86be407f
2,389
// swift-tools-version:5.5 // In order to support users running on the latest Xcodes, please ensure that // [email protected] is kept in sync with this file. /* This source file is part of the Swift.org open source project Copyright (c) 2021 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 Swift project authors */ import PackageDescription import class Foundation.ProcessInfo let cmarkPackageName = ProcessInfo.processInfo.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil ? "swift-cmark" : "swift-cmark-gfm" let package = Package( name: "swift-markdown", products: [ .library( name: "Markdown", targets: ["Markdown"]), ], targets: [ .target( name: "Markdown", dependencies: [ "CAtomic", .product(name: "cmark-gfm", package: cmarkPackageName), .product(name: "cmark-gfm-extensions", package: cmarkPackageName), ]), .executableTarget( name: "markdown-tool", dependencies: [ "Markdown", .product(name: "ArgumentParser", package: "swift-argument-parser") ]), .testTarget( name: "MarkdownTests", dependencies: ["Markdown"], resources: [.process("Visitors/Everything.md")]), .target(name: "CAtomic"), ] ) // If the `SWIFTCI_USE_LOCAL_DEPS` environment variable is set, // we're building in the Swift.org CI system alongside other projects in the Swift toolchain and // we can depend on local versions of our dependencies instead of fetching them remotely. if ProcessInfo.processInfo.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil { // Building standalone, so fetch all dependencies remotely. package.dependencies += [ .package(url: "https://github.com/apple/swift-cmark.git", .branch("gfm")), .package(url: "https://github.com/apple/swift-argument-parser", .upToNextMinor(from: "1.0.1")), ] } else { // Building in the Swift.org CI system, so rely on local versions of dependencies. package.dependencies += [ .package(path: "../swift-cmark-gfm"), .package(path: "../swift-argument-parser"), ] }
37.328125
127
0.642947
e90d6aafcf1866090578e4571817da347a88be5e
1,577
// // String.swift // zScanner // // Created by Jakub Skořepa on 29/06/2019. // Copyright © 2019 Institut klinické a experimentální medicíny. All rights reserved. // import Foundation extension String { var localized: String { return localized(withComment: "") } func localized(withComment comment: String) -> String { return NSLocalizedString(self, comment: comment) } var length: Int { return count } subscript (i: Int) -> String { return self[i ..< i + 1] } func substring(fromIndex: Int) -> String { return self[min(fromIndex, length) ..< length] } func substring(toIndex: Int) -> String { return self[0 ..< max(0, toIndex)] } subscript (r: Range<Int>) -> String { let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)), upper: min(length, max(0, r.upperBound)))) let start = index(startIndex, offsetBy: range.lowerBound) let end = index(start, offsetBy: range.upperBound - range.lowerBound) return String(self[start ..< end]) } /* Personal identification number (PIN) before the year 1954 had only 9 digits, but starting 1954, they changed it to 10 */ func isPIN() -> Bool { guard let year = Int(self.prefix(2)) else { return false } let newFormatYear = 54 let oldFormat = 9 let newFormat = 10 return (year < newFormatYear && length == oldFormat) || (year >= newFormatYear && length == newFormat) } }
29.754717
127
0.599873
f7d9cd74cdbc1d53ef20be94955542a751e20671
1,525
import UIKit import JTAppleCalendar class CalendarCell : JTAppleDayCellView { @IBOutlet weak var dateLabel : UILabel! @IBOutlet weak var activityView : CalendarDailyActivityView! @IBOutlet weak var backgroundView: UIView! private let fontSize = CGFloat(14.0) func reset(allowScrollingToDate: Bool) { clipsToBounds = true backgroundColor = UIColor.clear backgroundView.layer.cornerRadius = 0 backgroundView.backgroundColor = UIColor.clear isUserInteractionEnabled = allowScrollingToDate dateLabel.text = "" dateLabel.textColor = UIColor.black dateLabel.font = UIFont.systemFont(ofSize: fontSize) activityView.reset() } func bind(toDate date: Date, isSelected: Bool, allowsScrollingToDate: Bool, dailyActivity: [Activity]?) { reset(allowScrollingToDate: allowsScrollingToDate) dateLabel.text = String(date.day) dateLabel.textColor = UIColor.black activityView.update(dailyActivity: dailyActivity) backgroundView.alpha = 1.0 backgroundView.backgroundColor = UIColor.clear if isSelected { clipsToBounds = true backgroundView.alpha = 0.24 backgroundView.layer.cornerRadius = 14 backgroundView.backgroundColor = Style.Color.gray dateLabel.font = UIFont.systemFont(ofSize: fontSize, weight: UIFontWeightMedium) } } }
30.5
107
0.651803
715567c517ca8ced498ddc659cba294be42a7441
1,376
// // FrameExtensions.swift // WeatherForecast // // Created by giftbot on 13/06/2019. // Copyright © 2019 giftbot. All rights reserved. // import UIKit extension CGRect { static var screenBounds: CGRect { return UIScreen.main.bounds } static func make(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect { return CGRect(x: x, y: y, width: width, height: height) } } extension CGFloat { public static let screenWidth = UIScreen.main.nativeBounds.size.width / UIScreen.main.nativeScale public static let screenHeight = UIScreen.main.nativeBounds.size.height / UIScreen.main.nativeScale } extension UIView { var x: CGFloat { get { return frame.origin.x } set { frame.origin.x = newValue } } var y: CGFloat { get { return frame.origin.y } set { frame.origin.y = newValue } } var width: CGFloat { get { return frame.width } set { frame.size.width = newValue } } var height: CGFloat { get { return frame.height } set { frame.size.height = newValue } } var origin: CGPoint { get { return frame.origin } set { frame.origin = newValue } } var size: CGSize { get { return frame.size } set { frame.size = newValue } } var maxX: CGFloat { return frame.origin.x + frame.size.width } var maxY: CGFloat { return frame.origin.y + frame.size.height } }
24.571429
101
0.659884
2892ea77633632d56c342fef1aa015ab55c62f46
5,136
// // BestSeasonFilter.swift // Canyoneer // // Created by Brice Pollock on 1/8/22. // import Foundation import UIKit import RxSwift struct BestSeasonFilterData { let name: String let options: [SeasonSelection] let isUserInteractionEnabled: Bool } struct SeasonSelection { let name: String let isSelected: Bool } class BestSeasonFilter: UIView { enum Strings { static let all = "All " static let none = "None " } private let masterStackView = UIStackView() private let titleStackView = UIStackView() private let massSelectionButton = RxUIButton() private let firstRow = UIStackView() private let secondRow = UIStackView() private let titleLabel = UILabel() private let bag = DisposeBag() public var selections: [String] { return seasonButtons.filter { return $0.isSelected }.compactMap { return $0.text } } public var seasonButtons: [SeasonView] { let views = firstRow.arrangedSubviews + secondRow.arrangedSubviews return views.compactMap { return $0 as? SeasonView } } init() { super.init(frame: .zero) self.addSubview(self.masterStackView) self.masterStackView.constrain.fillSuperview() self.masterStackView.axis = .vertical self.masterStackView.spacing = .small self.titleLabel.textAlignment = .center self.titleLabel.font = FontBook.Body.emphasis self.addSubview(self.massSelectionButton) self.massSelectionButton.didSelect.subscribeOnNext { () in let isAnySelected = self.selections.count > 0 let shouldHighlightAll = !isAnySelected self.seasonButtons.forEach { $0.chooseSelection(shouldHighlightAll) } }.disposed(by: self.bag) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(with data: BestSeasonFilterData) { self.isUserInteractionEnabled = data.isUserInteractionEnabled self.massSelectionButton.isHidden = !data.isUserInteractionEnabled self.masterStackView.removeAll() self.masterStackView.addArrangedSubview(self.titleStackView) self.titleStackView.removeAll() self.titleStackView.axis = .horizontal self.titleStackView.alignment = .center self.titleStackView.distribution = .equalCentering self.titleStackView.addArrangedSubview(UIView()) self.titleStackView.addArrangedSubview(self.titleLabel) self.titleStackView.addArrangedSubview(UIView()) self.massSelectionButton.constrain.horizontalSpacing(to: self.titleLabel, with: Grid.small) self.massSelectionButton.constrain.height(to: self.titleLabel) self.titleLabel.setContentHuggingPriority(.required, for: .horizontal) self.titleLabel.textAlignment = .center self.titleLabel.text = data.name self.massSelectionButton.configure(text: Strings.none) self.massSelectionButton.contentHorizontalAlignment = .left self.massSelectionButton.didSelect.subscribeOnNext { () in let isAnySelected = self.selections.count > 0 self.massSelectionButton.configure(text: isAnySelected ? Strings.none : Strings.all) }.disposed(by: self.bag) // to collect all button selections so if any is selected we can update our massSelectionButton var buttonSelections = [Observable<Void>]() // show two rows of months because we cannot cramp them all visually into one line let mid = data.options.count / 2 let firstRowData = data.options.prefix(mid) let secondRowData = data.options.dropFirst(mid) self.firstRow.removeAll() firstRow.distribution = .equalSpacing firstRow.alignment = .center firstRowData.forEach { let monthView = SeasonView() monthView.configure(name: $0.name) monthView.chooseSelection($0.isSelected) buttonSelections.append(monthView.didSelect) firstRow.addArrangedSubview(monthView) } self.masterStackView.addArrangedSubview(firstRow) self.secondRow.removeAll() secondRow.distribution = .equalSpacing secondRowData.forEach { let monthView = SeasonView() monthView.configure(name: $0.name) monthView.chooseSelection($0.isSelected) buttonSelections.append(monthView.didSelect) secondRow.addArrangedSubview(monthView) } self.masterStackView.addArrangedSubview(secondRow) // if any button selected then update massSelectionButton Observable.merge(buttonSelections).subscribeOnNext { () in let isAnySelected = self.selections.count > 0 self.massSelectionButton.configure(text: isAnySelected ? Strings.none : Strings.all) }.disposed(by: self.bag) } }
35.666667
103
0.657516
088013efcc95d00d8be662dc3b51e2291f11f8cc
2,189
// // URLQueryItemsDecoderTests.swift // MoreCodableTests // // Created by Tatsuya Tanaka on 20180212. // Copyright © 2018年 tattn. All rights reserved. // import XCTest import MoreCodable class URLQueryItemsDecoderTests: XCTestCase { var decoder = URLQueryItemsDecoder() override func setUp() { super.setUp() decoder = URLQueryItemsDecoder() } override func tearDown() { super.tearDown() } func testDecodeSimpleParameter() throws { struct Parameter: Codable { let string: String let int: Int let double: Double } let params: [URLQueryItem] = [ URLQueryItem(name: "string", value: "abc"), URLQueryItem(name: "int", value: "123"), URLQueryItem(name: "double", value: Double.pi.description) ] let parameter = try decoder.decode(Parameter.self, from: params) XCTAssertEqual(parameter.string, params[0].value) XCTAssertEqual(parameter.int.description, params[1].value) XCTAssertEqual(parameter.double.description, params[2].value) } func testDecodeOptionalParameter() throws { struct Parameter: Codable { let string: String? let int: Int? let double: Double? } let params: [URLQueryItem] = [ URLQueryItem(name: "string", value: "abc"), URLQueryItem(name: "double", value: Double.pi.description) ] let parameter = try decoder.decode(Parameter.self, from: params) XCTAssertEqual(parameter.string, params[0].value) XCTAssertEqual(parameter.int?.description, nil) XCTAssertEqual(parameter.double?.description, params[1].value) } func testDecodeEmptyOptionalParameter() throws { struct Parameter: Codable { let string: String? let int: Int? let double: Double? } let parameter = try decoder.decode(Parameter.self, from: []) XCTAssertEqual(parameter.string, nil) XCTAssertEqual(parameter.int, nil) XCTAssertEqual(parameter.double, nil) } }
29.581081
72
0.608954
1edd77f20030a053c801c1a9d41b595329b43b96
4,684
import Foundation import NetworkExtension import CocoaLumberjackSwift /// The delegate protocol of `NWUDPSocket`. public protocol NWUDPSocketDelegate: class { /** Socket did receive data from remote. - parameter data: The data. - parameter from: The socket the data is read from. */ func didReceive(data: Data, from: NWUDPSocket) func didCancel(socket: NWUDPSocket) } /// The wrapper for NWUDPSession. /// /// - note: This class is thread-safe. public class NWUDPSocket: NSObject { private let session: NWUDPSession private var pendingWriteData: [Data] = [] private var writing = false private let queue: DispatchQueue = QueueFactory.getQueue() private let timer: DispatchSourceTimer private let timeout: Int /// The delegate instance. public weak var delegate: NWUDPSocketDelegate? /// The time when the last activity happens. /// /// Since UDP do not have a "close" semantic, this can be an indicator of timeout. public var lastActive: Date = Date() /** Create a new UDP socket connecting to remote. - parameter host: The host. - parameter port: The port. */ public init?(host: String, port: Int, timeout: Int = Opt.UDPSocketActiveTimeout) { guard let udpsession = RawSocketFactory.TunnelProvider?.createUDPSession(to: NWHostEndpoint(hostname: host, port: "\(port)"), from: nil) else { return nil } session = udpsession self.timeout = timeout timer = DispatchSource.makeTimerSource(queue: queue) super.init() timer.schedule(deadline: DispatchTime.now(), repeating: DispatchTimeInterval.seconds(Opt.UDPSocketActiveCheckInterval), leeway: DispatchTimeInterval.seconds(Opt.UDPSocketActiveCheckInterval)) timer.setEventHandler { [weak self] in self?.queueCall { self?.checkStatus() } } timer.resume() session.addObserver(self, forKeyPath: #keyPath(NWUDPSession.state), options: [.new], context: nil) session.setReadHandler({ [ weak self ] dataArray, error in self?.queueCall { guard let sSelf = self else { return } sSelf.updateActivityTimer() guard error == nil, let dataArray = dataArray else { DDLogError("Error when reading from remote server. \(error?.localizedDescription ?? "Connection reset")") return } for data in dataArray { sSelf.delegate?.didReceive(data: data, from: sSelf) } } }, maxDatagrams: 32) } /** Send data to remote. - parameter data: The data to send. */ public func write(data: Data) { pendingWriteData.append(data) checkWrite() } public func disconnect() { session.cancel() timer.cancel() } public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard keyPath == "state" else { return } switch session.state { case .cancelled: queueCall { self.delegate?.didCancel(socket: self) } case .ready: checkWrite() default: break } } private func checkWrite() { updateActivityTimer() guard session.state == .ready else { return } guard !writing else { return } guard pendingWriteData.count > 0 else { return } writing = true session.writeMultipleDatagrams(self.pendingWriteData) {_ in self.queueCall { self.writing = false self.checkWrite() } } self.pendingWriteData.removeAll(keepingCapacity: true) } private func updateActivityTimer() { lastActive = Date() } private func checkStatus() { if timeout > 0 && Date().timeIntervalSince(lastActive) > TimeInterval(timeout) { disconnect() } } private func queueCall(block: @escaping () -> Void) { queue.async { block() } } deinit { session.removeObserver(self, forKeyPath: #keyPath(NWUDPSession.state)) } }
28.91358
199
0.561913
5d4f4d310e574c6e8209a0be8f343c5e4c022be5
2,339
// // ImoTableViewActions.swift // ImoTableView // // Created by Borinschi Ivan on 12/5/16. // Copyright © 2016 Imodeveloperlab. All rights reserved. // import UIKit public extension ImoTableView { /// Did select row delegate /// /// - Parameters: /// - tableView: UITableView /// - indexPath: IndexPath func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let source = self.cellSourceForIndexPath(indexPath: indexPath) { didSelect(source: source) didSelectCellAtIndexPath(indexPath: indexPath) performSelector(for: source) } } /// Will call didSelectSource closure if didSelectSource is not nil /// /// - Parameter source: CellSource func didSelect(source: ImoTableViewSource) { if let didSelect = self.didSelectSource { DispatchQueue.main.async { didSelect(source) } } } /// Will call didSelectCellAtIndexPath closure if didSelectCellAtIndexPath is not nil /// /// - Parameter indexPath: IndexPath func didSelectCellAtIndexPath(indexPath: IndexPath) { if let action = self.didSelectCellAtIndexPath { action(indexPath) } } /// Perform selector /// /// - Parameter source: ImoTableViewSource func performSelector(for source: ImoTableViewSource) { if let target = source.target { if let selector = source.selector { performSelector(target: target, selector: selector, source: source) } } } /// Perform selector /// /// - Parameters: /// - target: Target /// - selector: Selector /// - source: CellSource func performSelector(target: AnyObject, selector: Selector, source: ImoTableViewSource) { DispatchQueue.main.async { if target.responds(to: selector) { if let object = source.object { _ = target.perform(selector, with: object) } else { _ = target.perform(selector, with: source) } } } } }
27.517647
89
0.552373
20235666c03b9b3326961ec5340bf3428f39e5cd
552
// // AppUIView.swift // fledger-ios // // Created by Robert Conrad on 4/18/15. // Copyright (c) 2015 TwoSpec Inc. All rights reserved. // import UIKit class AppUIView: UIView { override init(frame: CGRect) { super.init(frame: frame) setup() } convenience init() { self.init(frame: CGRectZero) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } internal func setup() { backgroundColor = AppColors.bgMain() } }
17.25
56
0.570652
87e2b75b0541121926ac545969f9b13e9d2fecdb
930
// // SourceEditorCommand.swift // LazyLoad // // Created by 张建宇 on 2019/8/2. // Copyright © 2019 DevOrz. All rights reserved. // import Foundation import XcodeKit enum Command: String { case withMark = "withMark" case withoutMark = "withoutMark" } class SourceEditorCommand: NSObject, XCSourceEditorCommand { // func error(_ message: String) -> NSError { // return NSError(domain: "JYLoayLoad", code: 1, userInfo: [ // NSLocalizedDescriptionKey: NSLocalizedString(message, comment: ""), // ]) // } // // func handleError(message: String,_ completionHandler: @escaping (Error?) -> Void) { // completionHandler(error(message)) // } func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void { Runtime.shared.lazyLoad(invocation) completionHandler(nil) } }
25.833333
124
0.644086
e2fb9c070119d3659f0a3089e5812384249f8389
7,945
import AVFoundation import HaishinKit import UIKit import VideoToolbox extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(rgb: Int) { self.init( red: (rgb >> 16) & 0xFF, green: (rgb >> 8) & 0xFF, blue: rgb & 0xFF ) } } @objc(VideoStream) class VideoStream : CDVPlugin { var rtmpConnection: RTMPConnection? = nil var rtmpStream: RTMPStream? = nil var hkView : HKView? = nil var closeButton: UIButton? = nil var streamName: String = "" var command:CDVInvokedUrlCommand? = nil var maskview : UIView? = nil @objc(echo:) func echo(_ command: CDVInvokedUrlCommand) { var pluginResult = CDVPluginResult( status: CDVCommandStatus_ERROR ) let msg = command.arguments[0] as? String ?? "" if msg.count > 0 { /* UIAlertController is iOS 8 or newer only. */ let toastController: UIAlertController = UIAlertController( title: "", message: msg, preferredStyle: .alert ) self.viewController?.present( toastController, animated: true, completion: nil ) let mainQueue = DispatchQueue.main let deadline = DispatchTime.now() + .seconds(10) mainQueue.asyncAfter(deadline: deadline) { toastController.dismiss( animated: true, completion: nil ) } pluginResult = CDVPluginResult( status: CDVCommandStatus_OK, messageAs: msg ) } self.commandDelegate!.send( pluginResult, callbackId: command.callbackId ) } @objc(streamRTMP:) func streamRTMP(_ command: CDVInvokedUrlCommand) { self.command = command var pluginResult = CDVPluginResult( status: CDVCommandStatus_ERROR ) let uri = command.arguments[0] as? String ?? "" let streamName = command.arguments[1] as? String ?? "" self.streamName=streamName self.rtmpConnection = RTMPConnection() self.rtmpStream = RTMPStream(connection: rtmpConnection!) self.rtmpStream?.captureSettings = [ .fps: 30, // FPS .sessionPreset: AVCaptureSession.Preset.medium, // input video width/height .isVideoMirrored: false, .continuousAutofocus: false, // use camera autofocus mode .continuousExposure: false, // use camera exposure mode .preferredVideoStabilizationMode: AVCaptureVideoStabilizationMode.auto ] self.rtmpStream?.audioSettings = [ .muted: false, // mute audio .bitrate: 32 * 1000, ] self.rtmpStream?.videoSettings = [ .width: 845, // video output width .height: 480, // video output height .bitrate: 2 * 1000, // video output bitrate .profileLevel: kVTProfileLevel_H264_Baseline_3_1, // H264 Profile require "import VideoToolbox" .maxKeyFrameIntervalDuration: 2, // key frame / sec ] self.rtmpStream?.attachAudio(AVCaptureDevice.default(for: AVMediaType.audio)) { error in print(error) } self.rtmpStream?.attachCamera(DeviceUtil.device(withPosition: .front)) { error in print(error) } let view = viewController.view self.hkView = HKView(frame: view!.bounds) self.hkView?.videoGravity = AVLayerVideoGravity.resizeAspectFill self.hkView?.attachStream(rtmpStream) view?.addSubview(self.hkView!) self.closeButton = UIButton(type: .system) // Position Button self.closeButton?.frame = CGRect(x: 10, y: 20, width: 60, height: 40) // Set text on button self.closeButton?.setTitle("Close", for: .normal) //self.closeButton?.setTitleColor(.red, for: .normal) self.closeButton?.backgroundColor = UIColor.darkGray self.closeButton?.tintColor = UIColor(rgb: 0x404040) // Set button action self.maskview = UIView(frame: CGRect(x: 0, y: 0, width: (view?.bounds.width)!, height: (view?.bounds.height)!)) self.maskview?.backgroundColor = UIColor(white: 0, alpha: 1) view?.addSubview(self.maskview!) view?.addSubview(self.closeButton!) UIApplication.shared.isIdleTimerDisabled = true self.rtmpConnection?.connect(uri) self.closeButton?.addTarget(self, action: #selector(closeAction(_:)), for: .touchUpInside) self.rtmpStream!.publish(self.streamName) pluginResult = CDVPluginResult( status: CDVCommandStatus_OK, messageAs: "Streaming to \(uri)" ) self.commandDelegate!.send( pluginResult, callbackId: command.callbackId ) } @objc private func closeAction(_ sender: UIButton?) { self.stopStream() } @objc private func stopStream(){ rtmpConnection?.close() //rtmpStream?.close() // rtmpStream?.dispose() // rtmpStream?.attachCamera(nil) closeButton?.removeFromSuperview() maskview?.removeFromSuperview() hkView?.removeFromSuperview() UIApplication.shared.isIdleTimerDisabled = false } @objc private func alerMessage(msg: String){ if msg.count > 0 { /* UIAlertController is iOS 8 or newer only. */ let toastController: UIAlertController = UIAlertController( title: "", message: msg, preferredStyle: .alert ) self.viewController?.present( toastController, animated: true, completion: nil ) let mainQueue = DispatchQueue.main let deadline = DispatchTime.now() + .seconds(5) mainQueue.asyncAfter(deadline: deadline) { toastController.dismiss( animated: true, completion: nil ) } } } @objc func rtmpStatusEvent(_ notification: Notification) { let e: Event = Event.from(notification) if let data: ASObject = e.data as? ASObject, let code: String = data["code"] as? String{ // you can handle errors. switch code { case RTMPConnection.Code.connectSuccess.rawValue: self.alerMessage(msg: "Connected") break case RTMPConnection.Code.connectRejected.rawValue: self.alerMessage(msg: "Unbleto Connect To Server") break case RTMPConnection.Code.connectClosed.rawValue: self.alerMessage(msg: "Disconnected") break case RTMPConnection.Code.connectFailed.rawValue: self.alerMessage(msg: "Unbleto Connect To Server") break case RTMPConnection.Code.connectIdleTimeOut.rawValue: self.alerMessage(msg: "Server Connection Time Out") break case RTMPStream.Code.publishStart.rawValue: self.alerMessage(msg: "Streaming Started") break case RTMPStream.Code.unpublishSuccess.rawValue: break default: break } } } }
30.440613
119
0.571177
4b2e91578fbb2f0d0086efbeb7cd11c738b56957
669
// // AppDelegate.swift // iOSExample // // Created by Bibin Jacob Pulickal on 15/05/20. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } }
31.857143
179
0.77728
fb5983a1748833fd054721ae932cea989929d464
1,024
public struct StringMetadata { /// The pattern keyword is used to restrict a string to a particular regular expression. /// The regular expression syntax is the one defined in JavaScript (ECMA 262 specifically). public let pattern: String? /// The minimum number of characters in the string. (Character defined by RFC 4627) /// If present, this value *must* be greater than or equal to zero. public let minLength: Int? /// The maximum number of characters in the string. (Character defined by RFC 4627) /// If present, this value *must* be greater than or equal to zero. public let maxLength: Int? } struct StringMetadataBuilder: Codable { let pattern: String? let minLength: Int? let maxLength: Int? } extension StringMetadataBuilder: Builder { typealias Building = StringMetadata func build(_ swagger: SwaggerBuilder) throws -> StringMetadata { return StringMetadata(pattern: self.pattern, minLength: self.minLength, maxLength: self.maxLength) } }
35.310345
106
0.719727
f5df20d677370d72a4374bc1620b39691dbeef77
995
// // commitRow.swift // Gopher // // Created by Dane Acena on 8/15/21. // import SwiftUI //struct CommitRow: View{ // var commit: Repo // var body: some View { // List(commits) { commit in // VStack(alignment: .leading){ // Text(commit.sha) // .fontWeight(.heavy) // .font(.title2) // .lineLimit(1) // Text("By \(commit.commit.author.name)") // .font(.subheadline) // Text(commit.commit.message) // .font(.body) // .lineLimit(/*@START_MENU_TOKEN@*/2/*@END_MENU_TOKEN@*/) // } // }.onAppear(){ // apiCall().getGitHubCommits{ (commits) in // self.commits = commits // } // } //struct CommitRow_Previews: PreviewProvider{ // static var previews: some View { // Group{ // CommitRow(commit: repository[0]) // } // } //}
23.139535
77
0.463317
2f5b65934b49954dd8a044f10f702163d9dbd7fe
800
// // ID3FramesWithLocalizedContentCreatorFactory.swift // ID3TagEditor // // Created by Fabrizio Duroni on 29.10.20. // 2020 Fabrizio Duroni. // import Foundation class ID3FramesWithLocalizedContentCreatorFactory { static func make() -> ID3FramesWithLocalizedContentCreator { let frameConfiguration = ID3FrameConfiguration() let paddingAdder = PaddingAdderToEndOfContentUsingNullChar() return ID3FramesWithLocalizedContentCreator( localizedFrameNames: frameNamesWithLocalizedContent, localizedFrameCreator: ID3LocalizedFrameCreator( id3FrameConfiguration: frameConfiguration, frameHeaderCreator: ID3FrameHeaderCreatorFactory.make(), paddingAdder: paddingAdder ) ) } }
30.769231
72
0.71
46dc8f6336201cf4d691ca115bc45bc95d46598c
540
// // ViewController.swift // FlickrUpdates // // Created by Leonardo Vinicius Kaminski Ferreira on 25/08/17. // Copyright © 2017 Leonardo Ferreira. 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.769231
80
0.685185
1ef8725466203cd05fb5ceb72cbeeb3ee027a3b8
504
// // ViewController.swift // DACarthageExample // // Created by Dejan on 09/05/2017. // Copyright © 2017 Dejan. 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. } }
19.384615
80
0.670635
e933855276a4b7ba31fefa24f946f4c2f5249d7f
4,286
// RUN: %target-swift-frontend -print-ast %s | %FileCheck %s --check-prefix=CHECK-AST import _Differentiation struct GenericTangentVectorMember<T: Differentiable>: Differentiable, AdditiveArithmetic { var x: T.TangentVector } // CHECK-AST-LABEL: internal struct GenericTangentVectorMember<T> : Differentiable, AdditiveArithmetic where T : Differentiable // CHECK-AST: internal var x: T.TangentVector // CHECK-AST: internal init(x: T.TangentVector) // CHECK-AST: internal typealias TangentVector = GenericTangentVectorMember<T> // CHECK-AST: internal static var zero: GenericTangentVectorMember<T> { get } // CHECK-AST: internal static func + (lhs: GenericTangentVectorMember<T>, rhs: GenericTangentVectorMember<T>) -> GenericTangentVectorMember<T> // CHECK-AST: internal static func - (lhs: GenericTangentVectorMember<T>, rhs: GenericTangentVectorMember<T>) -> GenericTangentVectorMember<T> // CHECK-AST: @_implements(Equatable, ==(_:_:)) internal static func __derived_struct_equals(_ a: GenericTangentVectorMember<T>, _ b: GenericTangentVectorMember<T>) -> Bool public struct ConditionallyDifferentiable<T> { public var x: T } extension ConditionallyDifferentiable: Differentiable where T: Differentiable {} // CHECK-AST-LABEL: public struct ConditionallyDifferentiable<T> { // CHECK-AST: @differentiable(wrt: self where T : Differentiable) // CHECK-AST: public var x: T // CHECK-AST: internal init(x: T) // CHECK-AST: } // Verify that `TangentVector` is not synthesized to be `Self` for // `AdditiveArithmetic`-conforming classes. final class AdditiveArithmeticClass<T: AdditiveArithmetic & Differentiable>: AdditiveArithmetic, Differentiable { var x, y: T init(x: T, y: T) { self.x = x self.y = y } // Dummy `AdditiveArithmetic` requirements. static func == (lhs: AdditiveArithmeticClass, rhs: AdditiveArithmeticClass) -> Bool { fatalError() } static var zero: AdditiveArithmeticClass { fatalError() } static func + (lhs: AdditiveArithmeticClass, rhs: AdditiveArithmeticClass) -> Self { fatalError() } static func - (lhs: AdditiveArithmeticClass, rhs: AdditiveArithmeticClass) -> Self { fatalError() } } // CHECK-AST-LABEL: final internal class AdditiveArithmeticClass<T> : AdditiveArithmetic, Differentiable where T : AdditiveArithmetic, T : Differentiable { // CHECK-AST: final internal var x: T, y: T // CHECK-AST: internal struct TangentVector : Differentiable, AdditiveArithmetic // CHECK-AST: } @frozen public struct FrozenStruct: Differentiable {} // CHECK-AST-LABEL: @frozen public struct FrozenStruct : Differentiable { // CHECK-AST: internal init() // CHECK-AST: @frozen public struct TangentVector : Differentiable, AdditiveArithmetic { @usableFromInline struct UsableFromInlineStruct: Differentiable {} // CHECK-AST-LABEL: @usableFromInline // CHECK-AST: struct UsableFromInlineStruct : Differentiable { // CHECK-AST: internal init() // CHECK-AST: @usableFromInline // CHECK-AST: struct TangentVector : Differentiable, AdditiveArithmetic { // Test property wrappers. @propertyWrapper struct Wrapper<Value> { var wrappedValue: Value } struct WrappedPropertiesStruct: Differentiable { @Wrapper @Wrapper var x: Float @Wrapper var y: Float var z: Float @noDerivative @Wrapper var nondiff: Float } // CHECK-AST-LABEL: internal struct WrappedPropertiesStruct : Differentiable { // CHECK-AST: internal struct TangentVector : Differentiable, AdditiveArithmetic { // CHECK-AST: internal var x: Float.TangentVector // CHECK-AST: internal var y: Float.TangentVector // CHECK-AST: internal var z: Float.TangentVector // CHECK-AST: } // CHECK-AST: } class WrappedPropertiesClass: Differentiable { @Wrapper @Wrapper var x: Float = 1 @Wrapper var y: Float = 2 var z: Float = 3 @noDerivative @Wrapper var noDeriv: Float = 4 } // CHECK-AST-LABEL: internal class WrappedPropertiesClass : Differentiable { // CHECK-AST: internal struct TangentVector : Differentiable, AdditiveArithmetic { // CHECK-AST: internal var x: Float.TangentVector // CHECK-AST: internal var y: Float.TangentVector // CHECK-AST: internal var z: Float.TangentVector // CHECK-AST: } // CHECK-AST: }
35.716667
174
0.730985
5ba0cf17c7948937301e49b4dcfb3e338defd518
5,035
// // _CardBrandDataSource.swift // VGSCollectSDK // // Created by Vitalii Obertynskyi on 06.04.2020. // Copyright © 2020 VGS. All rights reserved. // import Foundation @testable import VGSCollectSDK extension SwiftLuhn.CardType { var cardNumbers: [String] { switch self { case .amex: return [ "340000099900036", "340000099900028", "340000099900044", "340000099900051", "343434343434343", "378282246310005", "371449635398431", "378734493671000", "370000000000002", "370000000100018" ] case .visaElectron: return [ "4917300800000000", "4917300000000008" ] case .visa: return [ "4000020000000000", "4000060000000006", "4000160000000004", "4000180000000002", "4000620000000007", "4000640000000005", "4000760000000001", "4002690000000008", "4003550000000003", "4005519000000006", "4017340000000003", "4035501000000008", "4111111111111111", "4111111145551142", "4131840000000003", "4151500000000008", "4166676667666746", "4199350000000002", "4293189100000008", "4400000000000008", "4444333322221111", "4484600000000004", "4571000000000001", "4607000000000009", "4646464646464644", "4977949494949497", "4988080000000000", "4988438843884305", "4462030000000000", "4242424242424242", "4444333322221111455" ] case .mastercard: return [ "2222400010000008", "2222400030000004", "2222400050000009", "2222400060000007", "2222400070000005", "2222410700000002", "2222410740360010", "2223000048410010", "2223520443560010", "5100060000000002", "5100290029002909", "5100705000000002", "5101180000000007", "5103221911199245", "5106040000000008", "5136333333333335", "5424000000000015", "5500000000000004", "5555341244441115", "5555444433331111", "5555555555554444", "5577000055770004", "5585558555855583", "5454545454545454" ] case .discover: return [ "6011000400000000", "6011100099900013", "6011111111111117", "6011000990139424", "6011601160116611", "6445644564456445" ] case .dinersClub: return [ "30599900026332", "30599900026340", "38520000023237", "30569309025904", "36006666333344", "36070500001020", "36700102000000", "36148900647913", "3096000032340126" ] case .jcb: return [ "3569990010095841", "3530111333300000", "3566002020360505", "3569990010030400" ] case .maestro: return [ "6759649826438453", "6771798021000008", "6771798025000004", "6759156019808393" ] case .unknown: return [] } } } extension SwiftLuhn { static var specificNotValidCardNumbers: [String] { return [ "4", "41", "411", "4111", "41111", "411111", "4111111", "41111111", "411111111", "4111111111", "41111111111", "411111111111", "4111111111111", "41111111111111", "411111111111111", "0000000000000000", "1111111111111111", "2222222222222222", "3333333333333333", "4444444444444444", "5555555555555555", "6666666666666666", "7777777777777777", "8888888888888888", "9999999999999999", "1234123412342134", "1234567890000000", "0987654321111111", "4111111o1111111", "34000000000000000", "3400000000000000", "340000000000000", "601100040000000", "5555555555" ] } }
28.607955
54
0.449057
8ad6a76d1f097e5475e542f3d853dce01c087d4a
2,374
// // HikeGraphTests.swift // SwiftUIExampleTests // // Created by Heather Meadow on 2/23/21. // import Foundation import XCTest import SwiftUI import ViewInspector @testable import SwiftUIExample class HikeGraphTests: XCTestCase { func testHikeGraph() throws { let expectedHike = try getHikes().first! let observationKeyPath: KeyPath<Hike.Observation, Range<Double>> = \.elevation let hikeGraph = HikeGraph(hike: expectedHike, path: observationKeyPath) let geometryReader = try hikeGraph.inspect().geometryReader(0) XCTAssertEqual(try geometryReader.hStack().forEach(0).count, expectedHike.observations.count) try geometryReader.hStack().forEach(0).enumerated().forEach { let graphCapsule = try $0.element.find(GraphCapsule.self) XCTAssertEqual(try graphCapsule.colorMultiply(), .gray) XCTAssertEqual(try graphCapsule.actualView().index, $0.offset) let expectedObservation = expectedHike.observations[$0.offset].elevation XCTAssertEqual(try graphCapsule.actualView().range, expectedObservation) XCTAssertEqual(try graphCapsule.actualView().overallRange, 291.6526363563627..<547.4953522425105) } } func testHighGraphSetsColorBasedOnPath() throws { let expectedHike = try getHikes().first! var hikeGraph = HikeGraph(hike: expectedHike, path: \.heartRate) try hikeGraph.inspect().geometryReader(0).hStack().forEach(0).forEach { XCTAssertEqual(try $0.find(GraphCapsule.self).colorMultiply(), Color(hue: 0, saturation: 0.5, brightness: 0.7)) } hikeGraph = HikeGraph(hike: expectedHike, path: \.pace) try hikeGraph.inspect().geometryReader(0).hStack().forEach(0).forEach { XCTAssertEqual(try $0.find(GraphCapsule.self).colorMultiply(), Color(hue: 0.7, saturation: 0.4, brightness: 0.7)) } hikeGraph = HikeGraph(hike: expectedHike, path: \.newRange) try hikeGraph.inspect().geometryReader(0).hStack().forEach(0).forEach { XCTAssertEqual(try $0.find(GraphCapsule.self).colorMultiply(), .black) } } private func getHikes() throws -> [Hike] { return try JSONDecoder().decode([Hike].self, from: hikesJson) } } fileprivate extension Hike.Observation { var newRange: Range<Double> { 0..<1 } }
39.566667
125
0.68492
8f0e19aceb105205f78ab8c0b7dec79cf4e7579c
3,362
// Want to improve this file? // run `swift run danger-swift edit` in the terminal // and it will pop open in Xcode import Danger import Foundation import Yams let danger = Danger() // This one runs on Travis CI // There is another on Circle which validates the tests let modified = danger.git.modifiedFiles let editedFiles = modified + danger.git.createdFiles message("These files have changed: \(editedFiles.joined(separator: ", "))") let testFiles = editedFiles.filter { $0.contains("Tests") && ($0.fileType == .swift || $0.fileType == .m) } // Validates that we've not accidentally let in a testing // shortcut to simplify dev work let testingShortcuts = ["fdescribe", "fit(@", "fit("] for file in testFiles { let content = danger.utils.readFile(file) for shortcut in testingShortcuts { if content.contains(shortcut) { fail(message: "Found a testing shortcut", file: file, line: 0) } } } // A shortcut to say "I know what I'm doing thanks" let knownDevTools = danger.github.pullRequest.body.contains("#known") // These files are ones we really don't want changes to, except in really occasional // cases, so offer a way out. let devOnlyFiles = ["Artsy/View_Controllers/App_Navigation/ARTopMenuViewController+DeveloperExtras.m", "Artsy/View_Controllers/App_Navigation/ARTopMenuViewController+SwiftDeveloperExtras.swift", "Artsy.xcodeproj/xcshareddata/xcschemes/Artsy.xcscheme"] for file in devOnlyFiles { if modified.contains(file) && !knownDevTools { fail("Developer Specific file shouldn't be changed, you can skip by adding #known to the PR body and re-runnning CI") } } // Did you make analytics changes? Well you should also include a change to our analytics spec let madeAnalyticsChanges = modified.contains("/Artsy/App/ARAppDelegate+Analytics.m") let madeAnalyticsSpecsChanges = modified.contains("/Artsy_Tests/Analytics_Tests/ARAppAnalyticsSpec.m") if madeAnalyticsChanges { if !madeAnalyticsSpecsChanges { fail("Analytics changes should have reflected specs changes in ARAppAnalyticsSpec.m") } // And note to pay extra attention anyway message("Analytics dict changed, double check for ?: `@\"\"` on new entries to ensure nils don't crash the app.") let docs = "https://docs.google.com/spreadsheets/u/1/d/1bLbeOgVFaWzLSjxLOBDNOKs757-zBGoLSM1lIz3OPiI/edit#gid=497747862" message("Also, double check the [Analytics Eigen schema](\(docs)) if the changes are non-trivial.") } // Ensure the CHANGELOG is set up like we need do { // Ensure it is valid yaml let changelogYML = danger.utils.readFile("CHANGELOG.yml") let loadedDictionary = try Yams.load(yaml: changelogYML) as? [String: Any] // So that we don't accidentally copy & paste oour upcoming section wrong if let upcoming = loadedDictionary?["upcoming"] { if upcoming is Array<Any> { fail("Upcoming an array in the CHANGELOG") } // Deployments rely on this to send info to reviewers if upcoming is Dictionary<String, Any> { let upcomingDict = upcoming as! Dictionary<String, Any> if upcomingDict["user_facing"] == nil { fail("There must be a `user_facing` section in the upcoming section of the CHANGELOG") } } } } catch { fail("The CHANGELOG is not valid YML") }
41.506173
125
0.710589
3a5f381d3a984687c9d45e16becc31a08933d8e7
892
// Created by eric_horacek on 3/17/21. // Copyright © 2021 Airbnb Inc. All rights reserved. /// All examples from the README of this project. enum ReadmeExample: CaseIterable { case tapMe case counter case bottomButton case formNavigation case modalPresentation // MARK: Internal var title: String { switch self { case .tapMe: return "Tap Me" case .counter: return "Counter" case .bottomButton: return "Bottom button" case .formNavigation: return "Form Navigation" case .modalPresentation: return "Modal Presentation" } } var body: String { switch self { case .tapMe, .counter: return "EpoxyCollectionView" case .bottomButton: return "EpoxyBars" case .formNavigation: return "EpoxyNavigationController" case .modalPresentation: return "EpoxyPresentations" } } }
21.238095
52
0.664798
1c019e221cca43db9157e7722ea2aaa94433e903
606
// RUN: %empty-directory(%t) // RUN: %{python} %utils/split_file.py -o %t %s // RUN: %sourcekitd-test -req=cursor -pos=8:37 %t/first.swift -- %t/first.swift %t/second.swift | %FileCheck %s // CHECK: source.lang.swift.ref.var.instance (6:9-6:12) // BEGIN first.swift protocol ChatDataSourceDelegateProtocol { func chatDataSourceDidUpdate() } class BaseChatViewController { var foo = 1 func bar() { print(self . /*cursor-info->*/foo) } } // BEGIN second.swift extension BaseChatViewController: ChatDataSourceDelegateProtocol { func chatDataSourceDidUpdate() { fatalError() } }
25.25
111
0.691419
fca9a214d77007edfde2997acda0ee5e85fc4b46
414
// Provides the Earth's position with respect to the center of the sun. public struct HelioPosition { public let longitude: Double public let latitude: Double public let radius: Double public init(jme: Double) { longitude = HelioPositionCalc.longitude(jme: jme) latitude = HelioPositionCalc.latitude(jme: jme) radius = HelioPositionCalc.earthRadiusVector(jme: jme) } }
31.846154
71
0.707729
1e0456a5af53807427cc1e58915e5c109cc6e033
8,806
// // DefaultAPI.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation open class DefaultAPI { /** Authenticate with the admin server. - parameter authenticationRequest: (body) (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ open class func authenticate( authenticationRequest: AuthenticationRequest? = nil, apiResponseQueue: DispatchQueue = OpenAPIClientAPI.apiResponseQueue, completion: @escaping ((_ data: AuthenticationResponse?,_ error: Error?) -> Void) ) { authenticateWithRequestBuilder(authenticationRequest: authenticationRequest) .execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): completion(response.body, nil) case let .failure(error): completion(nil, error) } } } /** Authenticate with the admin server. - POST /client/auth - Used to retrieve all target segments for certain account id. - parameter authenticationRequest: (body) (optional) - returns: RequestBuilder<AuthenticationResponse> */ open class func authenticateWithRequestBuilder(authenticationRequest: AuthenticationRequest? = nil) -> RequestBuilder<AuthenticationResponse> { let path = "/client/auth" let URLString = OpenAPIClientAPI.configPath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: authenticationRequest) let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<AuthenticationResponse>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** Get feature evaluations for target - parameter environmentUUID: (path) Unique identifier for the environment object in the API. - parameter target: (path) Unique identifier for the target object in the API. - parameter cluster: Cluster. - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ open class func getEvaluations( environmentUUID: String, target: String, cluster: String, apiResponseQueue: DispatchQueue = OpenAPIClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Evaluation]?,_ error: Error?) -> Void) ) { getEvaluationsWithRequestBuilder( environmentUUID: environmentUUID, target: target, cluster: cluster ).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): completion(response.body, nil) case let .failure(error): completion(nil, error) } } } /** Get feature evaluations for target - parameter environmentUUID: (path) Unique identifier for the environment object in the API. - parameter feature: (path) Unique identifier for the flag object in the API. - parameter target: (path) Unique identifier for the target object in the API. - parameter cluster: Cluster. - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ open class func getEvaluationByIdentifier( environmentUUID: String, feature: String, target: String, apiResponseQueue: DispatchQueue = OpenAPIClientAPI.apiResponseQueue, cluster: String, completion: @escaping ((_ data: Evaluation?,_ error: Error?) -> Void) ) { getEvaluationByIdentifierWithRequestBuilder( environmentUUID: environmentUUID, feature: feature, target: target, cluster: cluster ).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): completion(response.body, nil) case let .failure(error): completion(nil, error) } } } /** Get feature evaluations for target - GET /client/env/{environmentUUID}/target/{target}/evaluations - parameter environmentUUID: (path) Unique identifier for the environment object in the API. - parameter target: (path) Unique identifier for the target object in the API. - parameter cluster: Cluster. - returns: RequestBuilder<[Evaluation]> */ open class func getEvaluationsWithRequestBuilder( environmentUUID: String, target: String, cluster: String ) -> RequestBuilder<[Evaluation]> { var path = "/client/env/{environmentUUID}/target/{target}/evaluations?cluster=\(cluster)" let environmentUUIDPreEscape = "\(APIHelper.mapValueToPathItem(environmentUUID))" let environmentUUIDPostEscape = environmentUUIDPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{environmentUUID}", with: environmentUUIDPostEscape, options: .literal, range: nil) let targetPreEscape = "\(APIHelper.mapValueToPathItem(target))" let targetPostEscape = targetPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{target}", with: targetPostEscape, options: .literal, range: nil) let URLString = OpenAPIClientAPI.configPath + path let parameters: [String:Any] = ["cluster": cluster] let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<[Evaluation]>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() let req = requestBuilder.init( method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false ) NSLog("API getEvaluations: \(req.URLString)") return req } /** Get feature evaluations for target - GET /client/env/{environmentUUID}/target/{target}/evaluations/{feature} - parameter environmentUUID: (path) Unique identifier for the environment object in the API. - parameter feature: (path) Unique identifier for the flag object in the API. - parameter target: (path) Unique identifier for the target object in the API. - parameter cluster: Cluster. - returns: RequestBuilder<Evaluation> */ open class func getEvaluationByIdentifierWithRequestBuilder( environmentUUID: String, feature: String, target: String, cluster: String ) -> RequestBuilder<Evaluation> { var path = "/client/env/{environmentUUID}/target/{target}/evaluations/{feature}?cluster=\(cluster)" let environmentUUIDPreEscape = "\(APIHelper.mapValueToPathItem(environmentUUID))" let environmentUUIDPostEscape = environmentUUIDPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{environmentUUID}", with: environmentUUIDPostEscape, options: .literal, range: nil) let featurePreEscape = "\(APIHelper.mapValueToPathItem(feature))" let featurePostEscape = featurePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{feature}", with: featurePostEscape, options: .literal, range: nil) let targetPreEscape = "\(APIHelper.mapValueToPathItem(target))" let targetPostEscape = targetPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{target}", with: targetPostEscape, options: .literal, range: nil) let URLString = OpenAPIClientAPI.configPath + path let parameters: [String:Any] = ["cluster": cluster] let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<Evaluation>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() let req = requestBuilder.init( method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false ) NSLog("API getEvaluationByIdentifier: \(req.URLString)") return req } }
42.747573
147
0.662616
e89efdaa6db7d79e5789466824fc99ac9918c7b0
1,142
// // ChatUITests.swift // ChatUITests // // Created by Swapnil on 14/06/19. // Copyright © 2019 Swapnil. All rights reserved. // import XCTest class ChatUITests: 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.628571
182
0.686515
f735ab9b379d50ca177c52f1cba1589ceb1223a2
2,418
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/noppoMan/aws-sdk-swift/blob/master/Sources/CodeGenerator/main.swift. DO NOT EDIT. import AWSSDKSwiftCore /// Error enum for AppStream public enum AppStreamErrorType: AWSErrorType { case concurrentModificationException(message: String?) case incompatibleImageException(message: String?) case invalidAccountStatusException(message: String?) case invalidParameterCombinationException(message: String?) case invalidRoleException(message: String?) case limitExceededException(message: String?) case operationNotPermittedException(message: String?) case resourceAlreadyExistsException(message: String?) case resourceInUseException(message: String?) case resourceNotAvailableException(message: String?) case resourceNotFoundException(message: String?) } extension AppStreamErrorType { public init?(errorCode: String, message: String?){ var errorCode = errorCode if let index = errorCode.index(of: "#") { errorCode = String(errorCode[errorCode.index(index, offsetBy: 1)...]) } switch errorCode { case "ConcurrentModificationException": self = .concurrentModificationException(message: message) case "IncompatibleImageException": self = .incompatibleImageException(message: message) case "InvalidAccountStatusException": self = .invalidAccountStatusException(message: message) case "InvalidParameterCombinationException": self = .invalidParameterCombinationException(message: message) case "InvalidRoleException": self = .invalidRoleException(message: message) case "LimitExceededException": self = .limitExceededException(message: message) case "OperationNotPermittedException": self = .operationNotPermittedException(message: message) case "ResourceAlreadyExistsException": self = .resourceAlreadyExistsException(message: message) case "ResourceInUseException": self = .resourceInUseException(message: message) case "ResourceNotAvailableException": self = .resourceNotAvailableException(message: message) case "ResourceNotFoundException": self = .resourceNotFoundException(message: message) default: return nil } } }
45.622642
143
0.711745
722beaca80929939bc2367d4c96dad614de63a60
594
// // KPLikeModel.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/7/25. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import UIKit import ObjectMapper class KPLikeModel: Mappable { var createdTime: NSNumber! var isLike: NSNumber! var memberID: String! required init?(map: Map) { if map.JSON["liker_id"] == nil { return nil } } func mapping(map: Map) { createdTime <- map["created_time"] isLike <- map["is_like"] memberID <- map["liker_id"] } }
19.8
57
0.558923
aca72193b5369a61dbc5522b4934c315de4dec58
14,670
// DO NOT EDIT. // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: messages.proto // // For information on using the generated types, please see the documenation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that your are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } enum Messageservice_MessageState: SwiftProtobuf.Enum { typealias RawValue = Int case queued // = 0 case sending // = 1 case delivered // = 2 case failed // = 3 case UNRECOGNIZED(Int) init() { self = .queued } init?(rawValue: Int) { switch rawValue { case 0: self = .queued case 1: self = .sending case 2: self = .delivered case 3: self = .failed default: self = .UNRECOGNIZED(rawValue) } } var rawValue: Int { switch self { case .queued: return 0 case .sending: return 1 case .delivered: return 2 case .failed: return 3 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension Messageservice_MessageState: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. static var allCases: [Messageservice_MessageState] = [ .queued, .sending, .delivered, .failed, ] } #endif // swift(>=4.2) struct Messageservice_Empty { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct Messageservice_Receiver { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var id: String = String() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct Messageservice_Sender { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var id: String = String() var nickName: String = String() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct Messageservice_Message { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var id: String { get {return _storage._id} set {_uniqueStorage()._id = newValue} } var text: String { get {return _storage._text} set {_uniqueStorage()._text = newValue} } var receiver: Messageservice_Receiver { get {return _storage._receiver ?? Messageservice_Receiver()} set {_uniqueStorage()._receiver = newValue} } /// Returns true if `receiver` has been explicitly set. var hasReceiver: Bool {return _storage._receiver != nil} /// Clears the value of `receiver`. Subsequent reads from it will return its default value. mutating func clearReceiver() {_uniqueStorage()._receiver = nil} var token: String { get {return _storage._token} set {_uniqueStorage()._token = newValue} } var date: Int64 { get {return _storage._date} set {_uniqueStorage()._date = newValue} } var state: Messageservice_MessageState { get {return _storage._state} set {_uniqueStorage()._state = newValue} } var sender: Messageservice_Sender { get {return _storage._sender ?? Messageservice_Sender()} set {_uniqueStorage()._sender = newValue} } /// Returns true if `sender` has been explicitly set. var hasSender: Bool {return _storage._sender != nil} /// Clears the value of `sender`. Subsequent reads from it will return its default value. mutating func clearSender() {_uniqueStorage()._sender = nil} var code: Int32 { get {return _storage._code} set {_uniqueStorage()._code = newValue} } var phone: String { get {return _storage._phone} set {_uniqueStorage()._phone = newValue} } var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _storage = _StorageClass.defaultInstance } struct Messageservice_MessageStreamRequest { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var login: String = String() var token: String = String() var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "messageservice" extension Messageservice_MessageState: SwiftProtobuf._ProtoNameProviding { static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "queued"), 1: .same(proto: "sending"), 2: .same(proto: "delivered"), 3: .same(proto: "failed"), ] } extension Messageservice_Empty: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Empty" static let _protobuf_nameMap = SwiftProtobuf._NameMap() mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Messageservice_Empty, rhs: Messageservice_Empty) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Messageservice_Receiver: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Receiver" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "id"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularStringField(value: &self.id) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.id.isEmpty { try visitor.visitSingularStringField(value: self.id, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Messageservice_Receiver, rhs: Messageservice_Receiver) -> Bool { if lhs.id != rhs.id {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Messageservice_Sender: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Sender" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "id"), 2: .same(proto: "nickName"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularStringField(value: &self.id) case 2: try decoder.decodeSingularStringField(value: &self.nickName) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.id.isEmpty { try visitor.visitSingularStringField(value: self.id, fieldNumber: 1) } if !self.nickName.isEmpty { try visitor.visitSingularStringField(value: self.nickName, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Messageservice_Sender, rhs: Messageservice_Sender) -> Bool { if lhs.id != rhs.id {return false} if lhs.nickName != rhs.nickName {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Messageservice_Message: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Message" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "id"), 2: .same(proto: "text"), 3: .same(proto: "receiver"), 4: .same(proto: "token"), 5: .same(proto: "date"), 6: .same(proto: "state"), 7: .same(proto: "sender"), 8: .same(proto: "code"), 9: .same(proto: "phone"), ] fileprivate class _StorageClass { var _id: String = String() var _text: String = String() var _receiver: Messageservice_Receiver? = nil var _token: String = String() var _date: Int64 = 0 var _state: Messageservice_MessageState = .queued var _sender: Messageservice_Sender? = nil var _code: Int32 = 0 var _phone: String = String() static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _id = source._id _text = source._text _receiver = source._receiver _token = source._token _date = source._date _state = source._state _sender = source._sender _code = source._code _phone = source._phone } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularStringField(value: &_storage._id) case 2: try decoder.decodeSingularStringField(value: &_storage._text) case 3: try decoder.decodeSingularMessageField(value: &_storage._receiver) case 4: try decoder.decodeSingularStringField(value: &_storage._token) case 5: try decoder.decodeSingularInt64Field(value: &_storage._date) case 6: try decoder.decodeSingularEnumField(value: &_storage._state) case 7: try decoder.decodeSingularMessageField(value: &_storage._sender) case 8: try decoder.decodeSingularInt32Field(value: &_storage._code) case 9: try decoder.decodeSingularStringField(value: &_storage._phone) default: break } } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in if !_storage._id.isEmpty { try visitor.visitSingularStringField(value: _storage._id, fieldNumber: 1) } if !_storage._text.isEmpty { try visitor.visitSingularStringField(value: _storage._text, fieldNumber: 2) } if let v = _storage._receiver { try visitor.visitSingularMessageField(value: v, fieldNumber: 3) } if !_storage._token.isEmpty { try visitor.visitSingularStringField(value: _storage._token, fieldNumber: 4) } if _storage._date != 0 { try visitor.visitSingularInt64Field(value: _storage._date, fieldNumber: 5) } if _storage._state != .queued { try visitor.visitSingularEnumField(value: _storage._state, fieldNumber: 6) } if let v = _storage._sender { try visitor.visitSingularMessageField(value: v, fieldNumber: 7) } if _storage._code != 0 { try visitor.visitSingularInt32Field(value: _storage._code, fieldNumber: 8) } if !_storage._phone.isEmpty { try visitor.visitSingularStringField(value: _storage._phone, fieldNumber: 9) } } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Messageservice_Message, rhs: Messageservice_Message) -> Bool { if lhs._storage !== rhs._storage { let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in let _storage = _args.0 let rhs_storage = _args.1 if _storage._id != rhs_storage._id {return false} if _storage._text != rhs_storage._text {return false} if _storage._receiver != rhs_storage._receiver {return false} if _storage._token != rhs_storage._token {return false} if _storage._date != rhs_storage._date {return false} if _storage._state != rhs_storage._state {return false} if _storage._sender != rhs_storage._sender {return false} if _storage._code != rhs_storage._code {return false} if _storage._phone != rhs_storage._phone {return false} return true } if !storagesAreEqual {return false} } if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Messageservice_MessageStreamRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".MessageStreamRequest" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "login"), 2: .same(proto: "token"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularStringField(value: &self.login) case 2: try decoder.decodeSingularStringField(value: &self.token) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.login.isEmpty { try visitor.visitSingularStringField(value: self.login, fieldNumber: 1) } if !self.token.isEmpty { try visitor.visitSingularStringField(value: self.token, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Messageservice_MessageStreamRequest, rhs: Messageservice_MessageStreamRequest) -> Bool { if lhs.login != rhs.login {return false} if lhs.token != rhs.token {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
33.340909
147
0.704158
1191b65d1f50536306e23740205f9d0a370dee85
8,109
import Nuke import Swiftest /// / /// / ImageDisplayable.swift /// / UIKitBase /// / /// / Created by Brian Strobach on 12/11/18. /// / Copyright © 2018 Brian Strobach. All rights reserved. /// / // import UIKit extension Nuke_ImageDisplaying where Self: UIView { @discardableResult public func loadImage(_ imageResolving: ImageResolving, options: ImageLoadingOptions = .shared, progress: ImageTask.ProgressHandler? = nil, completion: ImageTask.Completion? = nil) throws -> ImageTask? { switch imageResolving { case let .image(image): nuke_display(image: image) return nil case let .url(urlConvertible): return try self.loadImage(with: urlConvertible, options: options, progress: progress, completion: completion) } } @discardableResult public func loadImage(_ imageResolving: ImageResolving, options: ImageLoadingOptions = .shared, progress: ImageTask.ProgressHandler? = nil, completion: ImageTask.Completion? = nil, errorImage: PlatformImage?) -> ImageTask? { do { return try self.loadImage(imageResolving, options: options, progress: progress, completion: completion) } catch { nuke_display(image: errorImage) return nil } } @discardableResult public func loadImage(with url: URLConvertible, options: ImageLoadingOptions = .shared, progress: ImageTask.ProgressHandler? = nil, completion: ImageTask.Completion? = nil) throws -> ImageTask? { return try self.loadImage(with: url.assertURL(), options: options, progress: progress, completion: completion) } @discardableResult public func loadImage(with url: URLConvertible, options: ImageLoadingOptions = .shared, progress: ImageTask.ProgressHandler? = nil, completion: ImageTask.Completion? = nil, errorImage: PlatformImage?) -> ImageTask? { do { return try self.loadImage(with: url, options: options, progress: progress, completion: completion) } catch { nuke_display(image: errorImage) return nil } } @discardableResult public func loadImage(with url: URL, options: ImageLoadingOptions = .shared, progress: ImageTask.ProgressHandler? = nil, completion: ImageTask.Completion? = nil) -> ImageTask? { Nuke.cancelRequest(for: self) return Nuke.loadImage(with: url, options: options, into: self, progress: progress, completion: completion) } @discardableResult public func loadImage(with url: URL, requestOptions: ImageRequestOptions? = nil, loadingOptions: ImageLoadingOptions = .shared, progress: ImageTask.ProgressHandler? = nil, processors: [ImageProcessing] = [], completion: ImageTask.Completion? = nil) -> ImageTask? { Nuke.cancelRequest(for: self) let request = ImageRequest(url: url, processors: processors, options: requestOptions ?? .init()) return Nuke.loadImage(with: request, options: loadingOptions, into: self, progress: progress, completion: completion) } public func resetImage() { Nuke.cancelRequest(for: self) nuke_display(image: nil) } } extension UIButton: Nuke_ImageDisplaying { public func display(image: PlatformImage?) { imageView?.image = image } public func nuke_display(image: PlatformImage?) { imageView?.image = image } } public enum ImageResolving { case image(UIImage) case url(URLConvertible) } // // public typealias AsyncCompletion<S, E: Error> = (success: (S) -> Void, failure: (E) -> Void) // // public protocol URLImageResolvable{ // func resolve(imageAt url: URL, complete: AsyncCompletion<UIImage, ImageResolverError>) // func cancelRequest(forImageAt url: URL) // } // // open class URLImageResolver: URLImageResolvable{ // static var `default`: URLImageResolvable = DefaultURLImageResolver() // open func resolve(imageAt url: URL, complete: AsyncCompletion<UIImage, ImageResolverError>) { // assertionFailure(String(describing: self) + " is abstract. You must implement " + #function) // } // // open func cancelRequest(forImageAt url: URL) { // assertionFailure(String(describing: self) + " is abstract. You must implement " + #function) // } // } // // public class DefaultURLImageResolver: URLImageResolver{ // let imageCache = NSCache<NSString, UIImage>() // let requestCache: [String: [AsyncCompletion<UIImage, ImageResolverError>]] = [:] // // public override func resolve(imageAt url: URL, complete: AsyncCompletion<UIImage, ImageResolverError>) { // let key = url.absoluteString // if let cachedImage = imageCache.object(forKey: key.toNSString) { // complete.success(cachedImage) // return // } // URLSession.shared.dataTask(with: url, completionHandler: {[weak self] (data, response, error) in // guard let self = self else { return } // guard error == nil else { // complete.failure(ImageResolverError.NetworkError(error!)) // } // // guard let imageData = data, let image = UIImage(data: imageData) else { // complete.failure(ImageResolverError.BadImageData(error)) // } // // DispatchQueue.main.async { // self.imageCache.setObject(image, forKey: key.toNSString) // complete.success(image) // // } // }).resume() // } // // } // // public enum URLConvertibleError: Error { // case invalidURL // } // // public protocol URLConvertible { // var toURL: URL? { get } // func assertURL() throws -> URL // } // // extension URLConvertible { // public func assertURL() throws -> URL { // guard let url = toURL else { // throw URLConvertibleError.invalidURL // } // return url // } // } // // extension URL: URLConvertible { // public var toURL: URL? { // return self // } // } // // extension URLComponents: URLConvertible { // public var toURL: URL? { // return url // } // } // // extension String: URLConvertible { // public var toURL: URL? { // if let string = addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) { // return URL(string: string) // } // return URL(string: self) // } // } // // public protocol ImageDisplayable{ // func display(image: URLConvertible, placeholderImage: UIImage?, processing: ((UIImage) throws -> (UIImage))?) // func display(image: UIImage) // } // // public enum ImageResolverError: Error{ // case InvalidURL // case BadImageData(Error?) // case NetworkError(Error) // case ProcessingError(Error) // } // // // // extension UIImageView: ImageDisplayable{ // // public func display(image: URLConvertible, // placeholderImage: UIImage? = nil, // processing: ((UIImage) throws -> (UIImage))? = nil) { // // self.image = placeholderImage // // } // // public func display(image: UIImage) { // self.image = image // } // } // // extension UIButton{ // open func displayImage(withUrlString urlString: String, filter: ImageFilter? = nil, for state: UIControl.State){ // resetImage(for: state) // guard let url: URL = URL(string: urlString) else { return } // af_setImage(for: state, url: url) // } // // open func resetImage(for state: UIControl.State){ // af_cancelImageRequest(for: state) // } // } // //
33.37037
125
0.597731
76e72b54bf9a6d0670544655e801900ee2c1aefc
2,158
// // AppDelegate.swift // cocoapTest // // Created by 前链 on 2019/7/17. // Copyright © 2019 前链. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.914894
285
0.753939
21ddee9df4d91490869cf9eba709dee8c8f07113
118
// // Copyright (c) Vatsal Manot // import Swallow public enum AttributeMigrationPolicy { case discardCurrent }
11.8
38
0.728814
c1f3db9ea6e67b369e019dce91c1726e5aef9249
2,392
// // TweetViewCell.swift // Twitter // // Created by Sabrina Slattery on 3/6/21. // Copyright © 2021 Dan. All rights reserved. // import UIKit class TweetViewCell: UITableViewCell { @IBOutlet weak var userProfileView: UIImageView! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var tweetContentLabel: UILabel! @IBOutlet weak var favButton: UIButton! @IBOutlet weak var retweetButton: UIButton! var favorited:Bool = false var retweeted:Bool = false var tweetId:Int = -1 override func awakeFromNib() { super.awakeFromNib() // Initialization code } @IBAction func favoriteTweet(_ sender: Any) { let notFavorited = !favorited if (notFavorited) { TwitterAPICaller.client?.favoriteTweet(tweetId: tweetId, success: { self.setFavorite(true) }, failure: { (error) in print("Cannot favorite: \(error)") }) } else { TwitterAPICaller.client?.unfavoriteTweet(tweetId: tweetId, success: { self.setFavorite(false) }, failure: { (error) in print("Cannot unfavorite: \(error)") }) } } @IBAction func retweet(_ sender: Any) { TwitterAPICaller.client?.retweet(tweetId: tweetId, success: { self.setRetweeted(true) }, failure: { (error) in print("Cannot retweet: \(error)") }) } func setRetweeted(_ isRetweeted:Bool){ if(isRetweeted) { retweetButton.setImage(UIImage(named: "retweet-icon-green"), for: UIControl.State.normal) retweetButton.isEnabled = false } else { retweetButton.setImage(UIImage(named: "retweet-icon"), for: UIControl.State.normal) retweetButton.isEnabled = true } } func setFavorite(_ isFavorited:Bool){ favorited = isFavorited if (favorited) { favButton.setImage(UIImage(named:"favor-icon-red"), for: UIControl.State.normal) } else { favButton.setImage(UIImage(named:"favor-icon"), for: UIControl.State.normal) } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
29.530864
101
0.597408
ccbd29358cd64019aefa722b73d29a88fcc5d0bc
1,357
// // Icon.swift // SimpleWeather // // Created by Alan Cooke on 29/11/2019. // Copyright © 2019 Ryan Nystrom. All rights reserved. // import Foundation /* A machine-readable text summary of this data point, suitable for selecting an icon for display. If defined, this property will have one of the following values: clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night */ enum Icon: String, Codable { case clearDay = "clear-day" case clearNight = "clear-night" case partlyCloudyDay = "partly-cloudy-day" case partlyCloudyNight = "partly-cloudy-night" case snow, sleet, cloudy, rain, wind, fog } extension Icon { func named(night: Bool) -> String { switch self { case .clearDay: return night ? "Moon" : "Sun" case .clearNight: return "Moon" case .partlyCloudyDay: return night ? "Mostly-sunny-night" : "Mostly-sunny-day" case .partlyCloudyNight: return "Mostly-sunny-night" case .snow: return "Snow" case .cloudy: return "Cloudy" case .rain: return "Mist" case .wind: return "Wind" case .fog: return "Haze" default: return "" } } } /* */
24.672727
265
0.58364
d73c3232f87c476fe1e2ca8632726b9bfcec92d1
2,343
import UIKit import SpriteKit import AVFoundation import GoogleMobileAds class ViewController: UIViewController, GADBannerViewDelegate { var audioPlayer : AVAudioPlayer! var admobView: GADBannerView = GADBannerView() let AdMobID = "ca-app-pub-6865266976411360/5264970335" /* * viewDidLoad * */ override func viewDidLoad() { super.viewDidLoad() showAd() let mainFrame = UIScreen.mainScreen().bounds let skViewFrame = CGRectMake(0 , 0, mainFrame.width, mainFrame.height - admobView.frame.height) let skView = SKView(frame: skViewFrame) skView.multipleTouchEnabled = false skView.ignoresSiblingOrder = true self.view.addSubview(skView) let scene = TitleScene(size: skView.bounds.size) skView.presentScene(scene) changeBGM(scene) } func showAd() { admobView = GADBannerView(adSize:kGADAdSizeBanner) admobView.frame.origin = CGPointMake(0, self.view.frame.size.height - admobView.frame.height) admobView.frame.size = CGSizeMake(self.view.frame.width, admobView.frame.height) admobView.adUnitID = AdMobID admobView.delegate = self admobView.rootViewController = self let admobRequest : GADRequest = GADRequest() // admobRequest.testDevices = [kGADSimulatorID] admobView.loadRequest(admobRequest) self.view.addSubview(admobView) } /* * changeBGM * */ func changeBGM(scene: SKScene) { if audioPlayer != nil && audioPlayer.playing { audioPlayer.stop() } var bgm : String if scene.isKindOfClass(PlayScene) || scene.isKindOfClass(BattleScene){ bgm = "play_bgm" } else if scene.isKindOfClass(TitleScene) { bgm = "title_bgm" } else { bgm = "home_bgm" } audioPlayer = try! AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(bgm, ofType: "mp3")!)) audioPlayer.numberOfLoops = -1 audioPlayer.prepareToPlay() audioPlayer.play() } override func prefersStatusBarHidden() -> Bool { return true } }
32.09589
139
0.611182
0161f73e2dbc00f4b64011e88298e18371d39cb1
515
// // DividerCollectionViewCell.swift // ipad // // Created by Amir Shayegh on 2019-11-05. // Copyright © 2019 Amir Shayegh. All rights reserved. // import UIKit class DividerCollectionViewCell: UICollectionViewCell, Theme { @IBOutlet weak var divider: UIView! override func awakeFromNib() { super.awakeFromNib() style() } func setup(visible: Bool) { divider.alpha = visible ? 1 : 0 } func style() { styleDivider(view: divider) } }
17.758621
62
0.617476
ff0b3e4bdd0e8a2cf99c13fd21dc4f0fcfc70d24
1,688
// // Data+.swift // UIPiPView // // Created by Akihiro Urushihara on 2021/12/13. // import Foundation import AVKit import AVFoundation extension Data { func toCMBlockBuffer() throws -> CMBlockBuffer { /// This block source is a manually retained pointer to our data instance. /// The passed FreeBlock function manually releases it when the block buffer gets deallocated. let data = NSMutableData(data: self) var source = CMBlockBufferCustomBlockSource() source.refCon = Unmanaged.passRetained(data).toOpaque() source.FreeBlock = freeBlock var blockBuffer: CMBlockBuffer? let result = CMBlockBufferCreateWithMemoryBlock( allocator: kCFAllocatorDefault, memoryBlock: data.mutableBytes, blockLength: data.length, blockAllocator: kCFAllocatorNull, customBlockSource: &source, offsetToData: 0, dataLength: data.length, flags: 0, blockBufferOut: &blockBuffer) if OSStatus(result) != kCMBlockBufferNoErr { throw CMEncodingError.cmBlockCreationFailed } guard let buffer = blockBuffer else { throw CMEncodingError.cmBlockCreationFailed } assert(CMBlockBufferGetDataLength(buffer) == data.length) return buffer } } private func freeBlock( _ refCon: UnsafeMutableRawPointer?, doomedMemoryBlock: UnsafeMutableRawPointer, sizeInBytes: Int ) -> Void { let unmanagedData = Unmanaged<NSData>.fromOpaque(refCon!) unmanagedData.release() } enum CMEncodingError: Error { case cmBlockCreationFailed }
27.672131
102
0.659953
099b3aecd9c33d1b516f874cbb6e802332583019
1,092
// // Epub.swift // Example // // Created by Kevin Delord on 18/05/2017. // Copyright © 2017 FolioReader. All rights reserved. // import Foundation import NFolioReaderKit enum Epub: Int { case bookOne = 0 case bookTwo var name: String { switch self { case .bookOne: return "The Silver Chair" // standard eBook case .bookTwo: return "The Adventures Of Sherlock Holmes - Adventure I" // audio-eBook } } var shouldHideNavigationOnTap: Bool { switch self { case .bookOne: return false case .bookTwo: return true } } var scrollDirection: FolioReaderScrollDirection { switch self { case .bookOne: return .vertical case .bookTwo: return .horizontal } } var bookPath: String? { return Bundle.main.path(forResource: self.name, ofType: "epub") } var readerIdentifier: String { switch self { case .bookOne: return "READER_ONE" case .bookTwo: return "READER_TWO" } } }
22.75
99
0.583333
2027abc3c39612639325e82158cee7eafd6669ed
787
// // ViewController.swift // Example // // Created by Shubham Gupta on 10/09/18. // Copyright © 2018 Shubham Gupta. All rights reserved. // import UIKit import SGSelectionModal class ViewController: UIViewController { var selectedIndex: Int = 0 override func viewDidLoad() { super.viewDidLoad() } @IBAction func previewSGModal(_ sender: Any) { let modal = SGModal(title: "Select Country", closeButtonTitle: "Close") modal.width = 300 modal.selectedIndex = selectedIndex for (index, state) in StateList.states.enumerated() { modal.addItem(item: state) { () in print(state) self.selectedIndex = index } } modal.show() } }
22.485714
79
0.587039
09808ff8218eeebdfb45ebe7bb9ee5e275f5c2b6
2,820
//: [Previous](@previous) import UIKit import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true //: # Group of Tasks let workerQueue = DispatchQueue(label: "com.raywenderlich.worker", attributes: .concurrent) let numberArray = [(0,1), (2,3), (4,5), (6,7), (8,9)] print("hello world") //: ## Creating a group print("=== Group of sync tasks ===\n") // TODO: Create slowAddGroup let slowAddGroup = DispatchGroup() //: ## Dispatching to a group // TODO: Loop to add slowAdd tasks to group for inValue in numberArray { workerQueue.async(group: slowAddGroup) { let result = slowAdd(inValue) print("Result = \(result)") } } //: ## Notification of group completion //: Will be called only when every task in the dispatch group has completed let defaultQueue = DispatchQueue.global() // TODO: Call notify method slowAddGroup.notify(queue: defaultQueue) { print("SLOW ADD: completed all tasks") // PlaygroundPage.current.finishExecution() } //: ## Waiting for a group to complete //: __DANGER__ This is synchronous and can block: //: //: This is a synchronous call on the __current__ queue, so will block it. You cannot have anything in the group that wants to use the current queue otherwise you'll deadlock. // TODO: Call wait method slowAddGroup.wait(timeout: DispatchTime.distantFuture) //: ## Wrapping an existing Async API //: All well and good for new APIs, but there are lots of async APIs that don't have group parameters. What can you do with them, so the group knows when they're *really* finished? //: //: Remember from the previous video, the `slowAdd` function we wrapped as an asynchronous function? func asyncAdd(_ input: (Int, Int), runQueue: DispatchQueue, completionQueue: DispatchQueue, completion: @escaping (Int, Error?) -> ()) { runQueue.async { var error: Error? error = .none let result = slowAdd(input) completionQueue.async { completion(result, error) } } } //: Wrap `asyncAdd` function // TODO: Create asyncAdd_Group func asyncAdd_Group(_ input:(Int, Int), runQueue:DispatchQueue, completionQueue:DispatchQueue, group: DispatchGroup, completion:@escaping(Int, Error?) ->()) { group.enter() asyncAdd(input, runQueue: runQueue, completionQueue: completionQueue) { result, error in completion(result, error) group.leave() } } print("\n=== Group of async tasks ===\n") let wrappedGroup = DispatchGroup() for pair in numberArray { // TODO: use the new function here to calculate the sums of the array asyncAdd_Group(pair, runQueue: workerQueue, completionQueue: defaultQueue, group: wrappedGroup) { result, error in print("Result = \(result)") } } // TODO: Notify of completion wrappedGroup.notify(queue: defaultQueue) { print("SLOW ADD: completed all tasks") PlaygroundPage.current.finishExecution() } //: [Next](@next)
32.790698
180
0.72695
f52ed50eb30d53f5aa74303c082ae4d46ffef88f
5,478
// // CollectionViewSectionProvider.swift // Flix // // Created by DianQK on 04/10/2017. // Copyright © 2017 DianQK. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxDataSources protocol _SectionNode { var identity: String { get } var headerNode: _Node? { get } var footerNode: _Node? { get } } struct IdentifiableSectionNode: IdentifiableType, _SectionNode { let identity: String let headerNode: _Node? let footerNode: _Node? init(identity: String, headerNode: IdentifiableNode? = nil, footerNode: IdentifiableNode? = nil) { self.identity = identity self.headerNode = headerNode self.footerNode = footerNode } } struct SectionNode: _SectionNode { let identity: String let headerNode: _Node? let footerNode: _Node? init(identity: String, headerNode: _Node? = nil, footerNode: _Node? = nil) { self.identity = identity self.headerNode = headerNode self.footerNode = footerNode } } public class CollectionViewSectionProvider: FlixCustomStringConvertible, ProviderHiddenable { public var headerProvider: _SectionPartionCollectionViewProvider? public var footerProvider: _SectionPartionCollectionViewProvider? public var providers: [_CollectionViewMultiNodeProvider] public var isHidden: Bool { get { return _isHidden.value } set { _isHidden.accept(newValue) } } fileprivate let _isHidden = BehaviorRelay(value: false) public init(providers: [_CollectionViewMultiNodeProvider], headerProvider: _SectionPartionCollectionViewProvider? = nil, footerProvider: _SectionPartionCollectionViewProvider? = nil) { self.providers = providers self.headerProvider = headerProvider self.footerProvider = footerProvider } func createSectionModel() -> Observable<(section: SectionNode, nodes: [Node])?> { let headerSection = headerProvider?._createSectionPartion() ?? Observable.just(nil) let footerSection = footerProvider?._createSectionPartion() ?? Observable.just(nil) let nodes = Observable.combineLatest(providers.map { $0._createNodes() }) .map { $0.flatMap { $0 } } .ifEmpty(default: []) let sectionProviderIdentity = self._flix_identity let isHidden = self._isHidden.asObservable().distinctUntilChanged() return Observable .combineLatest(headerSection, footerSection, nodes, isHidden) { (headerSection, footerSection, nodes, isHidden) -> (section: SectionNode, nodes: [Node])? in if isHidden { return nil } let section = SectionNode(identity: sectionProviderIdentity, headerNode: headerSection, footerNode: footerSection) return (section: section, nodes: nodes) } } } public class AnimatableCollectionViewSectionProvider: CollectionViewSectionProvider { public var animatableHeaderProvider: _AnimatableSectionPartionCollectionViewProvider? public var animatableFooterProvider: _AnimatableSectionPartionCollectionViewProvider? public var animatableProviders: [_AnimatableCollectionViewMultiNodeProvider] public init(providers: [_AnimatableCollectionViewMultiNodeProvider], headerProvider: _AnimatableSectionPartionCollectionViewProvider? = nil, footerProvider: _AnimatableSectionPartionCollectionViewProvider? = nil) { self.animatableHeaderProvider = headerProvider self.animatableFooterProvider = footerProvider self.animatableProviders = providers super.init(providers: providers, headerProvider: headerProvider, footerProvider: footerProvider) } func createSectionModel() -> Observable<(section: IdentifiableSectionNode, nodes: [IdentifiableNode])?> { let headerSection = animatableHeaderProvider?._createAnimatableSectionPartion() ?? Observable.just(nil) let footerSection = animatableFooterProvider?._createAnimatableSectionPartion() ?? Observable.just(nil) let nodes = Observable.combineLatest(animatableProviders.map { $0._createAnimatableNodes() }) .ifEmpty(default: []) .map { (value) -> [IdentifiableNode] in return value.reduce([IdentifiableNode]()) { acc, x in let nodeCount = x.count let accCount = acc.count let nodes = x.map { node -> IdentifiableNode in var node = node node.providerStartIndexPath.row = accCount node.providerEndIndexPath.row = accCount + nodeCount - 1 return node } return acc + nodes } } let sectionProviderIdentity = self._flix_identity let isHidden = self._isHidden.asObservable().distinctUntilChanged() return Observable .combineLatest(headerSection, footerSection, nodes, isHidden) { (headerSection, footerSection, nodes, isHidden) -> (section: IdentifiableSectionNode, nodes: [IdentifiableNode])? in if isHidden { return nil } let section = IdentifiableSectionNode(identity: sectionProviderIdentity, headerNode: headerSection, footerNode: footerSection) return (section: section, nodes: nodes) } } }
38.851064
218
0.673421
e581b1c58151614fec0079f3177424ecce59e924
4,303
// // MainViewController.swift // ImageAnnotations // // Created by Jorge Ovalle on 17/01/20. // Copyright © 2020 Jorge Ovalle. All rights reserved. // import Cocoa final class MainViewController: NSViewController { private lazy var documentsTableView = ImagesTableViewController() private lazy var imageDetailView = ImageDetailViewController() let viewModel: ImageAnnotationsViewModelProtocol init(viewModel: ImageAnnotationsViewModelProtocol = ImageAnnotationViewModel()) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } @available (*, unavailable) required init?(coder: NSCoder) { viewModel = ImageAnnotationViewModel() super.init(coder: coder) } override func viewDidLoad() { super.viewDidLoad() documentsTableView.delegate = self documentsTableView.dataSource = self imageDetailView.delegate = self viewModel.binder = self } override func loadView() { let splitView = NSSplitView() splitView.addSubview(documentsTableView.view) splitView.addSubview(imageDetailView.view) splitView.isVertical = true documentsTableView.view.widthAnchor.constraint(equalToConstant: 200).isActive = true imageDetailView.view.widthAnchor.constraint(greaterThanOrEqualToConstant: 100).isActive = true let identifier = String(describing: self) splitView.dividerStyle = .thick splitView.autosaveName = identifier splitView.identifier = NSUserInterfaceItemIdentifier(rawValue: identifier) splitView.adjustSubviews() view = splitView } } extension MainViewController: NSTableViewDataSource { func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { let imageAnnotation = viewModel.imageAnotation(for: row) let cell = NSCell(textCell: imageAnnotation.name) cell.isEditable = false return cell } func numberOfRows(in tableView: NSTableView) -> Int { return viewModel.numberOfRows() } } extension MainViewController: NSTableViewDelegate { func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool { viewModel.current = viewModel.imageAnotation(for: row) return true } } extension MainViewController: ImageAnnotationsViewModelBinder { func bind(_ viewModel: ImageAnnotationsViewModelProtocol) { documentsTableView.bind(viewModel) imageDetailView.bind(viewModel) } } extension MainViewController: NSOpenSavePanelDelegate { func panel(_ sender: Any, validate url: URL) throws { guard let panel = (sender as? NSOpenPanel), let identifier = panel.identifier else { return } switch identifier { case .openPanel: viewModel.dataSet = AnnotationDataSet(urls: panel.urls) case .savePanel: panel.directoryURL.flatMap { viewModel.export(at: $0) } default: break } } } extension NSUserInterfaceItemIdentifier { static let savePanel = NSUserInterfaceItemIdentifier(rawValue: "savePanel") static let openPanel = NSUserInterfaceItemIdentifier(rawValue: "openPanel") } extension MainViewController: ImageDetailViewDelegate { func willAddAnnotation(coordinate: Coordinate) { let alert: NSAlert = NSAlert() alert.messageText = "Adding annotation" alert.informativeText = "Add the title for the image annotation" alert.alertStyle = NSAlert.Style.informational let textField = NSTextField(frame: NSRect(x: 0, y: 0, width: 100, height: 20)) alert.accessoryView = textField alert.addButton(withTitle: "Ok") alert.addButton(withTitle: "Cancel") alert.beginSheetModal(for: view.window!) { [weak self] modalResponse in guard let self = self else { return } switch modalResponse { case .alertFirstButtonReturn: self.viewModel.addAnnotation(with: textField.stringValue, at: coordinate) case .alertSecondButtonReturn: self.imageDetailView.removeLastAnnotation() default: break } } } }
32.847328
108
0.679061
c19ecbe45a4a57244c2310933b159690cff24679
11,984
// // SelectParticipantsViewController.swift // uChat-project // // Created by Luccas Beck on 3/6/19. // Copyright © 2019 Luccas Beck. All rights reserved. // import UIKit import Firebase import ARSLineProgress class SelectParticipantsViewController: UIViewController { let falconUsersCellID = "falconUsersCellID" let selectedParticipantsCollectionViewCellID = "SelectedParticipantsCollectionViewCellID" var filteredUsers = [User]() { didSet { configureSections() } } var users = [User]() var sortedFirstLetters = [String]() var sections = [[User]]() var selectedFalconUsers = [User]() var searchBar: UISearchBar? let tableView = UITableView() var selectedParticipantsCollectionView: UICollectionView = { var selectedParticipantsCollectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) return selectedParticipantsCollectionView }() let alignedFlowLayout = CollectionViewLeftAlignFlowLayout() var collectionViewHeightAnchor: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() setupSearchController() setupMainView() setupCollectionView() setupTableView() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if navigationController?.visibleViewController is GroupProfileTableViewController { return } deselectAll() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) DispatchQueue.main.async { self.tableView.reloadData() self.reloadCollectionView() } } deinit { print("select participants deinit") } fileprivate func deselectAll() { guard users.count > 0 else { return } _ = users.map { $0.isSelected = false } filteredUsers = users sections = [users] DispatchQueue.main.async { self.tableView.reloadData() } } fileprivate var isInitialLoad = true fileprivate func configureSections() { if isInitialLoad { _ = filteredUsers.map { $0.isSelected = false } isInitialLoad = false } let firstLetters = filteredUsers.map { $0.titleFirstLetter } let uniqueFirstLetters = Array(Set(firstLetters)) sortedFirstLetters = uniqueFirstLetters.sorted() sections = sortedFirstLetters.map { firstLetter in return self.filteredUsers .filter { $0.titleFirstLetter == firstLetter } .sorted { $0.name ?? "" < $1.name ?? "" } } } fileprivate func setupMainView() { definesPresentationContext = true view.backgroundColor = ThemeManager.currentTheme().generalBackgroundColor } func setupNavigationItemTitle(title: String) { navigationItem.title = title } func setupRightBarButton(with title: String) { if #available(iOS 11.0, *) { let rightBarButton = UIButton(type: .system) rightBarButton.setTitle(title, for: .normal) rightBarButton.titleLabel?.font = UIFont.systemFont(ofSize: 17) rightBarButton.addTarget(self, action: #selector(rightBarButtonTapped), for: .touchUpInside) navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBarButton) } else { navigationItem.rightBarButtonItem = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(rightBarButtonTapped)) } navigationItem.rightBarButtonItem?.isEnabled = false } @objc func rightBarButtonTapped() { } func createGroup() { let destination = GroupProfileTableViewController() destination.selectedFlaconUsers = selectedFalconUsers navigationController?.pushViewController(destination, animated: true) } var chatIDForUsersUpdate = String() var informationMessageSender = InformationMessageSender() func addNewMembers() { ARSLineProgress.ars_showOnView(view) navigationController?.view.isUserInteractionEnabled = false let reference = Database.database().reference().child("groupChats").child(chatIDForUsersUpdate).child(messageMetaDataFirebaseFolder).child("chatParticipantsIDs") reference.observeSingleEvent(of: .value) { (snapshot) in guard let dictionary = snapshot.value as? [String: AnyObject] else { return } guard var membersIDs = Array(dictionary.values) as? [String] else { return } var values = [String: AnyObject]() var selectedUserNames = [String]() for selectedUser in self.selectedFalconUsers { guard let selectedID = selectedUser.id, let selectedUserName = selectedUser.name else { continue } values.updateValue(selectedID as AnyObject, forKey: selectedID) selectedUserNames.append(selectedUserName) membersIDs.append(selectedID) } reference.updateChildValues(values, withCompletionBlock: { (_, _) in let userNamesString = selectedUserNames.joined(separator: ", ") let usersTitleString = selectedUserNames.count > 1 ? "users" : "user" let text = "Admin added \(usersTitleString) \(userNamesString) to the group" self.informationMessageSender.sendInformatoinMessage(chatID: self.chatIDForUsersUpdate, membersIDs: membersIDs, text: text) ARSLineProgress.showSuccess() self.navigationController?.view.isUserInteractionEnabled = true self.navigationController?.popViewController(animated: true) }) } } fileprivate func setupTableView() { if #available(iOS 11.0, *) { navigationItem.largeTitleDisplayMode = .never } view.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false tableView.topAnchor.constraint(equalTo: selectedParticipantsCollectionView.bottomAnchor).isActive = true if #available(iOS 11.0, *) { tableView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 0).isActive = true tableView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: 0).isActive = true tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true } else { tableView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true tableView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true } tableView.delegate = self tableView.dataSource = self tableView.indicatorStyle = ThemeManager.currentTheme().scrollBarStyle tableView.sectionIndexBackgroundColor = view.backgroundColor tableView.backgroundColor = view.backgroundColor tableView.allowsMultipleSelection = true tableView.allowsSelection = true tableView.allowsSelectionDuringEditing = true tableView.allowsMultipleSelectionDuringEditing = true tableView.setEditing(true, animated: false) tableView.register(ParticipantTableViewCell.self, forCellReuseIdentifier: falconUsersCellID) tableView.separatorStyle = .none } fileprivate func setupCollectionView() { selectedParticipantsCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: alignedFlowLayout) view.addSubview(selectedParticipantsCollectionView) selectedParticipantsCollectionView.translatesAutoresizingMaskIntoConstraints = false selectedParticipantsCollectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true collectionViewHeightAnchor = selectedParticipantsCollectionView.heightAnchor.constraint(equalToConstant: 0) collectionViewHeightAnchor.priority = UILayoutPriority(rawValue: 999) collectionViewHeightAnchor.isActive = true if #available(iOS 11.0, *) { selectedParticipantsCollectionView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 0).isActive = true selectedParticipantsCollectionView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: 0).isActive = true } else { selectedParticipantsCollectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true selectedParticipantsCollectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true } selectedParticipantsCollectionView.delegate = self selectedParticipantsCollectionView.dataSource = self selectedParticipantsCollectionView.showsVerticalScrollIndicator = true selectedParticipantsCollectionView.showsHorizontalScrollIndicator = false selectedParticipantsCollectionView.alwaysBounceVertical = true selectedParticipantsCollectionView.backgroundColor = .clear selectedParticipantsCollectionView.register(SelectedParticipantsCollectionViewCell.self, forCellWithReuseIdentifier: selectedParticipantsCollectionViewCellID) selectedParticipantsCollectionView.decelerationRate = UIScrollView.DecelerationRate.fast selectedParticipantsCollectionView.isScrollEnabled = true selectedParticipantsCollectionView.contentInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) alignedFlowLayout.minimumInteritemSpacing = 5 alignedFlowLayout.minimumLineSpacing = 5 alignedFlowLayout.estimatedItemSize = CGSize(width: 100, height: 32) } fileprivate func setupSearchController() { searchBar = UISearchBar() searchBar?.delegate = self searchBar?.searchBarStyle = .minimal searchBar?.changeBackgroundColor(to: ThemeManager.currentTheme().searchBarColor) searchBar?.placeholder = "Search" searchBar?.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 50) tableView.tableHeaderView = searchBar } func reloadCollectionView() { if #available(iOS 11.0, *) { DispatchQueue.main.async { self.selectedParticipantsCollectionView.reloadData() } } else { DispatchQueue.main.async { UIView.performWithoutAnimation { self.selectedParticipantsCollectionView.reloadSections([0]) } } } if selectedFalconUsers.count == 0 { collectionViewHeightAnchor.constant = 0 UIView.animate(withDuration: 0.3) { self.view.layoutIfNeeded() } self.navigationItem.rightBarButtonItem?.isEnabled = false return } navigationItem.rightBarButtonItem?.isEnabled = true if selectedFalconUsers.count == 1 { collectionViewHeightAnchor.constant = 75 UIView.animate(withDuration: 0.3) { self.view.layoutIfNeeded() } return } } func didSelectUser(at indexPath: IndexPath) { let user = sections[indexPath.section][indexPath.row] if let filteredUsersIndex = filteredUsers.firstIndex(of: user) { filteredUsers[filteredUsersIndex].isSelected = true } if let usersIndex = users.firstIndex(of: user) { users[usersIndex].isSelected = true } sections[indexPath.section][indexPath.row].isSelected = true selectedFalconUsers.append(sections[indexPath.section][indexPath.row]) DispatchQueue.main.async { self.reloadCollectionView() } } func didDeselectUser(at indexPath: IndexPath) { let user = sections[indexPath.section][indexPath.row] if let findex = filteredUsers.firstIndex(of: user) { filteredUsers[findex].isSelected = false } if let index = users.firstIndex(of: user) { users[index].isSelected = false } if let selectedFalconUserIndexInCollectionView = selectedFalconUsers.firstIndex(of: user) { selectedFalconUsers[selectedFalconUserIndexInCollectionView].isSelected = false selectedFalconUsers.remove(at: selectedFalconUserIndexInCollectionView) DispatchQueue.main.async { self.reloadCollectionView() } } sections[indexPath.section][indexPath.row].isSelected = false } }
37.567398
165
0.735564
234091cc6439ab11bd03daf5c6648081fbd9a011
3,450
// // CalculateTotalPriceResponseModel.swift // OtiNetwork // // Created by odeon on 1.07.2021. // import UIKit import ObjectMapper public class CalculateTotalPriceResponseModel: Mappable { public var totalAmount : Double? public var excursionsTotalAmount : Double? public var exrasTotalAmount : Double? public var currencyId : Int? public var currency : String? public var tourPlanId : Int? public var tourists : [TouristsList]? public var globalExtras : String? public var summary : Summary? public required init?(map: Map) { } public func mapping(map: Map) { totalAmount <- map["TotalAmount"] excursionsTotalAmount <- map["ExcursionsTotalAmount"] exrasTotalAmount <- map["ExrasTotalAmount"] currencyId <- map["CurrencyId"] currency <- map["Currency"] tourPlanId <- map["TourPlanId"] tourists <- map["Tourists"] globalExtras <- map["GlobalExtras"] summary <- map["Summary"] } } public class ExtrasList: Mappable,Decodable,Encodable { public var extraId : Int? public var priceId : Int? public var priceName : String? public var priceType : Int? public var amount : Double? public var extraTotalPaxCount : Int? public required init?(map: Map) { } public func mapping(map: Map) { extraId <- map["ExtraId"] priceId <- map["PriceId"] priceName <- map["PriceName"] priceType <- map["PriceType"] amount <- map["Amount"] extraTotalPaxCount <- map["ExtraTotalPaxCount"] } } public class Summary: Mappable,Decodable,Encodable { public var id : Int? public var importantNotes : String? public var excursionName : String? public var excursionLocalName : String? public var excursionType : String? public var excursionTypeKey : Int? public var includedServices : String? public var exculededServices : String? public var cancellationPolicy : String? public var height : Bool? public var serviceLanguageTrans : String? public var languageCode : String? public required init?(map: Map) { } public func mapping(map: Map) { id <- map["id"] importantNotes <- map["importantNotes"] excursionName <- map["excursionName"] excursionLocalName <- map["excursionLocalName"] excursionType <- map["excursionType"] excursionTypeKey <- map["excursionTypeKey"] includedServices <- map["includedServices"] exculededServices <- map["exculededServices"] cancellationPolicy <- map["cancellationPolicy"] height <- map["height"] serviceLanguageTrans <- map["serviceLanguageTrans"] languageCode <- map["languageCode"] } } public class TouristsList: Mappable,Decodable,Encodable { public var birthday : String? public var amount : Double? public var touristId : Int? public var reservationNo : String? public var type : Int? public var typeName : String? public var extras : [ExtrasList]? public required init?(map: Map) { } public func mapping(map: Map) { birthday <- map["Birthday"] amount <- map["Amount"] touristId <- map["TouristId"] reservationNo <- map["ReservationNo"] type <- map["Type"] typeName <- map["TypeName"] extras <- map["Extras"] } }
27.380952
61
0.638551
d654abd120b3c147175e2627433d90bdba5dd0ae
2,687
import SwiftUI struct ContentView: View { let calc = [["(",")","q","w","e","r","t","y","u","i","o","p","[","]"],["a","s","d","f","g","h","j","k","l",";","'","return"],["1/x","2√x","3√x","y√x","In","log10","4","5","6","-"]] var body: some View { ZStack { Color(.black) VStack(spacing:-29) { ForEach(calc, id: \.self) { column in HStack (spacing: 3) { ForEach(column, id: \.self) { row in Button() { } label: { if row != "0" { ZStack { if ["=","+","-","×","÷"].contains(row) { Color.init(red: 155.0, green: 0.0, blue: 20.0) } else if ["AC","+/-","%"] .contains(row) { Color.init(red: 00.0, green: 50.0, blue: 100.0) } else if ["1","2","3","4","5","6","7","8","9","."].contains(row) { Color.red }else{ Color.green } Text("\(row)") .font(.title) } .frame(width: 70, height: 70) .clipShape(RoundedRectangle(cornerRadius: 40)) .shadow(radius: 5) } else if row == "0" { ZStack { Color.red Text("\(row)") .font(.title) } .frame(width: 146, height: 70) .clipShape(RoundedRectangle(cornerRadius: 40)) .shadow(radius: 5) } } } }.padding() } } } .ignoresSafeArea() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() .previewInterfaceOrientation(.portraitUpsideDown) } }
47.140351
184
0.261258
76946fcde1b04fb7b2916262f8ee4383d05d67ff
985
// // __GrayImageTests.swift // 3-GrayImageTests // // Created by FlyElephant on 17/1/18. // Copyright © 2017年 FlyElephant. All rights reserved. // import XCTest @testable import __GrayImage class __GrayImageTests: 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. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.621622
111
0.638579
dee388eec1f503a122c176cdfb3a155132e56dbd
23,239
// // SettingsViewController.swift // HomeAssistant // // Created by Robert Trencheny on 4/20/19. // Copyright © 2019 Robbie Trencheny. All rights reserved. // import Foundation import UIKit import Eureka import Shared import RealmSwift #if !targetEnvironment(macCatalyst) import Lokalise #endif import ZIPFoundation import UserNotifications import Firebase import WebKit import MBProgressHUD import PromiseKit import XCGLogger import Sentry // swiftlint:disable:next type_body_length class SettingsViewController: FormViewController { private var shakeCount = 0 private var maxShakeCount = 3 // swiftlint:disable:next function_body_length cyclomatic_complexity override func viewDidLoad() { super.viewDidLoad() self.becomeFirstResponder() title = L10n.Settings.NavigationBar.title ButtonRow.defaultCellSetup = { cell, row in cell.accessibilityIdentifier = row.tag cell.accessibilityLabel = row.title } LabelRow.defaultCellSetup = { cell, row in cell.accessibilityIdentifier = row.tag cell.accessibilityLabel = row.title } if !Current.isCatalyst { // About is in the Application menu on Catalyst, and closing the button is direct let aboutButton = UIBarButtonItem(title: L10n.Settings.NavigationBar.AboutButton.title, style: .plain, target: self, action: #selector(SettingsViewController.openAbout(_:))) self.navigationItem.setLeftBarButton(aboutButton, animated: true) } if !Current.sceneManager.supportsMultipleScenes || !Current.isCatalyst { let closeSelector = #selector(SettingsViewController.closeSettings(_:)) let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: closeSelector) self.navigationItem.setRightBarButton(doneButton, animated: true) } form +++ HomeAssistantAccountRow { $0.value = .init( user: Current.settingsStore.authenticatedUser, locationName: prefs.string(forKey: "location_name") ) $0.presentationMode = .show(controllerProvider: ControllerProvider.callback { return ConnectionSettingsViewController() }, onDismiss: nil) } form +++ Section() <<< ButtonRow("generalSettings") { $0.title = L10n.Settings.GeneralSettingsButton.title $0.presentationMode = .show(controllerProvider: ControllerProvider.callback { let view = SettingsDetailViewController() view.detailGroup = "general" return view }, onDismiss: nil) } <<< ButtonRow("locationSettings") { $0.title = L10n.Settings.DetailsSection.LocationSettingsRow.title $0.presentationMode = .show(controllerProvider: ControllerProvider.callback { let view = SettingsDetailViewController() view.detailGroup = "location" return view }, onDismiss: nil) } <<< ButtonRow("notificationSettings") { $0.title = L10n.Settings.DetailsSection.NotificationSettingsRow.title $0.presentationMode = .show(controllerProvider: .callback { return NotificationSettingsViewController() }, onDismiss: nil) } <<< ButtonRow { $0.title = L10n.SettingsSensors.title $0.presentationMode = .show(controllerProvider: .callback { SensorListViewController() }, onDismiss: nil) } +++ Section(L10n.Settings.DetailsSection.Integrations.header) <<< ButtonRow { $0.tag = "actions" $0.title = L10n.SettingsDetails.Actions.title $0.presentationMode = .show(controllerProvider: ControllerProvider.callback { let view = SettingsDetailViewController() view.detailGroup = "actions" return view }, onDismiss: { _ in }) } <<< ButtonRow { $0.tag = "watch" $0.hidden = .isCatalyst $0.title = L10n.Settings.DetailsSection.WatchRow.title $0.presentationMode = .show(controllerProvider: ControllerProvider.callback { return ComplicationListViewController() }, onDismiss: { _ in }) } <<< ButtonRow { $0.title = L10n.Nfc.List.title if #available(iOS 13, *) { $0.hidden = .isCatalyst $0.presentationMode = .show(controllerProvider: ControllerProvider.callback { return NFCListViewController() }, onDismiss: nil) } else { $0.hidden = true } } +++ ButtonRow("privacy") { $0.title = L10n.SettingsDetails.Privacy.title $0.presentationMode = .show(controllerProvider: .callback { let view = SettingsDetailViewController() view.detailGroup = "privacy" return view }, onDismiss: nil) } +++ ButtonRow("eventLog") { $0.title = L10n.Settings.EventLog.title let scene = StoryboardScene.ClientEvents.self let controllerProvider = ControllerProvider.storyBoard( storyboardId: scene.clientEventsList.identifier, storyboardName: scene.storyboardName, bundle: Bundle.main ) $0.presentationMode = .show(controllerProvider: controllerProvider, onDismiss: { vc in _ = vc.navigationController?.popViewController(animated: true) }) } <<< ButtonRow { if Current.isCatalyst { $0.title = L10n.Settings.Developer.ShowLogFiles.title } else { $0.title = L10n.Settings.Developer.ExportLogFiles.title } }.onCellSelection { cell, _ in Current.Log.verbose("Logs directory is: \(Constants.LogsDirectory)") guard !Current.isCatalyst else { // on Catalyst we can just open the directory to get to Finder UIApplication.shared.open(Constants.LogsDirectory, options: [:]) { success in Current.Log.info("opened log directory: \(success)") } return } let fileManager = FileManager.default let fileName = DateFormatter(withFormat: "yyyy-MM-dd'T'HHmmssZ", locale: "en_US_POSIX").string(from: Date()) + "_logs.zip" Current.Log.debug("Exporting logs as filename \(fileName)") if let zipDest = fileManager.containerURL(forSecurityApplicationGroupIdentifier: Constants.AppGroupID)? .appendingPathComponent(fileName, isDirectory: false) { _ = try? fileManager.removeItem(at: zipDest) guard let archive = Archive(url: zipDest, accessMode: .create) else { fatalError("Unable to create ZIP archive!") } guard let backupURL = Realm.backup() else { fatalError("Unable to backup Realm!") } do { try archive.addEntry(with: backupURL.lastPathComponent, relativeTo: backupURL.deletingLastPathComponent()) } catch { Current.Log.error("Error adding Realm backup to archive!") } if let logFiles = try? fileManager.contentsOfDirectory(at: Constants.LogsDirectory, includingPropertiesForKeys: nil) { for logFile in logFiles { do { try archive.addEntry(with: logFile.lastPathComponent, relativeTo: logFile.deletingLastPathComponent()) } catch { Current.Log.error("Error adding log \(logFile) to archive!") } } } let activityViewController = UIActivityViewController(activityItems: [zipDest], applicationActivities: nil) activityViewController.completionWithItemsHandler = { type, completed, _, _ in let didCancelEntirely = type == nil && !completed let didCompleteEntirely = completed if didCancelEntirely || didCompleteEntirely { try? fileManager.removeItem(at: zipDest) } } self.present(activityViewController, animated: true, completion: {}) if let popOver = activityViewController.popoverPresentationController { popOver.sourceView = cell } } } +++ Section { $0.tag = "reset" // $0.hidden = Condition(booleanLiteral: !self.configured) } <<< ButtonRow("resetApp") { $0.title = L10n.Settings.ResetSection.ResetRow.title }.cellUpdate { cell, _ in cell.textLabel?.textColor = .red }.onCellSelection { cell, row in let alert = UIAlertController(title: L10n.Settings.ResetSection.ResetAlert.title, message: L10n.Settings.ResetSection.ResetAlert.message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: L10n.cancelLabel, style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: L10n.Settings.ResetSection.ResetAlert.title, style: .destructive, handler: { (_) in row.hidden = true row.evaluateHidden() self.ResetApp() })) self.present(alert, animated: true, completion: nil) alert.popoverPresentationController?.sourceView = cell.formViewController()?.view } <<< ButtonRow("resetWebData") { $0.title = L10n.Settings.ResetSection.ResetWebCache.title }.cellUpdate { cell, _ in cell.textLabel?.textColor = .red }.onCellSelection { _, _ in WKWebsiteDataStore.default().removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: Date(timeIntervalSince1970: 0), completionHandler: { Current.Log.verbose("Reset browser caches!") }) } +++ Section(header: L10n.Settings.Developer.header, footer: L10n.Settings.Developer.footer) { $0.hidden = Condition(booleanLiteral: (Current.appConfiguration.rawValue > 1)) $0.tag = "developerOptions" } <<< ButtonRow("onboardTest") { $0.title = "Onboard" $0.presentationMode = .presentModally(controllerProvider: .storyBoard(storyboardId: "navController", storyboardName: "Onboarding", bundle: Bundle.main), onDismiss: nil) }.cellUpdate { cell, _ in cell.textLabel?.textAlignment = .center cell.accessoryType = .none cell.editingAccessoryType = cell.accessoryType cell.textLabel?.textColor = cell.tintColor.withAlphaComponent(1.0) } <<< ButtonRow { $0.title = L10n.Settings.Developer.SyncWatchContext.title }.onCellSelection { cell, _ in if let syncError = HomeAssistantAPI.SyncWatchContext() { let alert = UIAlertController(title: L10n.errorLabel, message: syncError.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: L10n.okLabel, style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) alert.popoverPresentationController?.sourceView = cell.formViewController()?.view } } <<< ButtonRow { $0.title = L10n.Settings.Developer.CopyRealm.title }.onCellSelection { cell, _ in guard let backupURL = Realm.backup() else { fatalError("Unable to get Realm backup") } let containerRealmPath = Realm.Configuration.defaultConfiguration.fileURL! Current.Log.verbose("Would copy from \(backupURL) to \(containerRealmPath)") if FileManager.default.fileExists(atPath: containerRealmPath.path) { do { _ = try FileManager.default.removeItem(at: containerRealmPath) } catch let error { Current.Log.error("Error occurred, here are the details:\n \(error)") } } do { _ = try FileManager.default.copyItem(at: backupURL, to: containerRealmPath) } catch let error as NSError { // Catch fires here, with an NSError being thrown Current.Log.error("Error occurred, here are the details:\n \(error)") } let msg = L10n.Settings.Developer.CopyRealm.Alert.message(backupURL.path, containerRealmPath.path) let alert = UIAlertController(title: L10n.Settings.Developer.CopyRealm.Alert.title, message: msg, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: L10n.okLabel, style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) alert.popoverPresentationController?.sourceView = cell.formViewController()?.view } <<< ButtonRow { $0.title = L10n.Settings.Developer.DebugStrings.title }.onCellSelection { cell, _ in prefs.set(!prefs.bool(forKey: "showTranslationKeys"), forKey: "showTranslationKeys") let alert = UIAlertController(title: L10n.okLabel, message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction(title: L10n.okLabel, style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) alert.popoverPresentationController?.sourceView = cell.formViewController()?.view } <<< ButtonRow("camera_notification_test") { $0.title = L10n.Settings.Developer.CameraNotification.title }.onCellSelection { _, _ in SettingsViewController.showCameraContentExtension() } <<< ButtonRow("map_notification_test") { $0.title = L10n.Settings.Developer.MapNotification.title }.onCellSelection { _, _ in SettingsViewController.showMapContentExtension() } <<< ButtonRow { $0.title = L10n.Settings.Developer.CrashlyticsTest.NonFatal.title }.onCellSelection { cell, _ in let alert = UIAlertController(title: L10n.Settings.Developer.CrashlyticsTest.NonFatal.Notification.title, message: L10n.Settings.Developer.CrashlyticsTest.NonFatal.Notification.body, preferredStyle: .alert) alert.addAction(UIAlertAction(title: L10n.okLabel, style: .default, handler: { (_) in let userInfo = [ NSLocalizedDescriptionKey: NSLocalizedString("The request failed.", comment: ""), NSLocalizedFailureReasonErrorKey: NSLocalizedString("The response returned a 404.", comment: ""), NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString("Does this page exist?", comment: ""), "ProductID": "123456", "View": "MainView" ] let error = NSError(domain: NSCocoaErrorDomain, code: -1001, userInfo: userInfo) Current.crashReporter.logError(error) })) self.present(alert, animated: true, completion: nil) alert.popoverPresentationController?.sourceView = cell.formViewController()?.view } <<< ButtonRow { $0.title = L10n.Settings.Developer.CrashlyticsTest.Fatal.title }.onCellSelection { cell, _ in let alert = UIAlertController(title: L10n.Settings.Developer.CrashlyticsTest.Fatal.Notification.title, message: L10n.Settings.Developer.CrashlyticsTest.Fatal.Notification.body, preferredStyle: .alert) alert.addAction(UIAlertAction(title: L10n.okLabel, style: .default, handler: { (_) in SentrySDK.crash() })) self.present(alert, animated: true, completion: nil) alert.popoverPresentationController?.sourceView = cell.formViewController()?.view } <<< SwitchRow { $0.title = L10n.Settings.Developer.AnnoyingBackgroundNotifications.title $0.value = prefs.bool(forKey: XCGLogger.shouldNotifyUserDefaultsKey) $0.onChange { row in prefs.set(row.value ?? false, forKey: XCGLogger.shouldNotifyUserDefaultsKey) } } } @objc func openAbout(_ sender: UIButton) { let aboutView = AboutViewController() let navController = UINavigationController(rootViewController: aboutView) self.show(navController, sender: nil) } @objc func closeSettings(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } func ResetApp() { Current.Log.verbose("Resetting app!") let hud = MBProgressHUD.showAdded(to: view, animated: true) hud.label.text = L10n.Settings.ResetSection.ResetAlert.progressMessage hud.show(animated: true) let waitAtLeast = after(seconds: 3.0) firstly { race( Current.tokenManager?.revokeToken().asVoid().recover { _ in () } ?? .value(()), after(seconds: 10.0) ) }.then { waitAtLeast }.done { hud.hide(animated: true) resetStores() setDefaults() let bundleId = Bundle.main.bundleIdentifier! UserDefaults.standard.removePersistentDomain(forName: bundleId) UserDefaults.standard.synchronize() prefs.removePersistentDomain(forName: bundleId) prefs.synchronize() Current.onboardingObservation.needed(.logout) } } override var canBecomeFirstResponder: Bool { return true } override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { if motion == .motionShake { Current.Log.verbose("shake!") if shakeCount >= maxShakeCount { if let section = self.form.sectionBy(tag: "developerOptions") { section.hidden = false section.evaluateHidden() self.tableView.reloadData() let alert = UIAlertController(title: "You did it!", message: "Developer functions unlocked", preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: L10n.okLabel, style: UIAlertAction.Style.default, handler: nil)) self.present(alert, animated: true, completion: nil) alert.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem } return } shakeCount += 1 } } static func showMapContentExtension() { let content = UNMutableNotificationContent() content.body = L10n.Settings.Developer.MapNotification.Notification.body content.sound = .default var firstPinLatitude = "40.785091" var firstPinLongitude = "-73.968285" if Current.appConfiguration == .FastlaneSnapshot, let lat = prefs.string(forKey: "mapPin1Latitude"), let lon = prefs.string(forKey: "mapPin1Longitude") { firstPinLatitude = lat firstPinLongitude = lon } var secondPinLatitude = "40.758896" var secondPinLongitude = "-73.985130" if Current.appConfiguration == .FastlaneSnapshot, let lat = prefs.string(forKey: "mapPin2Latitude"), let lon = prefs.string(forKey: "mapPin2Longitude") { secondPinLatitude = lat secondPinLongitude = lon } content.userInfo = [ "homeassistant": [ "latitude": firstPinLatitude, "longitude": firstPinLongitude, "second_latitude": secondPinLatitude, "second_longitude": secondPinLongitude ] ] content.categoryIdentifier = "map" let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let notificationRequest = UNNotificationRequest(identifier: "mapContentExtension", content: content, trigger: trigger) UNUserNotificationCenter.current().add(notificationRequest) } static func showCameraContentExtension() { let content = UNMutableNotificationContent() content.body = L10n.Settings.Developer.CameraNotification.Notification.body content.sound = .default var entityID = "camera.amcrest_camera" if Current.appConfiguration == .FastlaneSnapshot, let snapshotEntityID = prefs.string(forKey: "cameraEntityID") { entityID = snapshotEntityID } content.userInfo = ["entity_id": entityID] content.categoryIdentifier = "camera" let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let notificationRequest = UNNotificationRequest(identifier: "cameraContentExtension", content: content, trigger: trigger) UNUserNotificationCenter.current().add(notificationRequest) } // swiftlint:disable:next file_length }
41.721724
119
0.568226
913a8373e48aa5cbd7da2be4845dbd741db9a02e
1,002
// // ParseChatTests.swift // ParseChatTests // // Created by Raquel Figueroa-Opperman on 2/25/18. // Copyright © 2018 Raquel Figueroa-Opperman. All rights reserved. // import XCTest @testable import ParseChat class ParseChatTests: 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. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
27.081081
111
0.641717
d747c0b3b92f25adceeba0b50c7ef5705b4c1c24
1,310
import Foundation public struct SwiftXorGenerator: SwiftCipherContentsGenerating { public func variableValue(for secret: Secret, config: SwiftConfig) -> String { let salt = [UInt8].random(length: 64) let xoredValue = xorEncode(secret: secret.value, salt: salt) return "\(config.typeName)._xored(\(xoredValue), salt: \(salt))" } public func neededHelperFunctions() -> [String] { return [""" private static func _xored(_ secret: [UInt8], salt: [UInt8]) -> String { return String(bytes: secret.enumerated().map { index, character in return character ^ salt[index % salt.count] }, encoding: .utf8) ?? "" } """] } public func neededImports() -> [String] { return ["Foundation"] } private func xorEncode(secret: String, salt: [UInt8]) -> [UInt8] { let secretBytes = [UInt8](secret.utf8) return secretBytes.enumerated().map { index, character in return character ^ salt[index % salt.count] } } private func xorDecode(encoded secretBytes: [UInt8], salt: [UInt8]) -> String { return String(bytes: secretBytes.enumerated().map { index, character in return character ^ salt[index % salt.count] }, encoding: .utf8) ?? "" } }
34.473684
83
0.61145
e63cd2f0e8ebf1453f7bd1a88427c258ed26cbb6
5,676
// // Copyright © FINN.no AS, Inc. All rights reserved. // import FinniversKit final class ListFilterCell: CheckboxTableViewCell { private lazy var checkboxImageView = ListFilterImageView(withAutoLayout: true) private lazy var overlayView: UIView = { let view = UIView(withAutoLayout: true) view.backgroundColor = Theme.mainBackground.withAlphaComponent(0.5) view.isHidden = true return view }() // MARK: - Init override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Overrides override func layoutSubviews() { super.layoutSubviews() layoutAccessoryView() } override func prepareForReuse() { super.prepareForReuse() accessoryView = nil } override func setSelected(_ selected: Bool, animated: Bool) { let isCheckboxHighlighted = checkbox.isHighlighted super.setSelected(selected, animated: animated) checkbox.isHighlighted = isCheckboxHighlighted showSelectedBackground(selected) } override func setHighlighted(_ highlighted: Bool, animated: Bool) { let isCheckboxHighlighted = checkbox.isHighlighted super.setHighlighted(highlighted, animated: animated) checkbox.isHighlighted = isCheckboxHighlighted showSelectedBackground(highlighted) } override func animateSelection(isSelected: Bool) { super.animateSelection(isSelected: isSelected) updateAccessibilityLabel(isSelected: isSelected) showSelectedBackground(!isSelected) let animation = CABasicAnimation(keyPath: "opacity") animation.duration = 0.2 animation.fromValue = 1 animation.toValue = isSelected ? 1 : 0 animation.autoreverses = false animation.repeatCount = 1 animation.isRemovedOnCompletion = false selectedBackgroundView?.layer.add(animation, forKey: nil) } // MARK: - Setup func configure(with viewModel: ListFilterCellViewModel) { super.configure(with: viewModel) backgroundColor = Theme.mainBackground selectionStyle = .none switch viewModel.accessoryStyle { case .external: let accessoryView = UIImageView(image: UIImage(named: .webview).withRenderingMode(.alwaysTemplate)) accessoryView.tintColor = .chevron self.accessoryView = accessoryView case .none: accessoryView = UIView() case .chevron: break } detailLabelTrailingConstraint.constant = detailLabelConstraint(constantFor: viewModel.accessoryStyle) switch viewModel.checkboxStyle { case .selectedBordered: checkboxImageView.setImage(UIImage(named: .checkboxBordered), for: .normal) checkboxImageView.setImage(UIImage(named: .checkboxBorderedDisabled), for: .disabled) case .selectedFilled: checkboxImageView.setImage(nil, for: .normal) checkboxImageView.setImage(UIImage(named: .checkboxFilledDisabled), for: .disabled) case .deselected: checkboxImageView.setImage(nil, for: .normal, .disabled) } isUserInteractionEnabled = viewModel.isEnabled checkboxImageView.isEnabled = viewModel.isEnabled overlayView.isHidden = viewModel.isEnabled bringSubviewToFront(overlayView) updateAccessibilityLabel(isSelected: viewModel.checkboxStyle != .deselected) if let selectedBackgroundView = selectedBackgroundView, selectedBackgroundView.superview == nil { selectedBackgroundView.alpha = 0 insertSubview(selectedBackgroundView, at: 0) } detailLabel.adjustsFontForContentSizeCategory = true subtitleLabel.adjustsFontForContentSizeCategory = true } private func setup() { titleLabel.font = .bodyRegular titleLabel.adjustsFontForContentSizeCategory = true addSubview(overlayView) checkbox.addSubview(checkboxImageView) let verticalSpacing: CGFloat = 14 stackViewTopAnchorConstraint.constant = verticalSpacing stackViewBottomAnchorConstraint.constant = -verticalSpacing checkboxImageView.fillInSuperview() NSLayoutConstraint.activate([ overlayView.topAnchor.constraint(equalTo: topAnchor), overlayView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -1), overlayView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor), overlayView.trailingAnchor.constraint(equalTo: trailingAnchor), ]) } // MARK: - Private methods private func updateAccessibilityLabel(isSelected: Bool) { let accessibilityLabels = [ isSelected ? "selected".localized() : nil, titleLabel.text, subtitleLabel.text, detailLabel.text.map { $0 + " " + "numberOfResults".localized() }, ] accessibilityLabel = accessibilityLabels.compactMap { $0 }.joined(separator: ", ") } private func detailLabelConstraint(constantFor accessoryStyle: ListFilterCellViewModel.AccessoryStyle) -> CGFloat { guard #available(iOS 13, *), accessoryStyle == .chevron else { return 0 } return -.spacingS } private func showSelectedBackground(_ show: Bool) { selectedBackgroundView?.layer.removeAllAnimations() selectedBackgroundView?.alpha = show ? 1 : 0 } }
35.254658
119
0.680233
67ff6b97117c4571323e4785817ea8c7e7f0bdba
4,543
public protocol SoulContactsServiceProtocol { // POST: /contacts/requests func sendContactRequest(userId: String, completion: @escaping SoulResult<ContactRequest>.Completion) // POST: /contacts/requests/{requestId}/cancel func cancelContactRequest(requestId: String, completion: @escaping SoulResult<Void>.Completion) // POST: /contacts/requests/{requestId}/approve func approveContactRequest(requestId: String, completion: @escaping SoulResult<Void>.Completion) // POST: /contacts/requests/{requestId}/decline func declineContactRequest(requestId: String, completion: @escaping SoulResult<Void>.Completion) // PATCH /contacts/{userId} func editContactName(userId: String, nickname: String, completion: @escaping SoulResult<Void>.Completion) // DELETE: /contacts/{userId} func deleteContact(userId: String, completion: @escaping SoulResult<Void>.Completion) // GET: /contacts/requests/last_sent/{chat_id} func lastSentRequest(chatId: String, completion: @escaping SoulResult<ContactRequest?>.Completion) } final class SoulContactsService: SoulContactsServiceProtocol { let soulProvider: SoulProviderProtocol init(soulProvider: SoulProviderProtocol) { self.soulProvider = soulProvider } func sendContactRequest(userId: String, completion: @escaping SoulResult<ContactRequest>.Completion) { var request = SoulRequest( httpMethod: .POST, soulEndpoint: SoulContactsEndpoint.sendContactRequest, needAuthorization: true ) request.setBodyParameters(["userId": userId]) soulProvider.request(request) { (result: Result<SoulResponse, SoulSwiftError>) in completion(result.map { $0.request }) } } func cancelContactRequest(requestId: String, completion: @escaping SoulResult<Void>.Completion) { var request = SoulRequest( httpMethod: .POST, soulEndpoint: SoulContactsEndpoint.cancelContactRequest(requestId: requestId), needAuthorization: true ) soulProvider.request(request) { (result: Result<EmptyResponse, SoulSwiftError>) in completion(result.map { _ in }) } } func approveContactRequest(requestId: String, completion: @escaping SoulResult<Void>.Completion) { var request = SoulRequest( httpMethod: .POST, soulEndpoint: SoulContactsEndpoint.approveContactRequest(requestId: requestId), needAuthorization: true ) soulProvider.request(request) { (result: Result<EmptyResponse, SoulSwiftError>) in completion(result.map { _ in }) } } func declineContactRequest(requestId: String, completion: @escaping SoulResult<Void>.Completion) { var request = SoulRequest( httpMethod: .POST, soulEndpoint: SoulContactsEndpoint.declineContactRequest(requestId: requestId), needAuthorization: true ) soulProvider.request(request) { (result: Result<EmptyResponse, SoulSwiftError>) in completion(result.map { _ in }) } } func editContactName(userId: String, nickname: String, completion: @escaping SoulResult<Void>.Completion) { var request = SoulRequest( httpMethod: .PATCH, soulEndpoint: SoulContactsEndpoint.editContactName(userId: userId), needAuthorization: true ) request.setBodyParameters(["nickname": nickname]) soulProvider.request(request) { (result: Result<EmptyResponse, SoulSwiftError>) in completion(result.map { _ in }) } } func deleteContact(userId: String, completion: @escaping SoulResult<Void>.Completion) { var request = SoulRequest( httpMethod: .DELETE, soulEndpoint: SoulContactsEndpoint.deleteContact(userId: userId), needAuthorization: true ) soulProvider.request(request) { (result: Result<EmptyResponse, SoulSwiftError>) in completion(result.map { _ in }) } } func lastSentRequest(chatId: String, completion: @escaping SoulResult<ContactRequest?>.Completion) { var request = SoulRequest( httpMethod: .GET, soulEndpoint: SoulContactsEndpoint.lastSentRequest(chatId: chatId), needAuthorization: true ) soulProvider.request(request) { (result: Result<SoulResponse, SoulSwiftError>) in completion(result.map { $0.request }) } } }
43.266667
111
0.677746
cc63bc2de04e1af5387658cdf8454e455d9346ed
1,254
// // GetChatWidgetOperation.swift // MobileMessaging // // Created by okoroleva on 24.04.2020. // import Foundation class GetChatWidgetOperation: MMOperation { let mmContext: MobileMessaging let finishBlock: ((NSError?, ChatWidget?) -> Void) var operationResult = GetChatWidgetResult.Cancel init(mmContext: MobileMessaging, finishBlock: @escaping ((NSError?, ChatWidget?) -> Void)) { self.mmContext = mmContext self.finishBlock = finishBlock super.init(isUserInitiated: false) self.addCondition(HealthyRegistrationCondition(mmContext: mmContext)) } override func execute() { guard !isCancelled else { logDebug("cancelled...") finish() return } logDebug("Started...") performRequest() } private func performRequest() { mmContext.remoteApiProvider.getChatWidget(applicationCode: mmContext.applicationCode, pushRegistrationId: mmContext.currentInstallation().pushRegistrationId, queue: underlyingQueue) { (result) in self.operationResult = result self.finishWithError(result.error) } } override func finished(_ errors: [NSError]) { assert(userInitiated == Thread.isMainThread) logDebug("finished with errors: \(errors)") finishBlock(errors.first, operationResult.value?.widget) } }
27.26087
203
0.744817
abacaf01bba6e894303b8507cf5cfd6016027bc7
82
import UIKit class ___VARIABLE_sceneName___Worker { //func doSomeWork() {} }
13.666667
38
0.731707
ffbfd71fd2b47a8b8700337e017a298e8fd33ba5
604
public struct Store<T>: StoreProtocol { private let _load: () throws -> T private let _store: (T) throws -> Void public init<X: StoreProtocol>( _ x: X ) where X.Value == T { self.init( load: { try x.load() }, store: { try x.store($0) } ) } public init( load: @escaping () throws -> T, store: @escaping (T) throws -> Void ) { self._load = load self._store = store } public func load() throws -> T { try _load() } public func store(_ value: T) throws { try _store(value) } }
22.37037
62
0.506623
22cbd72bf24c857bf6f6227ebf65354015c6a29d
281
import XCTest @testable import SLogger final class SLoggerTests: XCTestCase { func testExample() { SLogger.debug("Hello World!") SLogger.info("Hello World!") SLogger.warning("Hello World!") SLogger.error("Hello World!") // SLogger.fatal("Hello World!") } }
21.615385
38
0.679715
eb5d5b5d4274a2d138976b73e320aca24c9078a4
8,755
// // LockedViewController.swift // StandUp-iOS // // Created by Peter on 12/01/19. // Copyright © 2019 BlockchainCommons. All rights reserved. // import UIKit class LockedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var lockedArray = NSArray() var helperArray = [[String:Any]]() let creatingView = ConnectingView() var selectedVout = Int() var selectedTxid = "" var ind = 0 @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView(frame: .zero) DispatchQueue.main.async { self.creatingView.addConnectingView(vc: self, description: "Getting Locked UTXOs") } } override func viewDidAppear(_ animated: Bool) { getHelperArray() } func getHelperArray() { helperArray.removeAll() ind = 0 if lockedArray.count > 0 { for utxo in lockedArray { let dict = utxo as! NSDictionary let txid = dict["txid"] as! String let vout = dict["vout"] as! Int let helperDict = ["txid":txid, "vout":vout, "amount":0.0] as [String : Any] helperArray.append(helperDict) } getAmounts(i: ind) } else { DispatchQueue.main.async { self.tableView.reloadData() self.creatingView.removeConnectingView() displayAlert(viewController: self, isError: true, message: "No locked UTXO's") } } } func getAmounts(i: Int) { if i <= helperArray.count - 1 { selectedTxid = helperArray[i]["txid"] as! String selectedVout = helperArray[i]["vout"] as! Int executeNodeCommand(method: .getrawtransaction, param: "\"\(selectedTxid)\", true") } } // MARK: - Table view data source func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return helperArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "lockedCell", for: indexPath) let amountLabel = cell.viewWithTag(1) as! UILabel let voutLabel = cell.viewWithTag(2) as! UILabel let txidLabel = cell.viewWithTag(3) as! UILabel let dict = helperArray[indexPath.row] let txid = dict["txid"] as! String let vout = dict["vout"] as! Int let amount = dict["amount"] as! Double amountLabel.text = "\(amount)" voutLabel.text = "vout #\(vout)" txidLabel.text = "txid" + " " + txid return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 113 } func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let utxo = helperArray[indexPath.row] let txid = utxo["txid"] as! String let vout = utxo["vout"] as! Int let contextItem = UIContextualAction(style: .destructive, title: "Unlock") { (contextualAction, view, boolValue) in self.unlockUTXO(txid: txid, vout: vout) } let swipeActions = UISwipeActionsConfiguration(actions: [contextItem]) contextItem.backgroundColor = .blue return swipeActions } func unlockUTXO(txid: String, vout: Int) { let param = "true, ''[{\"txid\":\"\(txid)\",\"vout\":\(vout)}]''" executeNodeCommand(method: BTC_CLI_COMMAND.lockunspent, param: param) } func executeNodeCommand(method: BTC_CLI_COMMAND, param: String) { let reducer = Reducer() func getResult() { if !reducer.errorBool { switch method { case .getrawtransaction: let dict = reducer.dictToReturn let outputs = dict["vout"] as! NSArray for (i, outputDict) in outputs.enumerated() { let output = outputDict as! NSDictionary let value = output["value"] as! Double let vout = output["n"] as! Int if vout == selectedVout { helperArray[ind]["amount"] = value ind = ind + 1 } if i + 1 == outputs.count { if ind <= helperArray.count - 1 { getAmounts(i: ind) } else { DispatchQueue.main.async { self.tableView.reloadData() self.creatingView.removeConnectingView() } } } } case .listlockunspent: lockedArray = reducer.arrayToReturn getHelperArray() case .lockunspent: let result = reducer.doubleToReturn if result == 1 { displayAlert(viewController: self, isError: false, message: "UTXO is unlocked and can be selected for spends") } else { displayAlert(viewController: self, isError: true, message: "Unable to unlock that UTXO") } helperArray.removeAll() executeNodeCommand(method: .listlockunspent, param: "") DispatchQueue.main.async { self.creatingView.addConnectingView(vc: self, description: "Refreshing") } default: break } } else { DispatchQueue.main.async { self.creatingView.removeConnectingView() displayAlert(viewController: self, isError: true, message: reducer.errorDescription) } } } reducer.makeCommand(command: method, param: param, completion: getResult) } }
31.492806
142
0.406853
8789fb26bf85988d8251e97a3dd0a68ca809f4ee
3,386
// // 2019Day14.swift // aoc // // Created by Paul Uhn on 12/22/19. // Copyright © 2019 Rightpoint. All rights reserved. // import Foundation struct Y2019Day14 { struct Chemical: Hashable { let name: String static let ORE = Chemical(name: "ORE") static let FUEL = Chemical(name: "FUEL") init(name: Substring) { self.name = String(name) } } struct Reaction { var inputs: [Chemical: Int] let output: Chemical let amount: Int init?(_ data: String) { let regex = try! NSRegularExpression(pattern: "^([0-9 A-Z,]+) => ([0-9 A-Z]+)$") guard let match = regex.firstMatch(in: data, options: [], range: NSRange(location: 0, length: data.count)) else { return nil } let kv = data.match(match, at: 1) .commaSplit() .map { Reaction.tuple($0) } inputs = Dictionary(uniqueKeysWithValues: kv) (output, amount) = Reaction.tuple( data.match(match, at: 2)) } private static func tuple(_ data: String) -> (Chemical, Int) { let input = data.split(separator: " ") return (Chemical(name: input.last!), input.first!.int) } } static func Part1(_ data: [String]) -> Int { let reactions = data.compactMap(Reaction.init) return nanofactory(reactions, 1) } static func Part2(_ data: [String]) -> Int { let ORE = 1000000000000 let reactions = data.compactMap(Reaction.init) var min = 1 var max = ORE while true { let middle = (max + min) / 2 if middle == min { return middle } let ore = nanofactory(reactions, middle) if ore < ORE { min = middle } else { max = middle } } } private static func nanofactory(_ reactions: [Reaction], _ fuelAmount: Int) -> Int { var fuel = reactions.first { $0.output == .FUEL }! fuel.inputs[.FUEL] = fuelAmount - 1 var updated = false repeat { updated = false for input in fuel.inputs where input.key != .ORE { let reaction = reactions.first { $0.output == input.key }! let amount = fuel.inputs[input.key]! guard amount > 0 else { continue } replace(&fuel, reaction, multiply(reaction.amount, amount)) updated = true } } while updated return fuel.inputs[.ORE]! } private static func replace(_ fuel: inout Reaction, _ reaction: Reaction, _ multiples: Int) { for input in reaction.inputs { var amount = input.value * multiples if let existing = fuel.inputs[input.key] { amount += existing } fuel.inputs[input.key] = amount } fuel.inputs[reaction.output] = fuel.inputs[reaction.output]! - reaction.amount * multiples } private static func multiply(_ input: Int, _ output: Int) -> Int { var multiples = output / input if output % input != 0 { multiples += 1 } return multiples } }
30.504505
138
0.513585
46b82b2486e2653439b6b34760c90852905ddc4d
2,812
/*: ## App Exercise - Workout or Nil >These exercises reinforce Swift concepts in the context of a fitness tracking app. Have you ever accidentally tapped a button in an app? It's fairly common. In your fitness tracking app, you decide that if a user accidentally taps a button to start a workout and then ends the workout within 10 seconds, you simply don't want to create and log the workout. Otherwise the user would have to go delete the workout from the log. Create a `Workout` struct that has properties `startTime` and `endTime` of type `Double`. Dates are difficult to work with, so you'll be using doubles to represent the number of seconds since midnight, i.e. 28800 would represent 28,800 seconds, which is exactly 8 hours, so the start time is 8am. Write a failable initializer that takes parameters for your start and end times, and then checks to see if they are fewer than 10 seconds apart. If they are, your initializer should fail. Otherwise, they should set the properties accordingly. */ struct Workout { var startTime: Double var endTime: Double init?(startTime: Double, endTime: Double) { if endTime - startTime > 10 { self.startTime = startTime self.endTime = endTime } else { return nil } } } /*: Try to initialize two instances of a `Workout` object and print each of them. One of them should not be initialized because the start and end times are too close together. The other should successfully initialize a `Workout` object. */ var possibleWorkout1 = Workout.init(startTime: 28800, endTime: 32400) var possibleWorkout2 = Workout.init(startTime: 28800, endTime: 28805) /*: _Copyright © 2017 Apple Inc._ _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._ */ //: [Previous](@previous) | page 6 of 6
68.585366
463
0.754267
d569cab0da97ad17a122d3963476aa4c1de97a03
897
import XCTest import Foundation import Testing import HTTP @testable import Vapor @testable import App /// This file shows an example of testing /// routes through the Droplet. class RouteTests: TestCase { let drop = try! Droplet.testable() func testHello() throws { try drop .testResponse(to: .get, at: "hello") .assertStatus(is: .ok) .assertJSON("hello", equals: "world") } func testInfo() throws { try drop .testResponse(to: .get, at: "info") .assertStatus(is: .ok) .assertBody(contains: "0.0.0.0") } } // MARK: Manifest extension RouteTests { /// This is a requirement for XCTest on Linux /// to function properly. /// See ./Tests/LinuxMain.swift for examples static let allTests = [ ("testHello", testHello), ("testInfo", testInfo), ] }
22.425
49
0.595318
f837c8c572ba3da582c008b239738c06f892c424
4,596
//: ## FM Oscillator //: Open the timeline view to use the controls this playground sets up. //: import AudioKitPlaygrounds import AudioKit import AudioKitUI var oscillator = AKFMOscillator() oscillator.amplitude = 0.1 oscillator.rampDuration = 0.1 AudioKit.output = oscillator try AudioKit.start() class LiveView: AKLiveViewController { // UI Elements we'll need to be able to access var frequencySlider: AKSlider! var carrierMultiplierSlider: AKSlider! var modulatingMultiplierSlider: AKSlider! var modulationIndexSlider: AKSlider! var amplitudeSlider: AKSlider! var rampDurationSlider: AKSlider! override func viewDidLoad() { addTitle("FM Oscillator") addView(AKButton(title: "Start FM Oscillator") { button in oscillator.isStarted ? oscillator.stop() : oscillator.play() button.title = oscillator.isStarted ? "Stop FM Oscillator" : "Start FM Oscillator" }) let presets = ["Stun Ray", "Wobble", "Fog Horn", "Buzzer", "Spiral"] addView(AKPresetLoaderView(presets: presets) { preset in switch preset { case "Stun Ray": oscillator.presetStunRay() oscillator.start() case "Wobble": oscillator.presetWobble() oscillator.start() case "Fog Horn": oscillator.presetFogHorn() oscillator.start() case "Buzzer": oscillator.presetBuzzer() oscillator.start() case "Spiral": oscillator.presetSpiral() oscillator.start() default: break } self.frequencySlider?.value = oscillator.baseFrequency self.carrierMultiplierSlider?.value = oscillator.carrierMultiplier self.modulatingMultiplierSlider?.value = oscillator.modulatingMultiplier self.modulationIndexSlider?.value = oscillator.modulationIndex self.amplitudeSlider?.value = oscillator.amplitude self.rampDurationSlider?.value = oscillator.rampDuration }) addView(AKButton(title: "Randomize") { _ in oscillator.baseFrequency = self.frequencySlider.randomize() oscillator.carrierMultiplier = self.carrierMultiplierSlider.randomize() oscillator.modulatingMultiplier = self.modulatingMultiplierSlider.randomize() oscillator.modulationIndex = self.modulationIndexSlider.randomize() }) frequencySlider = AKSlider(property: "Frequency", value: oscillator.baseFrequency, range: 0 ... 800, format: "%0.2f Hz" ) { frequency in oscillator.baseFrequency = frequency } addView(frequencySlider) carrierMultiplierSlider = AKSlider(property: "Carrier Multiplier", value: oscillator.carrierMultiplier, range: 0 ... 20 ) { multiplier in oscillator.carrierMultiplier = multiplier } addView(carrierMultiplierSlider) modulatingMultiplierSlider = AKSlider(property: "Modulating Multiplier", value: oscillator.modulatingMultiplier, range: 0 ... 20 ) { multiplier in oscillator.modulatingMultiplier = multiplier } addView(modulatingMultiplierSlider) modulationIndexSlider = AKSlider(property: "Modulation Index", value: oscillator.modulationIndex, range: 0 ... 100 ) { index in oscillator.modulationIndex = index } addView(modulationIndexSlider) amplitudeSlider = AKSlider(property: "Amplitude", value: oscillator.amplitude) { amplitude in oscillator.amplitude = amplitude } addView(amplitudeSlider) rampDurationSlider = AKSlider(property: "Ramp Duration", value: oscillator.rampDuration, range: 0 ... 10, format: "%0.3f s" ) { time in oscillator.rampDuration = time } addView(rampDurationSlider) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
37.983471
101
0.583768
89b2d185ebd7cca13cb3a9ba593e11f3588edce2
504
// // ViewController.swift // MGArrayExtensions // // Created by Harly on 2017/8/11. // Copyright © 2017年 Harly. 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. } }
19.384615
80
0.670635
33b1a23c8ed0ba30780be1b4b691a2c3007a350f
1,114
// 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. // // EditContactViewController+Theme.swift import MacaroonUIKit import UIKit extension EditContactViewController { struct Theme: LayoutSheet, StyleSheet { let backgroundColor: Color let modalSize: LayoutSize let editContactViewTheme: EditContactViewTheme init(_ family: LayoutFamily) { backgroundColor = AppColors.Shared.System.background modalSize = (UIScreen.main.bounds.width, 402) editContactViewTheme = EditContactViewTheme() } } }
32.764706
75
0.722621
895738e08254f779b7db55d030e095f06331b348
8,110
// // AudioController.swift // blockchainapp // // Created by Aleksey Tyurnin on 06/12/2017. // Copyright © 2017 Ivan Gorbulin. All rights reserved. // import Foundation import Reachability import SDWebImage import UIKit import MediaPlayer class AudioController: AudioControllerProtocol, AudioPlayerDelegate1 { enum AudioStateNotification: String { case playing = "Playing", paused = "Paused", loading = "Loading" func notification() -> NSNotification.Name { return NSNotification.Name.init("AudioControllerUpdateNotification"+self.rawValue) } } static let main = AudioController() let player = AudioPlayer2() weak var delegate: AudioControllerDelegate? weak var popupDelegate: AudioControllerPresenter? var playlistName: String = "Main" var userPlaylist: AudioPlaylist = AudioPlaylist.init() var playlist: AudioPlaylist = AudioPlaylist.init() var currentTrackIndexPath: IndexPath = IndexPath.init(row: -1, section: -1) var info: (current: Double, length: Double) = (current: 0.0, length: 0.0) var currentTrack: AudioTrack? { get { return self[currentTrackIndexPath] } } var status: AudioStatus { get { return self.player.status == .playing ? .playing : .pause } } let reach: Reachability? = Reachability() init() { reach?.whenUnreachable = { _ in self.player.make(command: .pause) } do { try reach?.startNotifier() } catch { print("reach doesnt work") } self.player.delegate = self let mpcenter = MPRemoteCommandCenter.shared() mpcenter.playCommand.isEnabled = true mpcenter.pauseCommand.isEnabled = true mpcenter.nextTrackCommand.isEnabled = true mpcenter.skipBackwardCommand.isEnabled = true mpcenter.skipBackwardCommand.preferredIntervals = [10] mpcenter.previousTrackCommand.isEnabled = false mpcenter.playCommand.addTarget { (_) -> MPRemoteCommandHandlerStatus in self.make(command: .play(id: nil)) return .success } mpcenter.pauseCommand.addTarget { (_) -> MPRemoteCommandHandlerStatus in self.make(command: .pause) return .success } mpcenter.nextTrackCommand.addTarget { (_) -> MPRemoteCommandHandlerStatus in self.make(command: .next) return .success } mpcenter.skipBackwardCommand.addTarget { (_) -> MPRemoteCommandHandlerStatus in self.make(command: .seekBackward) return .success } // // MPRemoteCommandCenter.shared().previousTrackCommand.addTarget { (_) -> MPRemoteCommandHandlerStatus in // self.player.make(command: .prev) // return .success // } } func popupPlayer(show: Bool, animated: Bool) { } func make(command: AudioCommand) { if reach?.connection == Reachability.Connection.none { return } switch command { case .play(let id): if let id = id { if let indexPath = indexPath(id: id), indexPath != self.currentTrackIndexPath { self.currentTrackIndexPath = indexPath let index = indexPath.section * userPlaylist.tracks.count + indexPath.item player.load(item: (indexPath.section == 0 ? self.userPlaylist.tracks : self.playlist.tracks)[indexPath.item]) player.setTrack(index: index) player.make(command: .play) } else { if player.status == .playing { player.make(command: .pause) } else { player.make(command: .play) } } } else { player.make(command: .play) } DispatchQueue.main.async { self.popupDelegate?.popupPlayer(show: true, animated: true) } case .pause: player.make(command: .pause) case .next: self.play(indexPath: self.currentTrackIndexPath, next: true) case .prev: self.play(indexPath: self.currentTrackIndexPath, next: false) case .seekForward: let progress = ( info.current + 10.0 ) / info.length let validPregress = progress < 1.0 ? progress : 2.0 if validPregress < 1.0 { self.player.make(command: .seek(progress: validPregress)) } case .seekBackward: let newProgress = ( info.current - 10.0 ) / info.length player.make(command: .seek(progress: newProgress > 0 ? newProgress : 0.0)) case .seek(let progress): player.make(command: .seek(progress: progress)) default: print("unknown command") } } func addToUserPlaylist(track: AudioTrack, inBeginning: Bool) { if !self.userPlaylist.tracks.contains(where: {$0.id == track.id}) { var userIndexInsert = -1 if inBeginning { } else { self.userPlaylist.tracks.append(track) } } } func loadPlaylist(playlist:(String, [AudioTrack]), playId: String?) { if self.playlistName != playlist.0 { self.currentTrackIndexPath = IndexPath.invalid let newPlaylist = AudioPlaylist() newPlaylist.tracks = playlist.1 newPlaylist.name = playlist.0 self.playlist = newPlaylist if let id = playId { self.make(command: .play(id: id)) } } self.delegate?.playlistChanged() } func showPlaylist() { DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { self.popupDelegate?.showPlaylist() self.delegate?.showPlaylist() } } func setCurrentTrack(id: String) { if let indexPath = indexPath(id: id) { let index = indexPath.section * userPlaylist.tracks.count + indexPath.item self.player.setTrack(index: index) } } func itemFinishedPlaying(id: String) { self.play(id: id) } func play(indexPath: IndexPath, next: Bool) { let way = next ? 1 : -1 if indexPath.section == 0 { if indexPath.item + way == self.userPlaylist.tracks.count { self.currentTrackIndexPath = IndexPath.init(row: 0, section: 1) } else { self.currentTrackIndexPath.item += way } } else { if indexPath.item + way == self.playlist.tracks.count { self.make(command: .pause) self.currentTrackIndexPath = IndexPath.invalid self.userPlaylist.tracks = [] self.playlist.tracks = [] // TODO: hide player } else { self.currentTrackIndexPath.item += way } } if let item = self.currentTrack { self.player.load(item: item) self.player.make(command: .play) } } func play(id: String, next: Bool = true) { guard let indexPath = indexPath(id: id) else { return } self.play(indexPath: indexPath, next: next) } func update(time: AudioTime) { self.info.current = time.current self.info.length = time.length DispatchQueue.main.async { self.delegate?.updateTime(time: (current: time.current, length: time.length)) } } func update(status: PlayerStatus, id: String) { DispatchQueue.main.async { if let indexPath = self.indexPath(id: id) { switch status { case .paused: NotificationCenter.default.post(name: AudioStateNotification.paused.notification(), object: nil, userInfo: ["ItemID": id]) break case .playing: self.currentTrackIndexPath = indexPath NotificationCenter.default.post(name: AudioStateNotification.playing.notification(), object: nil, userInfo: ["ItemID": id]) break default: break } } self.delegate?.playState(isPlaying: self.player.status == .playing) self.delegate?.trackUpdate() } } private func indexPath(id: String) -> IndexPath? { if let mainIndex = self.playlist.tracks.index(where: {$0.id == id}) { return IndexPath.init(row: mainIndex, section: 1) } if let userIndex = self.userPlaylist.tracks.index(where: {$0.id == id}) { return IndexPath.init(row: userIndex, section: 0) } return nil } private func indexPath(index: Int) -> IndexPath? { if index < 0 { return nil } if index < userPlaylist.tracks.count { return IndexPath.init(row: index, section: 0) } else if index < userPlaylist.tracks.count + playlist.tracks.count { return IndexPath.init(row: index - userPlaylist.tracks.count , section: 1) } return nil } private subscript(indexPath: IndexPath) -> AudioTrack? { if indexPath.section == 0 { if indexPath.item >= 0 && indexPath.item < self.userPlaylist.tracks.count { return self.userPlaylist.tracks[indexPath.item] } } else if indexPath.section == 1 { if indexPath.item >= 0 && indexPath.item < self.playlist.tracks.count { return self.playlist.tracks[indexPath.item] } } return nil } }
27.491525
128
0.688903
891477bfee832841d8be8dee62605772cba2c264
2,255
// Copyright 2020-2021 Tokamak contributors // // 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. // // Created by Carson Katri on 10/10/20. // import CGTK import Dispatch import OpenCombineShim import TokamakCore public extension App { static func _launch(_ app: Self, with configuration: _AppConfiguration) { _ = Unmanaged.passRetained(GTKRenderer(app, configuration.rootEnvironment)) } static func _setTitle(_ title: String) { GTKRenderer.sharedWindow.withMemoryRebound(to: GtkWindow.self, capacity: 1) { gtk_window_set_title($0, title) } } var _phasePublisher: AnyPublisher<ScenePhase, Never> { CurrentValueSubject(.active).eraseToAnyPublisher() } var _colorSchemePublisher: AnyPublisher<ColorScheme, Never> { CurrentValueSubject(.light).eraseToAnyPublisher() } } extension UnsafeMutablePointer where Pointee == GApplication { @discardableResult func connect( signal: UnsafePointer<gchar>, data: UnsafeMutableRawPointer? = nil, handler: @convention(c) @escaping (UnsafeMutablePointer<GtkApplication>?, UnsafeRawPointer) -> Bool ) -> Int { let handler = unsafeBitCast(handler, to: GCallback.self) return Int(g_signal_connect_data(self, signal, handler, data, nil, GConnectFlags(rawValue: 0))) } /// Connect with a context-capturing closure. @discardableResult func connect( signal: UnsafePointer<gchar>, closure: @escaping () -> () ) -> Int { let closureBox = Unmanaged.passRetained(ClosureBox(closure)).toOpaque() return connect(signal: signal, data: closureBox) { _, closureBox in let unpackedAction = Unmanaged<ClosureBox<()>>.fromOpaque(closureBox) unpackedAction.takeRetainedValue().closure() return true } } }
32.681159
99
0.730377
e244b9543357593b8a0585a61bd5cbd4a7d2793c
6,981
// // OJADownloadManager.swift // LXMDownloader_Example // // Created by luxiaoming on 2019/1/4. // Copyright © 2019 CocoaPods. All rights reserved. // import Foundation import LXMDownloader let kLXMDidFinishDownloadNotification = "kLXMDidFinishDownloadNotification" private let kLXMdownloadFolder = "LXMDownloads" private let kLXMDownloadSavedModelKey = "kLXMDownloadSavedModelKey" let kOJSUserDefaults = UserDefaults.standard let kOJSFileManager = FileManager.default let kOJSUserDocumentDirectory = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] let kOJSUserCacheDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] class LXMVideoDownloadManager: NSObject { static let shared = LXMVideoDownloadManager() static let sessionIdentifier = "com.test.download" var selectedDefinition: String = "标清" fileprivate(set) var downloader: LXMDownloader = { var modelArray = [TestVideoModel]() if let data = kOJSUserDefaults.data(forKey: kLXMDownloadSavedModelKey), let array = NSKeyedUnarchiver.unarchiveObject(with: data) as? [TestVideoModel] { for model in array { if let downloadItem = model.lxm_downloadItem { if downloadItem.downloadStatus == .downloading || downloadItem.downloadStatus == .waiting { downloadItem.downloadStatus = .paused } modelArray.append(model) } } } let config = URLSessionConfiguration.background(withIdentifier: LXMVideoDownloadManager.sessionIdentifier) let downloader = LXMDownloader(sessionConfiguration: config, downloadFolderName: kLXMdownloadFolder, modelArray: modelArray) downloader.maxConcurrentTaskCount = 2 return downloader }() var allArray: [TestVideoModel] { return self.downloader.allArray as! [TestVideoModel] } var downloadingArray: [TestVideoModel] { return self.downloader.downloadingArray as! [TestVideoModel] } var finishedArray: [TestVideoModel] { return self.downloader.finishedArray as! [TestVideoModel] } fileprivate override init() { super.init() downloader.shouldSaveDownloadModelBlock = { [weak self] in self?.saveToUserDefaults() } downloader.downloadDidFailBlock = { [weak self] (model) in self?.saveToUserDefaults() } downloader.downloadDidFinishBlock = { [weak self] (model) in self?.saveToUserDefaults() if let model = model as? TestVideoModel { NotificationCenter.default.post(name: Notification.Name(kLXMDidFinishDownloadNotification), object: model) } } } } // MARK: - PrivateMethod private extension LXMVideoDownloadManager { func saveToUserDefaults() { // 持久化有多重方案可选,数据库,CoreData都可以,我这里就直接用UserDefaults了,只要目标model是可以序列化的就行。 let data = NSKeyedArchiver.archivedData(withRootObject: self.downloader.allArray) kOJSUserDefaults.set(data, forKey: kLXMDownloadSavedModelKey) kOJSUserDefaults.synchronize() } } // MARK: - PublicMethod extension LXMVideoDownloadManager { func downloadAction(forVideoModel videoModel: TestVideoModel, completion:@escaping ()->Void) { guard let allArray = self.downloader.allArray as? [TestVideoModel] else { return } for model in allArray { //注意,如果存在,要修改model的状态,而不是videoModel的 if model.videoId == videoModel.videoId { guard let item = model.lxm_downloadItem else { return } switch item.downloadStatus { case .none: self.download(videoModel: model)//理论上不会出现存在数组里又为none的状态 case .downloading: self.pauseDownload(videoModel: model, completion: nil) case .paused: self.download(videoModel: model) //判断是否要转为waiting在内部已经做了 case .waiting: self.pauseDownload(videoModel: model, completion: nil) //理论上不存在需要手动从waiting转换为downloading的任务 case .finished: print("您已经下载过该视频了") case .failed: print("下载失败") } completion() return //如果已经存在了,执行完上面的操作就能return了 } } self.download(videoModel: videoModel) completion() } func download(videoModel: TestVideoModel) { var urlString: String = videoModel.videoUrl_normal if self.selectedDefinition == "流畅" { urlString = videoModel.videoUrl_low } else if self.selectedDefinition == "标准" { urlString = videoModel.videoUrl_normal } else if self.selectedDefinition == "高清" { urlString = videoModel.videoUrl_high } guard let url = URL(string: urlString) else { return } // 注意!在调用downloader的download方法之前,一定要设置好lxm_downloadItem,不然会匹配不到数据 if videoModel.lxm_downloadItem == nil { videoModel.lxm_downloadItem = LXMDownloaderItem(itemId: "\(videoModel.videoId)", urlString: url.absoluteString) } self.downloader.download(item: videoModel, completion: { (success) in if success { print("已经开始下载") } else { print("下载失败") } }) } func pauseDownload(videoModel: TestVideoModel, completion:(()->Void)?) { self.downloader.pauseDownload(item: videoModel, completion: completion) } func deleteDownload(videoModel: TestVideoModel) { self.downloader.deleteDownload(item: videoModel) } /// 这个方法需要的时候主动调用,注意!!! func updateDownloadModel(targetModel: TestVideoModel) { let targetItemId = "\(targetModel.videoId)" for model in self.downloader.allArray { if model.lxm_downloadItem.itemId == targetItemId { targetModel.lxm_downloadItem = model.lxm_downloadItem return } } targetModel.lxm_downloadItem = nil } } // MARK - 路径相关方法 extension LXMVideoDownloadManager { /// 注意返回的是URL路径,不是string @objc class func localPath(forModel model: TestVideoModel) -> URL? { guard let item = model.lxm_downloadItem else { return nil } let path = LXMVideoDownloadManager.shared.downloader.localPath(forItem: item, isResumeData: false) return path } @objc class func hasLocalFile(forModel model: TestVideoModel) -> Bool { guard let item = model.lxm_downloadItem else { return false } return LXMVideoDownloadManager.shared.downloader.hasLocalFile(forItem: item) } }
36.359375
176
0.640596
385384e9a0421b82036dca232fdce92e61a32320
1,075
// // UIImage+Custom.swift // diyplayer // // Created by sidney on 2019/7/15. // Copyright © 2019 sidney. All rights reserved. // import Foundation import UIKit extension UIImage { //生成圆形图片 func toCircle() -> UIImage { //取最短边长 let shotest = min(self.size.width, self.size.height) //输出尺寸 let outputRect = CGRect(x: 0, y: 0, width: shotest, height: shotest) //开始图片处理上下文(由于输出的图不会进行缩放,所以缩放因子等于屏幕的scale即可) UIGraphicsBeginImageContextWithOptions(outputRect.size, false, 0) let context = UIGraphicsGetCurrentContext()! //添加圆形裁剪区域 context.addEllipse(in: outputRect) context.clip() //绘制图片 self.draw(in: CGRect(x: (shotest-self.size.width)/2, y: (shotest-self.size.height)/2, width: self.size.width, height: self.size.height)) //获得处理后的图片 let maskedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return maskedImage } }
29.861111
76
0.597209
fb0ded8763fe368b9518f914c6c29a2d62233762
2,633
// // ZTUIKit.swift // ZTCalculateLayout // // Created by 曾涛 on 2018/5/22. // Copyright © 2018年 曾涛. All rights reserved. // import UIKit @objc public class ZTUIKit: NSObject { /// label设置 /// /// - Parameters: 设置参数 /// - frame: frame /// - text: text /// - textColor: textColor /// - textfont: textfont /// - textAlignment: Alignment /// - Returns: label @objc public class func createLabel(frame:CGRect, textString:String, textColor:UIColor, textFont:UIFont, textAlignment:NSTextAlignment)-> UILabel{ let color:UIColor? = textColor let label = UILabel.init(frame: frame) label.text = textString label.font = textFont label.textAlignment = textAlignment label.textColor = (color != nil ? color : UIColor.black) return label } /// 富文本 /// /// - Parameters: /// - text: 文本内容 /// - line: 换行间距 /// - loc: 第几个字符开始替换 /// - len: 替换长度 /// - color: 替换颜色 /// - font: 替换字号 /// - alignment: 对齐方式, 0:居左 1:居中 2:居右 /// - Returns: AttributedString public class func swiftAttributedString(text:String, line:CGFloat, loc:Int, len:Int, color:UIColor, font:UIFont, alignment:Int) ->NSMutableAttributedString{ let paragraphStyle:NSMutableParagraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = line paragraphStyle.alignment = NSTextAlignment(rawValue: alignment)! let attributedStr:NSMutableAttributedString = NSMutableAttributedString.init(string: text) attributedStr.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: NSMakeRange(loc, len)) attributedStr.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, text.count)) attributedStr.addAttribute(NSAttributedStringKey.font, value: font, range: NSMakeRange(loc, len)) return attributedStr } /// 随机色 /// /// - Returns: UIColor @objc public class func randomColor() -> UIColor{ let hueRandom:CGFloat = CGFloat(arc4random() % 256) let colorRandom:CGFloat = CGFloat(arc4random() % 128) let hue:CGFloat = (hueRandom / CGFloat(256.0)) let saturation:CGFloat = (colorRandom / CGFloat(256.0)) + CGFloat(0.5) let brightness:CGFloat = (colorRandom / CGFloat(256.0)) + CGFloat(0.5) return UIColor.init(hue: hue, saturation: saturation, brightness: brightness, alpha: 1) } }
35.106667
160
0.616407
6928c0e11b4a62aead48098193c4be4e02bbc5f3
3,100
// // DHNewsSectionController.swift // DHIGListKitDemo // // Created by zipingfang on 2018/1/23. // Copyright © 2018年 aiden. All rights reserved. // import Foundation import IGListKit final class DHNewsSectionController: ListSectionController { override func numberOfItems() -> Int { return 5 } override func sizeForItem(at index: Int) -> CGSize { return CGSize(width: collectionContext!.containerSize.width, height: 50) } override func cellForItem(at index: Int) -> UICollectionViewCell { switch index { case 0: let cell = collectionContext?.dequeueReusableCell(withNibName: "DHNewsTopCollectionViewCell", bundle: nil, for: self, at: index) as! DHNewsTopCollectionViewCell return cell case 1: let cell = collectionContext?.dequeueReusableCell(withNibName: "DHNewsContentCollectionViewCell", bundle: nil, for: self, at: index) as! DHNewsContentCollectionViewCell cell.titleLabel.text = "123" cell.contentLabel.text = "nhiogqwmdwnegienwgiqwmiofmiwnfunqwurnwuirnwnr" return cell case 2: // let cell = collectionContext?.dequeueReusableCell(withNibName: "DHNewsImgsCollectionViewCell", bundle: nil, for: self, at: index) as! DHNewsImgsCollectionViewCell // return cell // let cell = collectionContext?.dequeueReusableCell(withNibName: "DHNewsImgCollectionViewCell", bundle: nil, for: self, at: index) as! DHNewsImgCollectionViewCell // return cell let cell = collectionContext?.dequeueReusableCell(withNibName: "DHNewsVedioCollectionViewCell", bundle: nil, for: self, at: index) as! DHNewsVedioCollectionViewCell return cell // let cell = collectionContext?.dequeueReusableCell(withNibName: "DHNewsAudioCollectionViewCell", bundle: nil, for: self, at: index) as! DHNewsAudioCollectionViewCell // return cell // let cell = collectionContext?.dequeueReusableCell(withNibName: "DHNewsAnswerCollectionViewCell", bundle: nil, for: self, at: index) as! DHNewsAnswerCollectionViewCell // return cell // let cell = collectionContext?.dequeueReusableCell(withNibName: "DHNewsLinkCollectionViewCell", bundle: nil, for: self, at: index) as! DHNewsLinkCollectionViewCell // return cell case 3: let cell = collectionContext?.dequeueReusableCell(withNibName: "DHNewsBottomCollectionViewCell", bundle: nil, for: self, at: index) as! DHNewsBottomCollectionViewCell return cell case 4: let cell = collectionContext?.dequeueReusableCell(withNibName: "DHSeparatorCollectionViewCell", bundle: nil, for: self, at: index) as! DHSeparatorCollectionViewCell return cell default: return UICollectionViewCell() } } override func didUpdate(to object: Any) { } override func didSelectItem(at index: Int) { } }
44.285714
180
0.666774
3a31eced95fe4f32faad6694186e09cf8f3cf055
14,549
// // UITableView+Chainable.swift // // // Created by 柴阿文 on 2021/2/4. // import UIKit import UIKitUtils public extension ChainableWrapper where Wrapped: UITableView { @discardableResult func registerCell(cellClass: UITableViewCell.Type, reuseIdentifier: String) -> Self { wrapped.register(cellClass, forCellReuseIdentifier: reuseIdentifier) return self } @discardableResult func registerCell(nib: UINib, reuseIdentifier: String) -> Self { wrapped.register(nib, forCellReuseIdentifier: reuseIdentifier) return self } @discardableResult func registerSectionHeaderFooterView(viewClass: UIView.Type, reuseIdentifier: String) -> Self { wrapped.register(viewClass, forHeaderFooterViewReuseIdentifier: reuseIdentifier) return self } @discardableResult func registerSectionHeaderFooterView(nib: UINib, reuseIdentifier: String) -> Self { wrapped.register(nib, forHeaderFooterViewReuseIdentifier: reuseIdentifier) return self } @discardableResult func tableHeaderView(_ view: UIView?) -> Self { wrapped.tableHeaderView = view return self } @discardableResult func tableFooterView(_ view: UIView?) -> Self { wrapped.tableFooterView = view return self } @discardableResult func backgroundView(_ view: UIView?) -> Self { wrapped.backgroundView = view return self } @discardableResult func rowHeight(_ height: CGFloat) -> Self { wrapped.rowHeight = height return self } @discardableResult func estimatedRowHeight(_ height: CGFloat) -> Self { wrapped.estimatedRowHeight = height return self } @discardableResult func isCellLayoutMarginsFollowReadableWidth(_ value: Bool) -> Self { wrapped.cellLayoutMarginsFollowReadableWidth = value return self } @discardableResult func isInsetsContentViewsToSafeArea(_ value: Bool) -> Self { wrapped.insetsContentViewsToSafeArea = value return self } @discardableResult func sectionHeaderHeight(_ height: CGFloat) -> Self { wrapped.sectionHeaderHeight = height return self } @discardableResult func sectionFooterHeight(_ height: CGFloat) -> Self { wrapped.sectionFooterHeight = height return self } @discardableResult func estimatedSectionHeaderHeight(_ height: CGFloat) -> Self { wrapped.estimatedSectionHeaderHeight = height return self } @discardableResult func estimatedSectionFooterHeight(_ height: CGFloat) -> Self { wrapped.estimatedSectionFooterHeight = height return self } @discardableResult func separatorStyle(_ style: UITableViewCell.SeparatorStyle) -> Self { wrapped.separatorStyle = style return self } @discardableResult func separatorColor(_ color: UIColor?) -> Self { wrapped.separatorColor = color return self } @discardableResult func separatorEffect(_ effect: UIVisualEffect?) -> Self { wrapped.separatorEffect = effect return self } @discardableResult func separatorInset(_ insets: UIEdgeInsets) -> Self { wrapped.separatorInset = insets return self } @discardableResult func separatorInsetReference(_ reference: UITableView.SeparatorInsetReference) -> Self { wrapped.separatorInsetReference = reference return self } @discardableResult func selectRow(indexPath: IndexPath?, isAnimated: Bool = true, scrollPosition: UITableView.ScrollPosition) -> Self { wrapped.selectRow(at: indexPath, animated: isAnimated, scrollPosition: scrollPosition) return self } @discardableResult func deselectRow(indexPath: IndexPath, isAnimated: Bool = true) -> Self { wrapped.deselectRow(at: indexPath, animated: isAnimated) return self } @discardableResult func isAllowsSelection(_ value: Bool) -> Self { wrapped.allowsSelection = value return self } @discardableResult func isAllowsMultipleSelection(_ value: Bool) -> Self { wrapped.allowsMultipleSelection = value return self } @discardableResult func isAllowsSelectionDuringEditing(_ value: Bool) -> Self { wrapped.allowsSelectionDuringEditing = value return self } @discardableResult func isAllowsMultipleSelectionDuringEditing(_ value: Bool) -> Self { wrapped.allowsMultipleSelectionDuringEditing = value return self } @discardableResult func isRemembersLastFocusedIndexPath(_ value: Bool) -> Self { wrapped.remembersLastFocusedIndexPath = value return self } @discardableResult func isSelectionFollowsFocus(_ value: Bool) -> Self { if #available(iOS 14.0, *) { wrapped.selectionFollowsFocus = value } return self } private var isTableViewEmpty: Bool { let numberOfSections = wrapped.numberOfSections guard numberOfSections != 0 else { return true } for section in 0..<numberOfSections { guard wrapped.numberOfRows(inSection: section) == 0 else { return false } } return true } @discardableResult func update(operation: DataSourceOperation, isAnimated: Bool = true, emptyViewHandler: ((UIView) -> Void)? = nil, completionHandler: ((Bool) -> Void)? = nil) -> Self { wrapped.viewWithTag(.max)?.removeFromSuperview() func handler(isFinished: Bool) -> Void { if let emptyViewHandler = emptyViewHandler, isTableViewEmpty { let emptyBackgroundView = UIView() emptyBackgroundView.tag = .max emptyBackgroundView.frame.size = wrapped.bounds.size emptyBackgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight] wrapped.insertSubview(emptyBackgroundView, at: 0) emptyViewHandler(emptyBackgroundView) } completionHandler?(isFinished) } switch operation { case .diff(let diffOperations): if wrapped.window == nil { if !diffOperations.isEmpty { wrapped.reloadData() } handler(isFinished: true) } else { if !diffOperations.isEmpty { if isAnimated { wrapped.performBatchUpdates({ diffOperations.forEach { diffOperation in switch diffOperation { case .insertSections(let indexSet): wrapped.insertSections(indexSet, with: .automatic) case .deleteSections(let indexSet): wrapped.deleteSections(indexSet, with: .automatic) case .updateSections(let indexSet): wrapped.reloadSections(indexSet, with: .automatic) case .moveSections(let indexs): indexs.forEach { (atIndex, toIndex) in wrapped.moveSection(atIndex, toSection: toIndex) } case .insert(let indexPaths): wrapped.insertRows(at: indexPaths, with: .automatic) case .delete(let indexPaths): wrapped.deleteRows(at: indexPaths, with: .automatic) case .update(let indexPaths): wrapped.reloadRows(at: indexPaths, with: .automatic) case .move(let indexPaths): indexPaths.forEach { (atIndexPath, toIndexPath) in wrapped.moveRow(at: atIndexPath, to: toIndexPath) } } } }, completion: handler) } else { UIView.performWithoutAnimation { wrapped.performBatchUpdates({ diffOperations.forEach { diffOperation in switch diffOperation { case .insertSections(let indexSet): wrapped.insertSections(indexSet, with: .automatic) case .deleteSections(let indexSet): wrapped.deleteSections(indexSet, with: .automatic) case .updateSections(let indexSet): wrapped.reloadSections(indexSet, with: .automatic) case .moveSections(let indexs): indexs.forEach { (atIndex, toIndex) in wrapped.moveSection(atIndex, toSection: toIndex) } case .insert(let indexPaths): wrapped.insertRows(at: indexPaths, with: .automatic) case .delete(let indexPaths): wrapped.deleteRows(at: indexPaths, with: .automatic) case .update(let indexPaths): wrapped.reloadRows(at: indexPaths, with: .automatic) case .move(let indexPaths): indexPaths.forEach { (atIndexPath, toIndexPath) in wrapped.moveRow(at: atIndexPath, to: toIndexPath) } } } }, completion: handler) } } } else { handler(isFinished: true) } } case .reload: wrapped.reloadData() handler(isFinished: true) } return self } @discardableResult func reloadEmptyView(handler: (UIView) -> Void) -> Self { wrapped.viewWithTag(.max)?.removeFromSuperview() if isTableViewEmpty { let emptyBackgroundView = UIView() emptyBackgroundView.tag = .max emptyBackgroundView.frame = wrapped.bounds emptyBackgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight] wrapped.insertSubview(emptyBackgroundView, at: 0) handler(emptyBackgroundView) } return self } @discardableResult func sectionIndexMinimumDisplayRowCount(_ value: Int) -> Self { wrapped.sectionIndexMinimumDisplayRowCount = value return self } @discardableResult func sectionIndexColor(_ color: UIColor?) -> Self { wrapped.sectionIndexColor = color return self } @discardableResult func sectionIndexBackgroundColor(_ color: UIColor?) -> Self { wrapped.sectionIndexBackgroundColor = color return self } @discardableResult func sectionIndexTrackingBackgroundColor(_ color: UIColor?) -> Self { wrapped.sectionIndexTrackingBackgroundColor = color return self } @discardableResult func isDragInteractionEnabled(_ value: Bool) -> Self { wrapped.dragInteractionEnabled = value return self } @discardableResult func scrollToRow(_ indexPath: IndexPath, scrollPosition: UITableView.ScrollPosition, isAnimated: Bool = true) -> Self { wrapped.scrollToRow(at: indexPath, at: scrollPosition, animated: isAnimated) return self } @discardableResult func scrollToNearestSelectedRow(scrollPosition: UITableView.ScrollPosition, isAnimated: Bool = true) -> Self { wrapped.scrollToNearestSelectedRow(at: scrollPosition, animated: isAnimated) return self } @discardableResult func scrollToLastRow(isAnimated: Bool = true) -> Self { let numberOfSections = wrapped.numberOfSections guard numberOfSections > 0 else { return self } for index in 1...numberOfSections { let numberOfRows = wrapped.numberOfRows(inSection: numberOfSections - index) if numberOfRows > 0 { wrapped.scrollToRow(at: IndexPath(row: numberOfRows - 1, section: numberOfSections - index), at: .bottom, animated: isAnimated) break } } return self } @discardableResult func isEditing(_ value: Bool, isAnimated: Bool = true) -> Self { wrapped.setEditing(value, animated: isAnimated) return self } @discardableResult func sectionHeaderTopPadding(_ padding: CGFloat) -> Self { if #available(iOS 15.0, *) { wrapped.sectionHeaderTopPadding = padding } return self } @discardableResult func reconfigureRows(at indexPaths: [IndexPath]) -> Self { if #available(iOS 15.0, *) { wrapped.reconfigureRows(at: indexPaths) } return self } @discardableResult func isAllowsFocus(_ value: Bool) -> Self { if #available(iOS 15.0, *) { wrapped.allowsFocus = value } return self } @discardableResult func isAllowsFocusDuringEditing(_ value: Bool) -> Self { if #available(iOS 15.0, *) { wrapped.allowsFocusDuringEditing = value } return self } @discardableResult func fillerRowHeight(_ height: CGFloat) -> Self { if #available(iOS 15.0, *) { wrapped.fillerRowHeight = height } return self } @discardableResult func isPrefetchingEnabled(_ value: Bool) -> Self { if #available(iOS 15.0, *) { wrapped.isPrefetchingEnabled = value } return self } }
35.659314
171
0.566912
ffaace5e2147df4e76018ca2dbdbb69e94766ead
840
// swift-tools-version:5.5 // // Package.swift // SBUnits // // Created by Ed Gamble on 12/3/15. // Copyright © 2015 Edward B. Gamble Jr. All rights reserved. // // See the LICENSE file at the project root for license information. // See the CONTRIBUTORS file at the project root for a list of contributors. // import PackageDescription let package = Package( name: "SBUnits", platforms: [ .macOS("11.1") ], products: [ .library( name: "SBUnits", targets: ["SBUnits"]), ], dependencies: [ ], targets: [ .target( name: "SBUnits", dependencies: [], path: "Sources" ), .testTarget( name: "SBUnitsTests", dependencies: ["SBUnits"], path: "Tests" ), ] )
20
77
0.527381
147b70b22565b6c0d183381eb8790f2479b56b09
18,806
/* file: tessellated_structured_item.swift generated: Mon Jan 3 16:32:52 2022 */ /* This file was generated by the EXPRESS to Swift translator "exp2swift", derived from STEPcode (formerly NIST's SCL). exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23 WARNING: You probably don't want to edit it since your modifications will be lost if exp2swift is used to regenerate it. */ import SwiftSDAIcore extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { //MARK: -ENTITY DEFINITION in EXPRESS /* ENTITY tessellated_structured_item SUPERTYPE OF ( ONEOF ( tessellated_face, tessellated_edge, tessellated_vertex ) ) SUBTYPE OF ( tessellated_item ); END_ENTITY; -- tessellated_structured_item (line:32099 file:ap242ed2_mim_lf_v1.101.TY.exp) */ //MARK: - ALL DEFINED ATTRIBUTES /* SUPER- ENTITY(1) representation_item ATTR: name, TYPE: label -- EXPLICIT SUPER- ENTITY(2) geometric_representation_item ATTR: dim, TYPE: dimension_count -- DERIVED := dimension_of( SELF ) SUPER- ENTITY(3) tessellated_item (no local attributes) ENTITY(SELF) tessellated_structured_item (no local attributes) SUB- ENTITY(5) tessellated_vertex ATTR: coordinates, TYPE: coordinates_list -- EXPLICIT (AMBIGUOUS/MASKED) ATTR: topological_link, TYPE: OPTIONAL vertex_point -- EXPLICIT ATTR: point_index, TYPE: INTEGER -- EXPLICIT SUB- ENTITY(6) tessellated_connecting_edge ATTR: smooth, TYPE: LOGICAL -- EXPLICIT (AMBIGUOUS/MASKED) ATTR: face1, TYPE: tessellated_face -- EXPLICIT (AMBIGUOUS/MASKED) ATTR: face2, TYPE: tessellated_face -- EXPLICIT (AMBIGUOUS/MASKED) ATTR: line_strip_face1, TYPE: LIST [2 : ?] OF INTEGER -- EXPLICIT ATTR: line_strip_face2, TYPE: LIST [2 : ?] OF INTEGER -- EXPLICIT SUB- ENTITY(7) cubic_tessellated_connecting_edge ATTR: smooth, TYPE: LOGICAL -- EXPLICIT (AMBIGUOUS/MASKED) ATTR: face1, TYPE: cubic_bezier_triangulated_face -- EXPLICIT (AMBIGUOUS/MASKED) ATTR: face2, TYPE: cubic_bezier_triangulated_face -- EXPLICIT (AMBIGUOUS/MASKED) SUB- ENTITY(8) cubic_bezier_tessellated_edge REDCR: line_strip, TYPE: LIST [4 : ?] OF INTEGER -- EXPLICIT -- OVERRIDING ENTITY: tessellated_edge SUB- ENTITY(9) tessellated_edge ATTR: coordinates, TYPE: coordinates_list -- EXPLICIT (AMBIGUOUS/MASKED) ATTR: geometric_link, TYPE: OPTIONAL edge_or_curve -- EXPLICIT (AMBIGUOUS/MASKED) ATTR: line_strip, TYPE: LIST [2 : ?] OF INTEGER -- EXPLICIT -- possibly overriden by ENTITY: cubic_bezier_tessellated_edge, TYPE: LIST [4 : ?] OF INTEGER SUB- ENTITY(10) triangulated_face ATTR: pnindex, TYPE: LIST [0 : ?] OF INTEGER -- EXPLICIT (AMBIGUOUS/MASKED) ATTR: triangles, TYPE: LIST [1 : ?] OF LIST [3 : 3] OF INTEGER -- EXPLICIT SUB- ENTITY(11) complex_triangulated_face ATTR: pnindex, TYPE: LIST [0 : ?] OF INTEGER -- EXPLICIT (AMBIGUOUS/MASKED) ATTR: triangle_strips, TYPE: LIST [0 : ?] OF LIST [3 : ?] OF INTEGER -- EXPLICIT ATTR: triangle_fans, TYPE: LIST [0 : ?] OF LIST [3 : ?] OF INTEGER -- EXPLICIT SUB- ENTITY(12) cubic_bezier_triangulated_face ATTR: ctriangles, TYPE: LIST [1 : ?] OF LIST [10 : 10] OF INTEGER -- EXPLICIT SUB- ENTITY(13) tessellated_face ATTR: coordinates, TYPE: coordinates_list -- EXPLICIT (AMBIGUOUS/MASKED) ATTR: pnmax, TYPE: INTEGER -- EXPLICIT ATTR: normals, TYPE: LIST [0 : ?] OF LIST [3 : 3] OF REAL -- EXPLICIT ATTR: geometric_link, TYPE: OPTIONAL face_or_surface -- EXPLICIT (AMBIGUOUS/MASKED) */ //MARK: - Partial Entity public final class _tessellated_structured_item : SDAI.PartialEntity { public override class var entityReferenceType: SDAI.EntityReference.Type { eTESSELLATED_STRUCTURED_ITEM.self } //ATTRIBUTES // (no local attributes) public override var typeMembers: Set<SDAI.STRING> { var members = Set<SDAI.STRING>() members.insert(SDAI.STRING(Self.typeName)) return members } //VALUE COMPARISON SUPPORT public override func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) { super.hashAsValue(into: &hasher, visited: &complexEntities) } public override func isValueEqual(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool { guard let rhs = rhs as? Self else { return false } if !super.isValueEqual(to: rhs, visited: &comppairs) { return false } return true } public override func isValueEqualOptionally(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? { guard let rhs = rhs as? Self else { return false } var result: Bool? = true if let comp = super.isValueEqualOptionally(to: rhs, visited: &comppairs) { if !comp { return false } } else { result = nil } return result } //EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR public init() { super.init(asAbstructSuperclass:()) } //p21 PARTIAL ENTITY CONSTRUCTOR public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) { let numParams = 0 guard parameters.count == numParams else { exchangeStructure.error = "number of p21 parameters(\(parameters.count)) are different from expected(\(numParams)) for entity(\(Self.entityName)) constructor"; return nil } self.init( ) } } //MARK: - Entity Reference /** ENTITY reference - EXPRESS: ```express ENTITY tessellated_structured_item SUPERTYPE OF ( ONEOF ( tessellated_face, tessellated_edge, tessellated_vertex ) ) SUBTYPE OF ( tessellated_item ); END_ENTITY; -- tessellated_structured_item (line:32099 file:ap242ed2_mim_lf_v1.101.TY.exp) ``` */ public final class eTESSELLATED_STRUCTURED_ITEM : SDAI.EntityReference { //MARK: PARTIAL ENTITY public override class var partialEntityType: SDAI.PartialEntity.Type { _tessellated_structured_item.self } public let partialEntity: _tessellated_structured_item //MARK: SUPERTYPES public let super_eREPRESENTATION_ITEM: eREPRESENTATION_ITEM // [1] public let super_eGEOMETRIC_REPRESENTATION_ITEM: eGEOMETRIC_REPRESENTATION_ITEM // [2] public let super_eTESSELLATED_ITEM: eTESSELLATED_ITEM // [3] public var super_eTESSELLATED_STRUCTURED_ITEM: eTESSELLATED_STRUCTURED_ITEM { return self } // [4] //MARK: SUBTYPES public var sub_eTESSELLATED_VERTEX: eTESSELLATED_VERTEX? { // [5] return self.complexEntity.entityReference(eTESSELLATED_VERTEX.self) } public var sub_eTESSELLATED_CONNECTING_EDGE: eTESSELLATED_CONNECTING_EDGE? { // [6] return self.complexEntity.entityReference(eTESSELLATED_CONNECTING_EDGE.self) } public var sub_eCUBIC_TESSELLATED_CONNECTING_EDGE: eCUBIC_TESSELLATED_CONNECTING_EDGE? { // [7] return self.complexEntity.entityReference(eCUBIC_TESSELLATED_CONNECTING_EDGE.self) } public var sub_eCUBIC_BEZIER_TESSELLATED_EDGE: eCUBIC_BEZIER_TESSELLATED_EDGE? { // [8] return self.complexEntity.entityReference(eCUBIC_BEZIER_TESSELLATED_EDGE.self) } public var sub_eTESSELLATED_EDGE: eTESSELLATED_EDGE? { // [9] return self.complexEntity.entityReference(eTESSELLATED_EDGE.self) } public var sub_eTRIANGULATED_FACE: eTRIANGULATED_FACE? { // [10] return self.complexEntity.entityReference(eTRIANGULATED_FACE.self) } public var sub_eCOMPLEX_TRIANGULATED_FACE: eCOMPLEX_TRIANGULATED_FACE? { // [11] return self.complexEntity.entityReference(eCOMPLEX_TRIANGULATED_FACE.self) } public var sub_eCUBIC_BEZIER_TRIANGULATED_FACE: eCUBIC_BEZIER_TRIANGULATED_FACE? { // [12] return self.complexEntity.entityReference(eCUBIC_BEZIER_TRIANGULATED_FACE.self) } public var sub_eTESSELLATED_FACE: eTESSELLATED_FACE? { // [13] return self.complexEntity.entityReference(eTESSELLATED_FACE.self) } //MARK: ATTRIBUTES // FACE1: (2 AMBIGUOUS REFs) // FACE2: (2 AMBIGUOUS REFs) // GEOMETRIC_LINK: (2 AMBIGUOUS REFs) // COORDINATES: (3 AMBIGUOUS REFs) // PNINDEX: (2 AMBIGUOUS REFs) // SMOOTH: (2 AMBIGUOUS REFs) /// __EXPLICIT__ attribute /// - origin: SUB( ``eCUBIC_BEZIER_TRIANGULATED_FACE`` ) public var CTRIANGLES: (SDAI.LIST<SDAI.LIST<SDAI.INTEGER>/*[10:10]*/ >/*[1:nil]*/ )? { get { return sub_eCUBIC_BEZIER_TRIANGULATED_FACE?.partialEntity._ctriangles } set(newValue) { guard let partial = sub_eCUBIC_BEZIER_TRIANGULATED_FACE?.super_eCUBIC_BEZIER_TRIANGULATED_FACE .partialEntity else { return } partial._ctriangles = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUB( ``eTESSELLATED_FACE`` ) public var NORMALS: (SDAI.LIST<SDAI.LIST<SDAI.REAL>/*[3:3]*/ >/*[0:nil]*/ )? { get { return sub_eTESSELLATED_FACE?.partialEntity._normals } set(newValue) { guard let partial = sub_eTESSELLATED_FACE?.super_eTESSELLATED_FACE.partialEntity else { return } partial._normals = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUB( ``eTESSELLATED_VERTEX`` ) public var TOPOLOGICAL_LINK: eVERTEX_POINT? { get { return sub_eTESSELLATED_VERTEX?.partialEntity._topological_link } set(newValue) { guard let partial = sub_eTESSELLATED_VERTEX?.super_eTESSELLATED_VERTEX.partialEntity else { return } partial._topological_link = newValue } } /// __EXPLICIT__ attribute /// - origin: SUB( ``eTESSELLATED_EDGE`` ) public var LINE_STRIP: (SDAI.LIST<SDAI.INTEGER>/*[2:nil]*/ )? { get { return sub_eTESSELLATED_EDGE?.partialEntity._line_strip } set(newValue) { guard let partial = sub_eTESSELLATED_EDGE?.super_eTESSELLATED_EDGE.partialEntity else { return } partial._line_strip = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUB( ``eTESSELLATED_CONNECTING_EDGE`` ) public var LINE_STRIP_FACE2: (SDAI.LIST<SDAI.INTEGER>/*[2:nil]*/ )? { get { return sub_eTESSELLATED_CONNECTING_EDGE?.partialEntity._line_strip_face2 } set(newValue) { guard let partial = sub_eTESSELLATED_CONNECTING_EDGE?.super_eTESSELLATED_CONNECTING_EDGE .partialEntity else { return } partial._line_strip_face2 = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUB( ``eTESSELLATED_CONNECTING_EDGE`` ) public var LINE_STRIP_FACE1: (SDAI.LIST<SDAI.INTEGER>/*[2:nil]*/ )? { get { return sub_eTESSELLATED_CONNECTING_EDGE?.partialEntity._line_strip_face1 } set(newValue) { guard let partial = sub_eTESSELLATED_CONNECTING_EDGE?.super_eTESSELLATED_CONNECTING_EDGE .partialEntity else { return } partial._line_strip_face1 = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUB( ``eCOMPLEX_TRIANGULATED_FACE`` ) public var TRIANGLE_STRIPS: (SDAI.LIST<SDAI.LIST<SDAI.INTEGER>/*[3:nil]*/ >/*[0:nil]*/ )? { get { return sub_eCOMPLEX_TRIANGULATED_FACE?.partialEntity._triangle_strips } set(newValue) { guard let partial = sub_eCOMPLEX_TRIANGULATED_FACE?.super_eCOMPLEX_TRIANGULATED_FACE.partialEntity else { return } partial._triangle_strips = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUB( ``eTRIANGULATED_FACE`` ) public var TRIANGLES: (SDAI.LIST<SDAI.LIST<SDAI.INTEGER>/*[3:3]*/ >/*[1:nil]*/ )? { get { return sub_eTRIANGULATED_FACE?.partialEntity._triangles } set(newValue) { guard let partial = sub_eTRIANGULATED_FACE?.super_eTRIANGULATED_FACE.partialEntity else { return } partial._triangles = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUB( ``eTESSELLATED_VERTEX`` ) public var POINT_INDEX: SDAI.INTEGER? { get { return sub_eTESSELLATED_VERTEX?.partialEntity._point_index } set(newValue) { guard let partial = sub_eTESSELLATED_VERTEX?.super_eTESSELLATED_VERTEX.partialEntity else { return } partial._point_index = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUB( ``eTESSELLATED_FACE`` ) public var PNMAX: SDAI.INTEGER? { get { return sub_eTESSELLATED_FACE?.partialEntity._pnmax } set(newValue) { guard let partial = sub_eTESSELLATED_FACE?.super_eTESSELLATED_FACE.partialEntity else { return } partial._pnmax = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUPER( ``eREPRESENTATION_ITEM`` ) public var NAME: tLABEL { get { return SDAI.UNWRAP( super_eREPRESENTATION_ITEM.partialEntity._name ) } set(newValue) { let partial = super_eREPRESENTATION_ITEM.partialEntity partial._name = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUB( ``eCOMPLEX_TRIANGULATED_FACE`` ) public var TRIANGLE_FANS: (SDAI.LIST<SDAI.LIST<SDAI.INTEGER>/*[3:nil]*/ >/*[0:nil]*/ )? { get { return sub_eCOMPLEX_TRIANGULATED_FACE?.partialEntity._triangle_fans } set(newValue) { guard let partial = sub_eCOMPLEX_TRIANGULATED_FACE?.super_eCOMPLEX_TRIANGULATED_FACE.partialEntity else { return } partial._triangle_fans = SDAI.UNWRAP(newValue) } } /// __DERIVE__ attribute /// - origin: SUPER( ``eGEOMETRIC_REPRESENTATION_ITEM`` ) public var DIM: tDIMENSION_COUNT? { get { if let cached = cachedValue(derivedAttributeName:"DIM") { return cached.value as! tDIMENSION_COUNT? } let origin = super_eGEOMETRIC_REPRESENTATION_ITEM let value = tDIMENSION_COUNT(origin.partialEntity._dim__getter(SELF: origin)) updateCache(derivedAttributeName:"DIM", value:value) return value } } //MARK: INITIALIZERS public convenience init?(_ entityRef: SDAI.EntityReference?) { let complex = entityRef?.complexEntity self.init(complex: complex) } public required init?(complex complexEntity: SDAI.ComplexEntity?) { guard let partial = complexEntity?.partialEntityInstance(_tessellated_structured_item.self) else { return nil } self.partialEntity = partial guard let super1 = complexEntity?.entityReference(eREPRESENTATION_ITEM.self) else { return nil } self.super_eREPRESENTATION_ITEM = super1 guard let super2 = complexEntity?.entityReference(eGEOMETRIC_REPRESENTATION_ITEM.self) else { return nil } self.super_eGEOMETRIC_REPRESENTATION_ITEM = super2 guard let super3 = complexEntity?.entityReference(eTESSELLATED_ITEM.self) else { return nil } self.super_eTESSELLATED_ITEM = super3 super.init(complex: complexEntity) } public required convenience init?<G: SDAIGenericType>(fromGeneric generic: G?) { guard let entityRef = generic?.entityReference else { return nil } self.init(complex: entityRef.complexEntity) } public convenience init?<S: SDAISelectType>(_ select: S?) { self.init(possiblyFrom: select) } public convenience init?(_ complex: SDAI.ComplexEntity?) { self.init(complex: complex) } //MARK: DICTIONARY DEFINITION public class override var entityDefinition: SDAIDictionarySchema.EntityDefinition { _entityDefinition } private static let _entityDefinition: SDAIDictionarySchema.EntityDefinition = createEntityDefinition() private static func createEntityDefinition() -> SDAIDictionarySchema.EntityDefinition { let entityDef = SDAIDictionarySchema.EntityDefinition(name: "TESSELLATED_STRUCTURED_ITEM", type: self, explicitAttributeCount: 0) //MARK: SUPERTYPE REGISTRATIONS entityDef.add(supertype: eREPRESENTATION_ITEM.self) entityDef.add(supertype: eGEOMETRIC_REPRESENTATION_ITEM.self) entityDef.add(supertype: eTESSELLATED_ITEM.self) entityDef.add(supertype: eTESSELLATED_STRUCTURED_ITEM.self) //MARK: ATTRIBUTE REGISTRATIONS entityDef.addAttribute(name: "CTRIANGLES", keyPath: \eTESSELLATED_STRUCTURED_ITEM.CTRIANGLES, kind: .explicit, source: .subEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "NORMALS", keyPath: \eTESSELLATED_STRUCTURED_ITEM.NORMALS, kind: .explicit, source: .subEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "TOPOLOGICAL_LINK", keyPath: \eTESSELLATED_STRUCTURED_ITEM.TOPOLOGICAL_LINK, kind: .explicitOptional, source: .subEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "LINE_STRIP", keyPath: \eTESSELLATED_STRUCTURED_ITEM.LINE_STRIP, kind: .explicit, source: .subEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "LINE_STRIP_FACE2", keyPath: \eTESSELLATED_STRUCTURED_ITEM.LINE_STRIP_FACE2, kind: .explicit, source: .subEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "LINE_STRIP_FACE1", keyPath: \eTESSELLATED_STRUCTURED_ITEM.LINE_STRIP_FACE1, kind: .explicit, source: .subEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "TRIANGLE_STRIPS", keyPath: \eTESSELLATED_STRUCTURED_ITEM.TRIANGLE_STRIPS, kind: .explicit, source: .subEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "TRIANGLES", keyPath: \eTESSELLATED_STRUCTURED_ITEM.TRIANGLES, kind: .explicit, source: .subEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "POINT_INDEX", keyPath: \eTESSELLATED_STRUCTURED_ITEM.POINT_INDEX, kind: .explicit, source: .subEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "PNMAX", keyPath: \eTESSELLATED_STRUCTURED_ITEM.PNMAX, kind: .explicit, source: .subEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "NAME", keyPath: \eTESSELLATED_STRUCTURED_ITEM.NAME, kind: .explicit, source: .superEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "TRIANGLE_FANS", keyPath: \eTESSELLATED_STRUCTURED_ITEM.TRIANGLE_FANS, kind: .explicit, source: .subEntity, mayYieldEntityReference: false) entityDef.addAttribute(name: "DIM", keyPath: \eTESSELLATED_STRUCTURED_ITEM.DIM, kind: .derived, source: .superEntity, mayYieldEntityReference: false) return entityDef } } }
37.839034
185
0.702648
f8f49964b574f0ff90ace595ac569ed4991565ff
1,329
import ReactiveSwift import UIKit extension Reactive where Base: UIButton { /// The action to be triggered when the button is pressed. It also controls /// the enabled state of the button. public var pressed: CocoaAction<Base>? { get { return associatedAction.withValue { info in return info.flatMap { info in return info.controlEvents == pressEvent ? info.action : nil } } } nonmutating set { setAction(newValue, for: pressEvent) } } private var pressEvent: UIControl.Event { if #available(iOS 9.0, tvOS 9.0, *) { return .primaryActionTriggered } else { return .touchUpInside } } /// Sets the title of the button for its normal state. public var title: BindingTarget<String> { return makeBindingTarget { $0.setTitle($1, for: .normal) } } /// Sets the title of the button for the specified state. public func title(for state: UIControl.State) -> BindingTarget<String> { return makeBindingTarget { $0.setTitle($1, for: state) } } /// Sets the image of the button for the specified state. public func image(for state: UIControl.State) -> BindingTarget<UIImage?> { return makeBindingTarget { $0.setImage($1, for: state) } } /// Sets the image of the button for the .normal state public var image: BindingTarget<UIImage?> { return image(for: .normal) } }
27.122449
76
0.699022
db1edd58be89559c9afde461a230df3ff6775eb5
3,969
#!/usr/bin/swift import Foundation struct Bash { @discardableResult static func run(_ command: String) -> Process { let process: Process = Process() process.launchPath = "/bin/sh" process.arguments = ["-c", String(format:"%@", command)] process.launch() return process } } func mapping(from url: URL) throws -> Package { let data = try Data(contentsOf: url, options: .mappedIfSafe) let decoder = JSONDecoder() return try decoder.decode(Package.self, from: data) } struct Package: Decodable { let targets: [Target] } struct Target: Decodable { let name: String let include: [String]? let exclude: [String]? } struct FileMaker { private let package: Package private let existedFrameworks: [String] init(package: Package, existedFrameworks: [String]) { self.package = package self.existedFrameworks = existedFrameworks } func make(toFolderURL folderURL: URL) throws { package.targets.forEach { target in let frameworks = allowedFrameworks(target: target, existedFrameworks: existedFrameworks) let inputFileName = target.name.lowercased() == "default" ? "Input" : "Input-\(target.name)" let outputFileName = target.name.lowercased() == "default" ? "Output" : "Output-\(target.name)" let inputFiles = frameworks.reduce("") { $0 + "$(SRCROOT)/Carthage/Build/iOS/\($1).framework\n" } let ouputFiles = frameworks.reduce("") { $0 + "$(BUILT_PRODUCTS_DIR)/$(FRAMEWORKS_FOLDER_PATH)/\($1).framework\n" } write(inputFiles, to: folderURL.appendingPathComponent("\(inputFileName).xcfilelist")) write(ouputFiles, to: folderURL.appendingPathComponent("\(outputFileName).xcfilelist")) print("🎯 \(target.name) Target\n\(frameworks.reduce("") { $0 + "\($1)\n" })") } } private func write(_ text: String, to url: URL) { try? text.write(to: url, atomically: false, encoding: .utf8) } private func allowedFrameworks(target: Target, existedFrameworks: [String]) -> [String] { if let include = target.include { return existedFrameworks.filter { include.contains($0) == true } } else { return existedFrameworks.filter { target.exclude?.contains($0) == false } } } } struct FrameworkFinder { private let url: URL init(url: URL) { self.url = url } func findNames() throws -> [String] { return try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil) .filter { $0.pathExtension == "framework" } .map { $0.deletingPathExtension().lastPathComponent } } } var process: Process? signal(SIGINT, SIG_IGN) // Make sure the signal does not terminate the application. let sigintSrc = DispatchSource.makeSignalSource(signal: SIGINT, queue: .main) sigintSrc.setEventHandler { process?.terminate() exit(0) } sigintSrc.resume() if CommandLine.arguments.count > 1 { process = Bash.run("carthage update \(CommandLine.arguments[1]) --platform iOS") } else { process = Bash.run("carthage update --platform iOS") } process?.waitUntilExit() let rootURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) let fileURL = rootURL.appendingPathComponent("Cartfile.pack") let frameworkURL = rootURL.appendingPathComponent("Carthage/Build/iOS") let outputURL = rootURL.appendingPathComponent("Carthage") do { let package = try mapping(from: fileURL) let existedFrameworks = try FrameworkFinder(url: frameworkURL).findNames() let fileMaker = FileMaker(package: package, existedFrameworks: existedFrameworks) print("🧰 Downloaded Frameworks\n\(existedFrameworks.reduce("") { $0 + "\($1)\n" })") try fileMaker.make(toFolderURL: outputURL) } catch { print("Exception: \(error)") }
33.923077
127
0.651298
b978e9864ce55e2eff907a7ac46ac8775c33d769
31,884
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 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 // //===----------------------------------------------------------------------===// import Foundation import XCTest class TestDecimal : XCTestCase { func test_AdditionWithNormalization() { let biggie = Decimal(65536) let smallee = Decimal(65536) let answer = biggie/smallee XCTAssertEqual(Decimal(1),answer) var one = Decimal(1) var addend = Decimal(1) var expected = Decimal() var result = Decimal() expected._isNegative = 0; expected._isCompact = 0; // 2 digits -- certain to work addend._exponent = -1; XCTAssertEqual(.noError, NSDecimalAdd(&result, &one, &addend, .plain), "1 + 0.1") expected._exponent = -1; expected._length = 1; expected._mantissa.0 = 11; XCTAssertEqual(.orderedSame, NSDecimalCompare(&expected, &result), "1.1 == 1 + 0.1") // 38 digits -- guaranteed by NSDecimal to work addend._exponent = -37; XCTAssertEqual(.noError, NSDecimalAdd(&result, &one, &addend, .plain), "1 + 1e-37") expected._exponent = -37; expected._length = 8; expected._mantissa.0 = 0x0001; expected._mantissa.1 = 0x0000; expected._mantissa.2 = 0x36a0; expected._mantissa.3 = 0x00f4; expected._mantissa.4 = 0x46d9; expected._mantissa.5 = 0xd5da; expected._mantissa.6 = 0xee10; expected._mantissa.7 = 0x0785; XCTAssertEqual(.orderedSame, NSDecimalCompare(&expected, &result), "1 + 1e-37") // 39 digits -- not guaranteed to work but it happens to, so we make the test work either way addend._exponent = -38; let error = NSDecimalAdd(&result, &one, &addend, .plain) XCTAssertTrue(error == .noError || error == .lossOfPrecision, "1 + 1e-38") if error == .noError { expected._exponent = -38; expected._length = 8; expected._mantissa.0 = 0x0001; expected._mantissa.1 = 0x0000; expected._mantissa.2 = 0x2240; expected._mantissa.3 = 0x098a; expected._mantissa.4 = 0xc47a; expected._mantissa.5 = 0x5a86; expected._mantissa.6 = 0x4ca8; expected._mantissa.7 = 0x4b3b; XCTAssertEqual(.orderedSame, NSDecimalCompare(&expected, &result), "1 + 1e-38") } else { XCTAssertEqual(.orderedSame, NSDecimalCompare(&one, &result), "1 + 1e-38") } // 40 digits -- doesn't work; need to make sure it's rounding for us addend._exponent = -39; XCTAssertEqual(.lossOfPrecision, NSDecimalAdd(&result, &one, &addend, .plain), "1 + 1e-39") XCTAssertEqual("1", result.description) XCTAssertEqual(.orderedSame, NSDecimalCompare(&one, &result), "1 + 1e-39") } func test_BasicConstruction() { let zero = Decimal() XCTAssertEqual(20, MemoryLayout<Decimal>.size) XCTAssertEqual(0, zero._exponent) XCTAssertEqual(0, zero._length) XCTAssertEqual(0, zero._isNegative) XCTAssertEqual(0, zero._isCompact) XCTAssertEqual(0, zero._reserved) let (m0, m1, m2, m3, m4, m5, m6, m7) = zero._mantissa XCTAssertEqual(0, m0) XCTAssertEqual(0, m1) XCTAssertEqual(0, m2) XCTAssertEqual(0, m3) XCTAssertEqual(0, m4) XCTAssertEqual(0, m5) XCTAssertEqual(0, m6) XCTAssertEqual(0, m7) XCTAssertEqual(8, NSDecimalMaxSize) XCTAssertEqual(32767, NSDecimalNoScale) XCTAssertFalse(zero.isNormal) XCTAssertTrue(zero.isFinite) XCTAssertTrue(zero.isZero) XCTAssertFalse(zero.isSubnormal) XCTAssertFalse(zero.isInfinite) XCTAssertFalse(zero.isNaN) XCTAssertFalse(zero.isSignaling) if #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) { let d1 = Decimal(1234567890123456789 as UInt64) XCTAssertEqual(d1._exponent, 0) XCTAssertEqual(d1._length, 4) } } func test_Constants() { XCTAssertEqual(8, NSDecimalMaxSize) XCTAssertEqual(32767, NSDecimalNoScale) let smallest = Decimal(_exponent: 127, _length: 8, _isNegative: 1, _isCompact: 1, _reserved: 0, _mantissa: (UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max)) XCTAssertEqual(smallest, Decimal.leastFiniteMagnitude) let biggest = Decimal(_exponent: 127, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max, UInt16.max)) XCTAssertEqual(biggest, Decimal.greatestFiniteMagnitude) let leastNormal = Decimal(_exponent: -127, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (1, 0, 0, 0, 0, 0, 0, 0)) XCTAssertEqual(leastNormal, Decimal.leastNormalMagnitude) let leastNonzero = Decimal(_exponent: -127, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (1, 0, 0, 0, 0, 0, 0, 0)) XCTAssertEqual(leastNonzero, Decimal.leastNonzeroMagnitude) let pi = Decimal(_exponent: -38, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x6623, 0x7d57, 0x16e7, 0xad0d, 0xaf52, 0x4641, 0xdfa7, 0xec58)) XCTAssertEqual(pi, Decimal.pi) XCTAssertEqual(10, Decimal.radix) XCTAssertTrue(Decimal().isCanonical) XCTAssertFalse(Decimal().isSignalingNaN) XCTAssertFalse(Decimal.nan.isSignalingNaN) XCTAssertTrue(Decimal.nan.isNaN) XCTAssertEqual(.quietNaN, Decimal.nan.floatingPointClass) XCTAssertEqual(.positiveZero, Decimal().floatingPointClass) XCTAssertEqual(.negativeNormal, smallest.floatingPointClass) XCTAssertEqual(.positiveNormal, biggest.floatingPointClass) XCTAssertFalse(Double.nan.isFinite) XCTAssertFalse(Double.nan.isInfinite) } func test_Description() { XCTAssertEqual("0", Decimal().description) XCTAssertEqual("0", Decimal(0).description) XCTAssertEqual("10", Decimal(_exponent: 1, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (1, 0, 0, 0, 0, 0, 0, 0)).description) XCTAssertEqual("10", Decimal(10).description) XCTAssertEqual("123.458", Decimal(_exponent: -3, _length: 2, _isNegative: 0, _isCompact:1, _reserved: 0, _mantissa: (57922, 1, 0, 0, 0, 0, 0, 0)).description) XCTAssertEqual("123.458", Decimal(123.458).description) XCTAssertEqual("123", Decimal(UInt8(123)).description) XCTAssertEqual("45", Decimal(Int8(45)).description) XCTAssertEqual("3.14159265358979323846264338327950288419", Decimal.pi.description) XCTAssertEqual("-30000000000", Decimal(sign: .minus, exponent: 10, significand: Decimal(3)).description) XCTAssertEqual("300000", Decimal(sign: .plus, exponent: 5, significand: Decimal(3)).description) XCTAssertEqual("5", Decimal(signOf: Decimal(3), magnitudeOf: Decimal(5)).description) XCTAssertEqual("-5", Decimal(signOf: Decimal(-3), magnitudeOf: Decimal(5)).description) XCTAssertEqual("5", Decimal(signOf: Decimal(3), magnitudeOf: Decimal(-5)).description) XCTAssertEqual("-5", Decimal(signOf: Decimal(-3), magnitudeOf: Decimal(-5)).description) } func test_ExplicitConstruction() { var explicit = Decimal( _exponent: 0x17f, _length: 0xff, _isNegative: 3, _isCompact: 4, _reserved: UInt32(1<<18 + 1<<17 + 1), _mantissa: (6, 7, 8, 9, 10, 11, 12, 13) ) XCTAssertEqual(0x7f, explicit._exponent) XCTAssertEqual(0x7f, explicit.exponent) XCTAssertEqual(0x0f, explicit._length) XCTAssertEqual(1, explicit._isNegative) XCTAssertEqual(FloatingPointSign.minus, explicit.sign) XCTAssertTrue(explicit.isSignMinus) XCTAssertEqual(0, explicit._isCompact) XCTAssertEqual(UInt32(1<<17 + 1), explicit._reserved) let (m0, m1, m2, m3, m4, m5, m6, m7) = explicit._mantissa XCTAssertEqual(6, m0) XCTAssertEqual(7, m1) XCTAssertEqual(8, m2) XCTAssertEqual(9, m3) XCTAssertEqual(10, m4) XCTAssertEqual(11, m5) XCTAssertEqual(12, m6) XCTAssertEqual(13, m7) explicit._isCompact = 5 explicit._isNegative = 6 XCTAssertEqual(0, explicit._isNegative) XCTAssertEqual(1, explicit._isCompact) XCTAssertEqual(FloatingPointSign.plus, explicit.sign) XCTAssertFalse(explicit.isSignMinus) XCTAssertTrue(explicit.isNormal) let significand = explicit.significand XCTAssertEqual(0, significand._exponent) XCTAssertEqual(0, significand.exponent) XCTAssertEqual(0x0f, significand._length) XCTAssertEqual(0, significand._isNegative) XCTAssertEqual(1, significand._isCompact) XCTAssertEqual(0, significand._reserved) let (sm0, sm1, sm2, sm3, sm4, sm5, sm6, sm7) = significand._mantissa XCTAssertEqual(6, sm0) XCTAssertEqual(7, sm1) XCTAssertEqual(8, sm2) XCTAssertEqual(9, sm3) XCTAssertEqual(10, sm4) XCTAssertEqual(11, sm5) XCTAssertEqual(12, sm6) XCTAssertEqual(13, sm7) let ulp = explicit.ulp XCTAssertEqual(0x7f, ulp.exponent) XCTAssertEqual(1, ulp._length) XCTAssertEqual(0, ulp._isNegative) XCTAssertEqual(1, ulp._isCompact) XCTAssertEqual(0, ulp._reserved) XCTAssertEqual(1, ulp._mantissa.0) XCTAssertEqual(0, ulp._mantissa.1) XCTAssertEqual(0, ulp._mantissa.2) XCTAssertEqual(0, ulp._mantissa.3) XCTAssertEqual(0, ulp._mantissa.4) XCTAssertEqual(0, ulp._mantissa.5) XCTAssertEqual(0, ulp._mantissa.6) XCTAssertEqual(0, ulp._mantissa.7) } func test_Maths() { for i in -2...10 { for j in 0...5 { XCTAssertEqual(Decimal(i*j), Decimal(i) * Decimal(j), "\(Decimal(i*j)) == \(i) * \(j)") XCTAssertEqual(Decimal(i+j), Decimal(i) + Decimal(j), "\(Decimal(i+j)) == \(i)+\(j)") XCTAssertEqual(Decimal(i-j), Decimal(i) - Decimal(j), "\(Decimal(i-j)) == \(i)-\(j)") if j != 0 { let approximation = Decimal(Double(i)/Double(j)) let answer = Decimal(i) / Decimal(j) let answerDescription = answer.description let approximationDescription = approximation.description var failed: Bool = false var count = 0 let SIG_FIG = 14 for (a, b) in zip(answerDescription, approximationDescription) { if a != b { failed = true break } if count == 0 && (a == "-" || a == "0" || a == ".") { continue // don't count these as significant figures } if count >= SIG_FIG { break } count += 1 } XCTAssertFalse(failed, "\(Decimal(i/j)) == \(i)/\(j)") } } } } func test_Misc() { XCTAssertEqual(.minus, Decimal(-5.2).sign) XCTAssertEqual(.plus, Decimal(5.2).sign) var d = Decimal(5.2) XCTAssertEqual(.plus, d.sign) d.negate() XCTAssertEqual(.minus, d.sign) d.negate() XCTAssertEqual(.plus, d.sign) var e = Decimal(0) e.negate() XCTAssertEqual(e, 0) XCTAssertTrue(Decimal(3.5).isEqual(to: Decimal(3.5))) XCTAssertTrue(Decimal.nan.isEqual(to: Decimal.nan)) XCTAssertTrue(Decimal(1.28).isLess(than: Decimal(2.24))) XCTAssertFalse(Decimal(2.28).isLess(than: Decimal(2.24))) XCTAssertTrue(Decimal(1.28).isTotallyOrdered(belowOrEqualTo: Decimal(2.24))) XCTAssertFalse(Decimal(2.28).isTotallyOrdered(belowOrEqualTo: Decimal(2.24))) XCTAssertTrue(Decimal(1.2).isTotallyOrdered(belowOrEqualTo: Decimal(1.2))) XCTAssertTrue(Decimal.nan.isEqual(to: Decimal.nan)) XCTAssertTrue(Decimal.nan.isLess(than: Decimal(0))) XCTAssertFalse(Decimal.nan.isLess(than: Decimal.nan)) XCTAssertTrue(Decimal.nan.isLessThanOrEqualTo(Decimal(0))) XCTAssertTrue(Decimal.nan.isLessThanOrEqualTo(Decimal.nan)) XCTAssertFalse(Decimal.nan.isTotallyOrdered(belowOrEqualTo: Decimal.nan)) XCTAssertFalse(Decimal.nan.isTotallyOrdered(belowOrEqualTo: Decimal(2.3))) XCTAssertTrue(Decimal(2) < Decimal(3)) XCTAssertTrue(Decimal(3) > Decimal(2)) XCTAssertEqual(Decimal(-9), Decimal(1) - Decimal(10)) XCTAssertEqual(Decimal(3), Decimal(2).nextUp) XCTAssertEqual(Decimal(2), Decimal(3).nextDown) XCTAssertEqual(Decimal(-476), Decimal(1024).distance(to: Decimal(1500))) XCTAssertEqual(Decimal(68040), Decimal(386).advanced(by: Decimal(67654))) XCTAssertEqual(Decimal(1.234), abs(Decimal(1.234))) XCTAssertEqual(Decimal(1.234), abs(Decimal(-1.234))) if #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) { XCTAssertTrue(Decimal.nan.magnitude.isNaN) } var a = Decimal(1234) var r = a XCTAssertEqual(.noError, NSDecimalMultiplyByPowerOf10(&r, &a, 1, .plain)) XCTAssertEqual(Decimal(12340), r) a = Decimal(1234) XCTAssertEqual(.noError, NSDecimalMultiplyByPowerOf10(&r, &a, 2, .plain)) XCTAssertEqual(Decimal(123400), r) XCTAssertEqual(.overflow, NSDecimalMultiplyByPowerOf10(&r, &a, 128, .plain)) XCTAssertTrue(r.isNaN) a = Decimal(1234) XCTAssertEqual(.noError, NSDecimalMultiplyByPowerOf10(&r, &a, -2, .plain)) XCTAssertEqual(Decimal(12.34), r) var ur = r XCTAssertEqual(.underflow, NSDecimalMultiplyByPowerOf10(&ur, &r, -128, .plain)) XCTAssertTrue(ur.isNaN) a = Decimal(1234) XCTAssertEqual(.noError, NSDecimalPower(&r, &a, 0, .plain)) XCTAssertEqual(Decimal(1), r) a = Decimal(8) XCTAssertEqual(.noError, NSDecimalPower(&r, &a, 2, .plain)) XCTAssertEqual(Decimal(64), r) a = Decimal(-2) XCTAssertEqual(.noError, NSDecimalPower(&r, &a, 3, .plain)) XCTAssertEqual(Decimal(-8), r) for i in -2...10 { for j in 0...5 { var actual = Decimal(i) var result = actual XCTAssertEqual(.noError, NSDecimalPower(&result, &actual, j, .plain)) let expected = Decimal(pow(Double(i), Double(j))) XCTAssertEqual(expected, result, "\(result) == \(i)^\(j)") if #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) { XCTAssertEqual(expected, pow(actual, j)) } } } } func test_MultiplicationOverflow() { var multiplicand = Decimal(_exponent: 0, _length: 8, _isNegative: 0, _isCompact: 0, _reserved: 0, _mantissa: ( 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff )) var result = Decimal() var multiplier = Decimal(1) multiplier._mantissa.0 = 2 XCTAssertEqual(.noError, NSDecimalMultiply(&result, &multiplicand, &multiplier, .plain), "2 * max mantissa") XCTAssertEqual(.noError, NSDecimalMultiply(&result, &multiplier, &multiplicand, .plain), "max mantissa * 2") multiplier._exponent = 0x7f XCTAssertEqual(.overflow, NSDecimalMultiply(&result, &multiplicand, &multiplier, .plain), "2e127 * max mantissa") XCTAssertEqual(.overflow, NSDecimalMultiply(&result, &multiplier, &multiplicand, .plain), "max mantissa * 2e127") } func test_NaNInput() { var NaN = Decimal.nan var one = Decimal(1) var result = Decimal() XCTAssertNotEqual(.noError, NSDecimalAdd(&result, &NaN, &one, .plain)) XCTAssertTrue(NSDecimalIsNotANumber(&result), "NaN + 1") XCTAssertNotEqual(.noError, NSDecimalAdd(&result, &one, &NaN, .plain)) XCTAssertTrue(NSDecimalIsNotANumber(&result), "1 + NaN") XCTAssertNotEqual(.noError, NSDecimalSubtract(&result, &NaN, &one, .plain)) XCTAssertTrue(NSDecimalIsNotANumber(&result), "NaN - 1") XCTAssertNotEqual(.noError, NSDecimalSubtract(&result, &one, &NaN, .plain)) XCTAssertTrue(NSDecimalIsNotANumber(&result), "1 - NaN") XCTAssertNotEqual(.noError, NSDecimalMultiply(&result, &NaN, &one, .plain)) XCTAssertTrue(NSDecimalIsNotANumber(&result), "NaN * 1") XCTAssertNotEqual(.noError, NSDecimalMultiply(&result, &one, &NaN, .plain)) XCTAssertTrue(NSDecimalIsNotANumber(&result), "1 * NaN") XCTAssertNotEqual(.noError, NSDecimalDivide(&result, &NaN, &one, .plain)) XCTAssertTrue(NSDecimalIsNotANumber(&result), "NaN / 1") XCTAssertNotEqual(.noError, NSDecimalDivide(&result, &one, &NaN, .plain)) XCTAssertTrue(NSDecimalIsNotANumber(&result), "1 / NaN") XCTAssertNotEqual(.noError, NSDecimalPower(&result, &NaN, 0, .plain)) XCTAssertTrue(NSDecimalIsNotANumber(&result), "NaN ^ 0") XCTAssertNotEqual(.noError, NSDecimalPower(&result, &NaN, 4, .plain)) XCTAssertTrue(NSDecimalIsNotANumber(&result), "NaN ^ 4") XCTAssertNotEqual(.noError, NSDecimalPower(&result, &NaN, 5, .plain)) XCTAssertTrue(NSDecimalIsNotANumber(&result), "NaN ^ 5") XCTAssertNotEqual(.noError, NSDecimalMultiplyByPowerOf10(&result, &NaN, 0, .plain)) XCTAssertTrue(NSDecimalIsNotANumber(&result), "NaN e0") XCTAssertNotEqual(.noError, NSDecimalMultiplyByPowerOf10(&result, &NaN, 4, .plain)) XCTAssertTrue(NSDecimalIsNotANumber(&result), "NaN e4") XCTAssertNotEqual(.noError, NSDecimalMultiplyByPowerOf10(&result, &NaN, 5, .plain)) XCTAssertTrue(NSDecimalIsNotANumber(&result), "NaN e5") XCTAssertFalse(Double(truncating: NSDecimalNumber(decimal: Decimal(0))).isNaN) XCTAssertTrue(Decimal(Double.leastNonzeroMagnitude).isNaN) XCTAssertTrue(Decimal(Double.leastNormalMagnitude).isNaN) XCTAssertTrue(Decimal(Double.greatestFiniteMagnitude).isNaN) XCTAssertTrue(Decimal(Double("1e-129")!).isNaN) XCTAssertTrue(Decimal(Double("0.1e-128")!).isNaN) } func test_NegativeAndZeroMultiplication() { var one = Decimal(1) var zero = Decimal(0) var negativeOne = Decimal(-1) var result = Decimal() XCTAssertEqual(.noError, NSDecimalMultiply(&result, &one, &one, .plain), "1 * 1") XCTAssertEqual(.orderedSame, NSDecimalCompare(&one, &result), "1 * 1") XCTAssertEqual(.noError, NSDecimalMultiply(&result, &one, &negativeOne, .plain), "1 * -1") XCTAssertEqual(.orderedSame, NSDecimalCompare(&negativeOne, &result), "1 * -1") XCTAssertEqual(.noError, NSDecimalMultiply(&result, &negativeOne, &one, .plain), "-1 * 1") XCTAssertEqual(.orderedSame, NSDecimalCompare(&negativeOne, &result), "-1 * 1") XCTAssertEqual(.noError, NSDecimalMultiply(&result, &negativeOne, &negativeOne, .plain), "-1 * -1") XCTAssertEqual(.orderedSame, NSDecimalCompare(&one, &result), "-1 * -1") XCTAssertEqual(.noError, NSDecimalMultiply(&result, &one, &zero, .plain), "1 * 0") XCTAssertEqual(.orderedSame, NSDecimalCompare(&zero, &result), "1 * 0") XCTAssertEqual(0, result._isNegative, "1 * 0") XCTAssertEqual(.noError, NSDecimalMultiply(&result, &zero, &one, .plain), "0 * 1") XCTAssertEqual(.orderedSame, NSDecimalCompare(&zero, &result), "0 * 1") XCTAssertEqual(0, result._isNegative, "0 * 1") XCTAssertEqual(.noError, NSDecimalMultiply(&result, &negativeOne, &zero, .plain), "-1 * 0") XCTAssertEqual(.orderedSame, NSDecimalCompare(&zero, &result), "-1 * 0") XCTAssertEqual(0, result._isNegative, "-1 * 0") XCTAssertEqual(.noError, NSDecimalMultiply(&result, &zero, &negativeOne, .plain), "0 * -1") XCTAssertEqual(.orderedSame, NSDecimalCompare(&zero, &result), "0 * -1") XCTAssertEqual(0, result._isNegative, "0 * -1") } func test_Normalize() { var one = Decimal(1) var ten = Decimal(-10) XCTAssertEqual(.noError, NSDecimalNormalize(&one, &ten, .plain)) XCTAssertEqual(Decimal(1), one) XCTAssertEqual(Decimal(-10), ten) XCTAssertEqual(1, one._length) XCTAssertEqual(1, ten._length) one = Decimal(1) ten = Decimal(10) XCTAssertEqual(.noError, NSDecimalNormalize(&one, &ten, .plain)) XCTAssertEqual(Decimal(1), one) XCTAssertEqual(Decimal(10), ten) XCTAssertEqual(1, one._length) XCTAssertEqual(1, ten._length) } func test_NSDecimal() { var nan = Decimal.nan XCTAssertTrue(NSDecimalIsNotANumber(&nan)) var zero = Decimal() XCTAssertFalse(NSDecimalIsNotANumber(&zero)) var three = Decimal(3) var guess = Decimal() NSDecimalCopy(&guess, &three) XCTAssertEqual(three, guess) var f = Decimal(_exponent: 0, _length: 2, _isNegative: 0, _isCompact: 0, _reserved: 0, _mantissa: (0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) let before = f.description XCTAssertEqual(0, f._isCompact) NSDecimalCompact(&f) XCTAssertEqual(1, f._isCompact) let after = f.description XCTAssertEqual(before, after) } func test_RepeatingDivision() { let repeatingNumerator = Decimal(16) let repeatingDenominator = Decimal(9) let repeating = repeatingNumerator / repeatingDenominator let numerator = Decimal(1010) var result = numerator / repeating var expected = Decimal() expected._exponent = -35; expected._length = 8; expected._isNegative = 0; expected._isCompact = 1; expected._reserved = 0; expected._mantissa.0 = 51946; expected._mantissa.1 = 3; expected._mantissa.2 = 15549; expected._mantissa.3 = 55864; expected._mantissa.4 = 57984; expected._mantissa.5 = 55436; expected._mantissa.6 = 45186; expected._mantissa.7 = 10941; XCTAssertEqual(.orderedSame, NSDecimalCompare(&expected, &result), "568.12500000000000000000000000000248554: \(expected.description) != \(result.description)"); } func test_Round() { var testCases = [ // expected, start, scale, round ( 0, 0.5, 0, Decimal.RoundingMode.down ), ( 1, 0.5, 0, Decimal.RoundingMode.up ), ( 2, 2.5, 0, Decimal.RoundingMode.bankers ), ( 4, 3.5, 0, Decimal.RoundingMode.bankers ), ( 5, 5.2, 0, Decimal.RoundingMode.plain ), ( 4.5, 4.5, 1, Decimal.RoundingMode.down ), ( 5.5, 5.5, 1, Decimal.RoundingMode.up ), ( 6.5, 6.5, 1, Decimal.RoundingMode.plain ), ( 7.5, 7.5, 1, Decimal.RoundingMode.bankers ), ( -1, -0.5, 0, Decimal.RoundingMode.down ), ( -2, -2.5, 0, Decimal.RoundingMode.up ), ( -5, -5.2, 0, Decimal.RoundingMode.plain ), ( -4.5, -4.5, 1, Decimal.RoundingMode.down ), ( -5.5, -5.5, 1, Decimal.RoundingMode.up ), ( -6.5, -6.5, 1, Decimal.RoundingMode.plain ), ( -7.5, -7.5, 1, Decimal.RoundingMode.bankers ), ] if #available(macOS 10.16, iOS 14, watchOS 7, tvOS 14, *) { testCases += [ ( -2, -2.5, 0, Decimal.RoundingMode.bankers ), ( -4, -3.5, 0, Decimal.RoundingMode.bankers ), ] } for testCase in testCases { let (expected, start, scale, mode) = testCase var num = Decimal(start) var r = num NSDecimalRound(&r, &num, scale, mode) XCTAssertEqual(Decimal(expected), r) let numnum = NSDecimalNumber(decimal:Decimal(start)) let behavior = NSDecimalNumberHandler(roundingMode: mode, scale: Int16(scale), raiseOnExactness: false, raiseOnOverflow: true, raiseOnUnderflow: true, raiseOnDivideByZero: true) let result = numnum.rounding(accordingToBehavior:behavior) XCTAssertEqual(Double(expected), result.doubleValue) } } func test_ScanDecimal() { let testCases = [ // expected, value ( 123.456e78, "123.456e78" ), ( -123.456e78, "-123.456e78" ), ( 123.456, " 123.456 " ), ( 3.14159, " 3.14159e0" ), ( 3.14159, " 3.14159e-0" ), ( 0.314159, " 3.14159e-1" ), ( 3.14159, " 3.14159e+0" ), ( 31.4159, " 3.14159e+1" ), ( 12.34, " 01234e-02"), ] for testCase in testCases { let (expected, string) = testCase let decimal = Decimal(string:string)! let aboutOne = Decimal(expected) / decimal let approximatelyRight = aboutOne >= Decimal(0.99999) && aboutOne <= Decimal(1.00001) XCTAssertTrue(approximatelyRight, "\(expected) ~= \(decimal) : \(aboutOne) \(aboutOne >= Decimal(0.99999)) \(aboutOne <= Decimal(1.00001))" ) } guard let ones = Decimal(string:"111111111111111111111111111111111111111") else { XCTFail("Unable to parse Decimal(string:'111111111111111111111111111111111111111')") return } let num = ones / Decimal(9) guard let answer = Decimal(string:"12345679012345679012345679012345679012.3") else { XCTFail("Unable to parse Decimal(string:'12345679012345679012345679012345679012.3')") return } XCTAssertEqual(answer,num,"\(ones) / 9 = \(answer) \(num)") } func test_SimpleMultiplication() { var multiplicand = Decimal() multiplicand._isNegative = 0 multiplicand._isCompact = 0 multiplicand._length = 1 multiplicand._exponent = 1 var multiplier = multiplicand multiplier._exponent = 2 var expected = multiplicand expected._isNegative = 0 expected._isCompact = 0 expected._exponent = 3 expected._length = 1 var result = Decimal() for i in 1..<UInt8.max { multiplicand._mantissa.0 = UInt16(i) for j in 1..<UInt8.max { multiplier._mantissa.0 = UInt16(j) expected._mantissa.0 = UInt16(i) * UInt16(j) XCTAssertEqual(.noError, NSDecimalMultiply(&result, &multiplicand, &multiplier, .plain), "\(i) * \(j)") XCTAssertEqual(.orderedSame, NSDecimalCompare(&expected, &result), "\(expected._mantissa.0) == \(i) * \(j)"); } } } func test_ULP() { let x = 0.1 as Decimal XCTAssertFalse(x.ulp > x) } func test_unconditionallyBridgeFromObjectiveC() { XCTAssertEqual(Decimal(), Decimal._unconditionallyBridgeFromObjectiveC(nil)) } func test_parseDouble() throws { XCTAssertEqual(Decimal(Double(0.0)), Decimal(Int.zero)) XCTAssertEqual(Decimal(Double(-0.0)), Decimal(Int.zero)) // These values can only be represented as Decimal.nan XCTAssertEqual(Decimal(Double.nan), Decimal.nan) XCTAssertEqual(Decimal(Double.signalingNaN), Decimal.nan) // These values are out out range for Decimal XCTAssertEqual(Decimal(-Double.leastNonzeroMagnitude), Decimal.nan) XCTAssertEqual(Decimal(Double.leastNonzeroMagnitude), Decimal.nan) XCTAssertEqual(Decimal(-Double.leastNormalMagnitude), Decimal.nan) XCTAssertEqual(Decimal(Double.leastNormalMagnitude), Decimal.nan) XCTAssertEqual(Decimal(-Double.greatestFiniteMagnitude), Decimal.nan) XCTAssertEqual(Decimal(Double.greatestFiniteMagnitude), Decimal.nan) // SR-13837 let testDoubles: [(Double, String)] = [ (1.8446744073709550E18, "1844674407370954752"), (1.8446744073709551E18, "1844674407370954752"), (1.8446744073709552E18, "1844674407370955264"), (1.8446744073709553E18, "1844674407370955264"), (1.8446744073709554E18, "1844674407370955520"), (1.8446744073709555E18, "1844674407370955520"), (1.8446744073709550E19, "18446744073709547520"), (1.8446744073709551E19, "18446744073709552640"), (1.8446744073709552E19, "18446744073709552640"), (1.8446744073709553E19, "18446744073709552640"), (1.8446744073709554E19, "18446744073709555200"), (1.8446744073709555E19, "18446744073709555200"), (1.8446744073709550E20, "184467440737095526400"), (1.8446744073709551E20, "184467440737095526400"), (1.8446744073709552E20, "184467440737095526400"), (1.8446744073709553E20, "184467440737095526400"), (1.8446744073709554E20, "184467440737095552000"), (1.8446744073709555E20, "184467440737095552000"), ] for (d, s) in testDoubles { XCTAssertEqual(Decimal(d), Decimal(string: s)) XCTAssertEqual(Decimal(d).description, try XCTUnwrap(Decimal(string: s)).description) } } func test_initExactly() { // This really requires some tests using a BinaryInteger of bitwidth > 128 to test failures. let d1 = Decimal(exactly: UInt64.max) XCTAssertNotNil(d1) XCTAssertEqual(d1?.description, UInt64.max.description) XCTAssertEqual(d1?._length, 4) let d2 = Decimal(exactly: Int64.min) XCTAssertNotNil(d2) XCTAssertEqual(d2?.description, Int64.min.description) XCTAssertEqual(d2?._length, 4) let d3 = Decimal(exactly: Int64.max) XCTAssertNotNil(d3) XCTAssertEqual(d3?.description, Int64.max.description) XCTAssertEqual(d3?._length, 4) let d4 = Decimal(exactly: Int32.min) XCTAssertNotNil(d4) XCTAssertEqual(d4?.description, Int32.min.description) XCTAssertEqual(d4?._length, 2) let d5 = Decimal(exactly: Int32.max) XCTAssertNotNil(d5) XCTAssertEqual(d5?.description, Int32.max.description) XCTAssertEqual(d5?._length, 2) let d6 = Decimal(exactly: 0) XCTAssertNotNil(d6) XCTAssertEqual(d6, Decimal.zero) XCTAssertEqual(d6?.description, "0") XCTAssertEqual(d6?._length, 0) let d7 = Decimal(exactly: 1) XCTAssertNotNil(d7) XCTAssertEqual(d7?.description, "1") XCTAssertEqual(d7?._length, 1) let d8 = Decimal(exactly: -1) XCTAssertNotNil(d8) XCTAssertEqual(d8?.description, "-1") XCTAssertEqual(d8?._length, 1) } }
45.613734
212
0.610494
1e57b34a7aded2b203f2c957f522f178b59be522
764
//: Playground - noun: a place where people can play import UIKit var array = [1,2,3,4,5,6,7] for number in array { print(number) var test = number test = 2 } print(array) // if else // while let number = 10 switch number { case 0..<5: print("Number is less than 5") case 5...10: print("Number is larger than 5") default: print(number) } let dictionary = ["key1": 1, "key2": 2] for (key, value) in dictionary { print("\(key),\(value)") } array.forEach { number in print(number) } let returnsArray = array.map { (number) -> String in let string = "name is" + "test" + "\n\(number)" return "\(number)" } let result = array.filter { (number) -> Bool in if number > 3 { return true } return false }
16.255319
52
0.598168
21fba13bb694499588a6ee5176979e7c2f35529d
2,541
// // RequestConfig.swift // HttpSessionManager_Example // // Created by macpro on 2019/5/30. // Copyright © 2019 CocoaPods. All rights reserved. // import Foundation import HttpSessionManager import Alamofire import SwiftyJSON /// 此处做自己项目的全局配置。 class RequestConfig: RequestConfigProtocol { /// Adding to path ,retrun URL. public func getBaseURL(path: String) -> URL { return URL(string: "https://github.com")! } /// request headers public var headers: [String: String]? { return nil } /// Alamofire.SessionManager. public var manager: SessionManager { return SessionManager.default } /// plugins used to special deal . public var plugins: [PluginProtocol] { return [] } /// parameters encoding. public var parameterEncoding: ParameterEncoding { return JSONEncoding.default } /// request method. public var requestMethod: HTTPMethod { return .post } /// auto retry once when request failed. public var shouldRetryFailed: Bool { return false } /// request successed statusCode. public var successStatusCode: [Int] { return Array(200..<300) } /// merge pulbic parameters method public func mergePulbicParameters(_ params: [String : Any]?, methodName: String) -> [String : Any] { return params == nil ? [:] : params! } // common encrypt method, include merge common parameters. public func encryptReqeustParameters(_ params: [String : Any], methodName: String) -> [String : Any]? { return params } /// common decrypt method. public func decryptRequestResult(_ jsonData: JSON, methodName: String) -> JSON? { return jsonData } /// time out public var timeoutInterval: TimeInterval { return 10 } /// server return code if request successed. public var successReturnCode: Int { return 1 } /// key of 'ReturnCode' public var returnCodeKey: String { return "ReturnCode" } /// key of 'ReturnMessage' public var returnMsgKey: String { return "ReturnMessage" } /// key of 'Data' public var dataKey: String { return "Data" } /// bad network message. public var badNetworkTip: String { return "网络不给力,请稍后再试" } /// server error message. public var serverErrorTip: String { return "哎呀,加载出错了〜" } }
23.527778
107
0.607241