repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
lemberg/connfa-ios
Pods/SwiftDate/Sources/SwiftDate/Supports/Calendars.swift
1
3114
// // CalendarConvertible.swift // SwiftDate // // Created by Daniele Margutti on 06/06/2018. // Copyright © 2018 SwiftDate. All rights reserved. // import Foundation public typealias Calendars = Calendar.Identifier public protocol CalendarConvertible { func toCalendar() -> Calendar } extension Calendar: CalendarConvertible { public func toCalendar() -> Calendar { return self } internal static func newCalendar(_ calendar: CalendarConvertible, configure: ((inout Calendar) -> Void)? = nil) -> Calendar { var cal = calendar.toCalendar() configure?(&cal) return cal } } extension Calendar.Identifier: CalendarConvertible { public func toCalendar() -> Calendar { return Calendar(identifier: self) } } // MARK: - Support for Calendar.Identifier encoding with Codable extension Calendar.Identifier: CustomStringConvertible { public var description: String { switch self { case .gregorian: return "gregorian" case .buddhist: return "buddhist" case .chinese: return "chinese" case .coptic: return "coptic" case .ethiopicAmeteMihret: return "ethiopicAmeteMihret" case .ethiopicAmeteAlem: return "ethiopicAmeteAlem" case .hebrew: return "hebrew" case .iso8601: return "iso8601" case .indian: return "indian" case .islamic: return "islamic" case .islamicCivil: return "islamicCivil" case .japanese: return "japanese" case .persian: return "persian" case .republicOfChina: return "republicOfChina" case .islamicTabular: return "islamicTabular" case .islamicUmmAlQura: return "islamicUmmAlQura" } } public init(_ rawValue: String) { switch rawValue { case Calendar.Identifier.gregorian.description: self = .gregorian case Calendar.Identifier.buddhist.description: self = .buddhist case Calendar.Identifier.chinese.description: self = .chinese case Calendar.Identifier.coptic.description: self = .coptic case Calendar.Identifier.ethiopicAmeteMihret.description: self = .ethiopicAmeteMihret case Calendar.Identifier.ethiopicAmeteAlem.description: self = .ethiopicAmeteAlem case Calendar.Identifier.hebrew.description: self = .hebrew case Calendar.Identifier.iso8601.description: self = .iso8601 case Calendar.Identifier.indian.description: self = .indian case Calendar.Identifier.islamic.description: self = .islamic case Calendar.Identifier.islamicCivil.description: self = .islamicCivil case Calendar.Identifier.japanese.description: self = .japanese case Calendar.Identifier.persian.description: self = .persian case Calendar.Identifier.republicOfChina.description: self = .republicOfChina case Calendar.Identifier.islamicTabular.description: self = .islamicTabular case Calendar.Identifier.islamicTabular.description: self = .islamicTabular case Calendar.Identifier.islamicUmmAlQura.description: self = .islamicUmmAlQura default: let defaultCalendar = SwiftDate.defaultRegion.calendar.identifier debugPrint("Calendar Identifier '\(rawValue)' not recognized. Using default (\(defaultCalendar))") self = defaultCalendar } } }
apache-2.0
oisinlavery/HackingWithSwift
project11-oisin/project11-oisin/AppDelegate.swift
1
2155
// // AppDelegate.swift // project11-oisin // // Created by Oisín Lavery on 11/12/15. // Copyright © 2015 Oisín Lavery. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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 throttle down OpenGL ES frame rates. 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 inactive 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:. } }
unlicense
CYXiang/CYXSwiftDemo
CYXSwiftDemo/CYXSwiftDemo/Classes/Main/GuideViewController.swift
1
3534
// // NewCharacteristicsViewController.swift // CYXSwiftDemo // // Created by apple开发 on 16/5/5. // Copyright © 2016年 cyx. All rights reserved. // import UIKit class GuideViewController: BaseViewController { private var collectionView: UICollectionView? private var imageNames = ["guide_40_1", "guide_40_2", "guide_40_3", "guide_40_4"] private let cellIdentifier = "GuideCell" private var isHiddenNextButton = true private var pageController = UIPageControl(frame: CGRectMake(0, ScreenHeight - 50, ScreenWidth, 20)) override func viewDidLoad() { super.viewDidLoad() UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.None) buildCollectionView() buildPageController() } // MARK: - Build UI private func buildCollectionView() { let layout = UICollectionViewFlowLayout() layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 layout.itemSize = ScreenBounds.size layout.scrollDirection = UICollectionViewScrollDirection.Horizontal collectionView = UICollectionView(frame: ScreenBounds, collectionViewLayout: layout) collectionView?.delegate = self collectionView?.dataSource = self collectionView?.showsHorizontalScrollIndicator = false collectionView?.showsVerticalScrollIndicator = false collectionView?.pagingEnabled = true collectionView?.bounces = false collectionView?.registerClass(GuideCell.self, forCellWithReuseIdentifier: cellIdentifier) view.addSubview(collectionView!) } private func buildPageController() { pageController.numberOfPages = imageNames.count pageController.currentPage = 0 view.addSubview(pageController) } } extension GuideViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imageNames.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! GuideCell cell.newImage = UIImage(named: imageNames[indexPath.row]) if indexPath.row != imageNames.count - 1 { cell.setNextButtonHidden(true) } return cell } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { if scrollView.contentOffset.x == ScreenWidth * CGFloat(imageNames.count - 1) { let cell = collectionView!.cellForItemAtIndexPath(NSIndexPath(forRow: imageNames.count - 1, inSection: 0)) as! GuideCell cell.setNextButtonHidden(false) isHiddenNextButton = false } } func scrollViewDidScroll(scrollView: UIScrollView) { if scrollView.contentOffset.x != ScreenWidth * CGFloat(imageNames.count - 1) && !isHiddenNextButton && scrollView.contentOffset.x > ScreenWidth * CGFloat(imageNames.count - 2) { let cell = collectionView!.cellForItemAtIndexPath(NSIndexPath(forRow: imageNames.count - 1, inSection: 0)) as! GuideCell cell.setNextButtonHidden(true) isHiddenNextButton = true } pageController.currentPage = Int(scrollView.contentOffset.x / ScreenWidth + 0.5) } }
apache-2.0
fei1990/PageScaledScroll
ScaledPageView/Pods/EZSwiftExtensions/Sources/UIImageExtensions.swift
1
4037
// // UIImageExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import UIKit extension UIImage { /// EZSE: Returns compressed image to rate from 0 to 1 public func compressImage(rate rate: CGFloat) -> NSData? { return UIImageJPEGRepresentation(self, rate) } /// EZSE: Returns Image size in Bytes public func getSizeAsBytes() -> Int { return UIImageJPEGRepresentation(self, 1)?.length ?? 0 } /// EZSE: Returns Image size in Kylobites public func getSizeAsKilobytes() -> Int { let sizeAsBytes = getSizeAsBytes() return sizeAsBytes != 0 ? sizeAsBytes / 1024 : 0 } /// EZSE: scales image public class func scaleTo(image image: UIImage, w: CGFloat, h: CGFloat) -> UIImage { let newSize = CGSize(width: w, height: h) UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) image.drawInRect(CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)) let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } /// EZSE Returns resized image with width. Might return low quality public func resizeWithWidth(width: CGFloat) -> UIImage { let aspectSize = CGSize (width: width, height: aspectHeightForWidth(width)) UIGraphicsBeginImageContext(aspectSize) self.drawInRect(CGRect(origin: CGPoint.zero, size: aspectSize)) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } /// EZSE Returns resized image with height. Might return low quality public func resizeWithHeight(height: CGFloat) -> UIImage { let aspectSize = CGSize (width: aspectWidthForHeight(height), height: height) UIGraphicsBeginImageContext(aspectSize) self.drawInRect(CGRect(origin: CGPoint.zero, size: aspectSize)) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } /// EZSE: public func aspectHeightForWidth(width: CGFloat) -> CGFloat { return (width * self.size.height) / self.size.width } /// EZSE: public func aspectWidthForHeight(height: CGFloat) -> CGFloat { return (height * self.size.width) / self.size.height } /// EZSE: Returns cropped image from CGRect public func croppedImage(bound: CGRect) -> UIImage? { guard self.size.width > bound.origin.x else { print("EZSE: Your cropping X coordinate is larger than the image width") return nil } guard self.size.height > bound.origin.y else { print("EZSE: Your cropping Y coordinate is larger than the image height") return nil } let scaledBounds: CGRect = CGRect(x: bound.x * self.scale, y: bound.y * self.scale, width: bound.w * self.scale, height: bound.h * self.scale) let imageRef = CGImageCreateWithImageInRect(self.CGImage!, scaledBounds) let croppedImage: UIImage = UIImage(CGImage: imageRef!, scale: self.scale, orientation: UIImageOrientation.Up) return croppedImage } ///EZSE: Returns the image associated with the URL public convenience init?(urlString: String) { guard let url = NSURL(string: urlString) else { self.init(data: NSData()) return } guard let data = NSData(contentsOfURL: url) else { print("EZSE: No image in URL \(urlString)") self.init(data: NSData()) return } self.init(data: data) } ///EZSE: Returns an empty image //TODO: Add to readme public class func blankImage() -> UIImage { UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0.0) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
mit
christopherhelf/TouchHeatmap
Source/TouchHeatmapExtensions.swift
2
4120
// // TouchHeatmapExtensions.swift // TouchHeatmap // // Created by Christopher Helf on 27.09.15. // Copyright © 2015 Christopher Helf. All rights reserved. // import Foundation import UIKit /** - UIApplication Extension We exchange implementations of the sendEvent method in order to be able to capture all touches occurring within the application, the other option would be to subclass UIApplication, which is however harder for users to setup */ public protocol SwizzlingInjection: class { static func inject() } class SwizzlingHelper { private static let doOnce: Any? = { UIViewController.inject() return nil }() static func enableInjection() { _ = SwizzlingHelper.doOnce } } extension UIApplication { override open var next: UIResponder? { // Called before applicationDidFinishLaunching SwizzlingHelper.enableInjection() return super.next } // Here we exchange the implementations func swizzleSendEvent() { let original = class_getInstanceMethod(object_getClass(self), #selector(UIApplication.sendEvent(_:))) let swizzled = class_getInstanceMethod(object_getClass(self), #selector(self.sendEventTracked(_:))) method_exchangeImplementations(original!, swizzled!); } // The new method, where we also send touch events to the TouchHeatmap Singleton @objc func sendEventTracked(_ event: UIEvent) { self.sendEventTracked(event) TouchHeatmap.sharedInstance.sendEvent(event: event) } } /** - UIViewController Extension In order to make screenshots and to manage the flows between Controllers, we need to know when a screen was presented. We override the initialization function here and exchange implementations of the viewDidAppear method In addition, we can add a name to a UIViewController so it's name is being tracked more easily */ extension UIViewController : SwizzlingInjection { // Reference for deprecates UIViewController initialize() // https://stackoverflow.com/questions/42824541/swift-3-1-deprecates-initialize-how-can-i-achieve-the-same-thing/42824542#_=_ public static func inject() { // make sure this isn't a subclass guard self === UIViewController.self else { return } let originalSelector = #selector(UIViewController.viewDidAppear(_:)) let swizzledSelector = #selector(viewDidAppearTracked(_:)) let originalMethod = class_getInstanceMethod(self, originalSelector) let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!)) if didAddMethod { class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!)) } else { method_exchangeImplementations(originalMethod!, swizzledMethod!); } } // The struct we storing for the controller's name private struct AssociatedKeys { static var DescriptiveName = "TouchHeatMapViewControllerKeyDefault" } // The variable that's set as the controller's name, default's to the classname var touchHeatmapKey: String { get { if let name = objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String { return name } else { return String.init(describing: self.classForCoder) } } set { objc_setAssociatedObject( self, &AssociatedKeys.DescriptiveName, newValue as NSString?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } // The method where we are tracking @objc func viewDidAppearTracked(_ animated: Bool) { self.viewDidAppearTracked(animated) TouchHeatmap.sharedInstance.viewDidAppear(name: self.touchHeatmapKey) } }
mit
exyte/Macaw
Source/MCAMediaTimingFunctionName_iOS.swift
1
558
// // MCAMediaTimingFunctionName_iOS.swift // Macaw // // Created by Anton Marunko on 27/09/2018. // Copyright © 2018 Exyte. All rights reserved. // import Foundation #if os(iOS) import UIKit public struct MCAMediaTimingFunctionName { static let linear = CAMediaTimingFunctionName.linear static let easeIn = CAMediaTimingFunctionName.easeIn static let easeOut = CAMediaTimingFunctionName.easeOut static let easeInEaseOut = CAMediaTimingFunctionName.easeInEaseOut static let `default` = CAMediaTimingFunctionName.default } #endif
mit
g08m11/Debug
Sample/SampleTests/SampleTests.swift
1
898
// // SampleTests.swift // SampleTests // // Created by 具志堅 雅 on 2015/10/05. // Copyright (c) 2015年 Bloc. All rights reserved. // import UIKit import XCTest class SampleTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
nessBautista/iOSBackup
DataStructsSwift/DataStructsSwift/BinaryTree.swift
1
19617
// // BinaryTree.swift // DataStructsSwift // // Created by Ness on 4/13/17. // Copyright © 2017 Ness. All rights reserved. // import UIKit //MARK: BINARY TREE CLASS public class BinaryTree<T:Comparable> { public var root:BinaryTreeNode<T>? public init(root: T) { self.root = BinaryTreeNode(value:root) } //MARK: ADD public func add(value: T) { guard let root = self.root else { print("Tree is empty") return } self.addHelper(node: root, value: value) } private func addHelper(node: BinaryTreeNode<T>, value: T) { if value < node.value { if let left = node.leftChild { self.addHelper(node: left, value: value) } else { let newNode = BinaryTreeNode(value:value) newNode.parent = node node.leftChild = newNode } } else if value > node.value { if let right = node.rightChild { self.addHelper(node: right, value: value) } else { let newNode = BinaryTreeNode(value:value) newNode.parent = node node.rightChild = newNode } } else { print("Duplicated") } } //MARK: SEARCH public func search(value:T) -> BinaryTreeNode<T>? { //Just in case root is removed at some point guard let root = self.root else { return nil } return self.searchHelper(node: root, value: value) } private func searchHelper(node: BinaryTreeNode<T>, value: T) -> BinaryTreeNode<T>? { if value == node.value { return node } else if value < node.value { if let left = node.leftChild { return self.searchHelper(node: left, value: value) } else { return nil } } else { if let right = node.rightChild { return self.searchHelper(node: right, value: value) } else { return nil } } } //MARK: MINIMUMS AND MAXIMUMS public func getMaximum() -> BinaryTreeNode<T> { if let right = self.root?.rightChild { return self.getMaximumHelper(node: right) } else { return self.root! } } private func getMaximumHelper(node: BinaryTreeNode<T>) -> BinaryTreeNode<T> { if let right = node.rightChild { return self.getMaximumHelper(node: right) } else { return node } } public func getMinimum() -> BinaryTreeNode<T> { if let left = self.root?.leftChild { return self.getMinimumHelper(node: left) } else { return self.root! } } private func getMinimumHelper(node: BinaryTreeNode<T>) -> BinaryTreeNode<T> { if let left = node.leftChild { return self.getMinimumHelper(node: left) } else { return node } } public func getMaximumValue() -> T? { guard let root = self.root else { print("empty tree") return nil } var prev = root.parent var current: BinaryTreeNode<T>? = root while(current != nil) { prev = current current = current?.rightChild } return prev?.value } public func getMinimumValue() -> T? { guard let root = self.root else { print("empty tree") return nil } var prev = root.parent var current:BinaryTreeNode<T>? = root while current != nil { prev = current current = current?.leftChild } return prev?.value } //MARK: ROTATIONS /* Two cases for rotation, it depends if the node being rotated is the root or not */ public func rotateLeft(node:BinaryTreeNode<T>) { //IF THE ROOT IS BEING ROTATED if node.parent == nil { let x = node let y = node.rightChild x.rightChild = y?.leftChild y?.leftChild?.parent = x if x.parent == nil { self.root = y } y?.leftChild = x x.parent = y } else { //Set nodes: X is the rotating node //Y is taking X's place (upward) let x = node let y = node.rightChild //connect y left subtree with x right subtree (optionals take care of validations) x.rightChild = y?.leftChild y?.leftChild?.parent = x //update root if x.parent == nil { self.root = y } //Connect X's Parent with Y <-> //Link x's parent with y y?.parent = x.parent if x === x.parent?.leftChild { //x is the left child x.parent?.leftChild = y } else { //x is the right child x.parent?.rightChild = y } //Put x on y's left y?.leftChild = x x.parent = y } } public func rotateRight(node:BinaryTreeNode<T>) { //IF THE ROOT IS BEING ROTATED if node.parent == nil { let x = node let y = node.leftChild x.leftChild = y?.rightChild y?.rightChild?.parent = x if x.parent == nil { self.root = y } y?.rightChild = x x.parent = y } else { //SET NODES let x = node let y = node.parent //Connect x's right subtree with y's left subtree y?.leftChild = x.rightChild x.rightChild?.parent = y //Update root if y?.parent == nil { self.root = x } //Connect Y's Parent with X <-> //Link y's parent with x x.parent = y?.parent if y === y?.parent?.leftChild { //y is the left child y?.parent?.leftChild = x } else { //y is the right child y?.parent?.rightChild = x } //Put Y on X's right x.rightChild = y y?.parent = x } } //MARK: DELETE public func delete(node: BinaryTreeNode<T>?) { guard let nodeToDelete = node else { return } //We will have 3 cases, node to delete has 2 children, only left, only right if let left = node?.leftChild { if let right = node?.rightChild { } //CASE 2: Node has only left child guard let parent = node?.parent else { //If parent is nil node?.leftChild?.parent = node?.parent //set leftchild's to nil return } //Connect parent to child //If nodeToDelete is the left child, connect to the left only child left.parent = parent if parent.leftChild === nodeToDelete { parent.leftChild = left } else { parent.rightChild = left } } else if let right = node?.rightChild { //CASE 3: Node has only right child guard let parent = node?.parent else { node?.rightChild?.parent = node?.parent return } //Connect parent to child //If nodeToDelete is the left child, connect to the right only child right.parent = parent if parent.leftChild === nodeToDelete { parent.leftChild = right } else { parent.rightChild = right } } } private func connectNode(parent:BinaryTreeNode<T>?, to child:BinaryTreeNode<T>?) { //first check that the parent is not nil guard let p = parent else { child?.parent = parent //set child's parent to nil return } //if the node is the lf } //MARK: HEIGHT AND DEPTH public func height() -> Int { guard let root = self.root else { return 0 } return self.heightHelper(node: root) } private func heightHelper(node: BinaryTreeNode<T>?) -> Int { if node?.rightChild == nil && node?.leftChild == nil { return 0 } else { return 1 + max(self.heightHelper(node: node?.rightChild),self.heightHelper(node: node?.leftChild)) } } public func depth(node:BinaryTreeNode<T>?) -> Int { guard var parent = node?.parent else { return 0 } var depth = 0 while (true) { depth = 1 + depth if let p = parent.parent { parent = p } else { break } } return depth } //MARK: PRINTING FUNCTIONS public func printRBTreeByLevels(nodes:[BinaryTreeNode<T>]) { var children:[BinaryTreeNode<T>] = Array() for node in nodes { print("\(node.value) ") if let leftChild = node.leftChild { children.append(leftChild) } if let rightChild = node.rightChild { children.append(rightChild) } } if children.count > 0 { print("************") printRBTreeByLevels(nodes: children) } } public func inOrder() { guard let root = self.root else { print("Tree empty") return } self.inOrderHelper(node: root) } private func inOrderHelper(node: BinaryTreeNode<T>?) { guard let n = node else { return } self.inOrderHelper(node: n.leftChild) print(n.value) self.inOrderHelper(node: n.rightChild) } public func preOrder() { guard let root = self.root else { print("Tree empty") return } self.preOrderHelper(node: root) } private func preOrderHelper(node: BinaryTreeNode<T>?) { guard let n = node else { return } print(n.value) self.preOrderHelper(node: n.leftChild) self.preOrderHelper(node: n.rightChild) } public func postOrder() { guard let root = self.root else { print("Tree empty") return } self.postOrderHelper(node: root) } private func postOrderHelper(node: BinaryTreeNode<T>?) { guard let n = node else { return } self.postOrderHelper(node: n.leftChild) self.postOrderHelper(node: n.rightChild) print(n.value) } } //MARK: SINGLE NODE CLASS public class BinaryTreeNode<T:Comparable> { public var value: T public var leftChild:BinaryTreeNode? public var rightChild:BinaryTreeNode? public weak var parent:BinaryTreeNode? public convenience init(value:T) { self.init(value: value, left: nil, right: nil, parent: nil) } public init(value:T, left:BinaryTreeNode?, right:BinaryTreeNode?, parent: BinaryTreeNode?) { self.value = value self.leftChild = left self.rightChild = right self.parent = parent } public func insertNodeFromRoot(value: T) { //to maintain the binary search tree property we must ensure that we run the insertNode process from the root node if let _ = self.parent { print("You can only add new nodes from the root node of the tree") return } self.addNode(value: value) } public func addNode(value:T) { if value < self.value { if let left = self.leftChild { left.addNode(value: value) } else { let newNode = BinaryTreeNode(value: value) newNode.parent = self self.leftChild = newNode } } else if value > self.value { if let right = self.rightChild { right.addNode(value: value) } else { let newNode = BinaryTreeNode(value: value) newNode.parent = self self.rightChild = newNode } } else { print("dup") } } public class func traverseInOrder(node: BinaryTreeNode?) { guard let node = node else { return } BinaryTreeNode.traverseInOrder(node: node.leftChild) print(node.value) BinaryTreeNode.traverseInOrder(node: node.rightChild) } public class func traversePreOrder(node: BinaryTreeNode?) { guard let node = node else { return } print(node.value) BinaryTreeNode.traversePreOrder(node: node.leftChild) BinaryTreeNode.traversePreOrder(node: node.rightChild) } public class func traversePostOrder(node: BinaryTreeNode?) { guard let node = node else { return } BinaryTreeNode.traversePostOrder(node: node.leftChild) BinaryTreeNode.traversePostOrder(node: node.rightChild) print(node.value) } public func search(value: T) -> BinaryTreeNode? { if value == self.value { return self } else if value < self.value { guard let left = self.leftChild else { return nil } return left.search(value: value) } else { guard let right = self.rightChild else { return nil } return right.search(value: value) } } public func delete() { if let left = leftChild { if let _ = rightChild { //node has 2 children self.exchangeWithSuccessor() } else { //Node has only left child self.connectParentTo(child: left) } } else if let right = rightChild { //Node has only right child self.connectParentTo(child: right) } else { //Node has no childs self.connectParentTo(child: nil) } //Delete refrences self.parent = nil self.leftChild = nil self.rightChild = nil } private func exchangeWithSuccessor() { //making sure node has both childs guard let right = self.rightChild, let left = self.leftChild else { return } //GET THE SUCCESSOR //The successor is the node with the lowest value in the right subtree let successor = right.minimum() //Disconnect the successor (this won't have any childs because is the minimum value) successor.delete() //CONNECT CURRENT DELETING NODE LEFT AND RIGHT CHILDS TO THE SUCCESSOR //Connect the left child with its new parent successor.leftChild = left left.parent = successor if right !== successor { //if the successor was NOT inmediatly connected to the deleted node successor.rightChild = right right.parent = successor } else { //If the successor was the right child of the deleted node //Then the successor won't have any childs successor.rightChild = nil } //CONNECT THE PARENT self.connectParentTo(child: successor) } private func connectParentTo(child: BinaryTreeNode?) { guard let parent = self.parent else { //set child to nil child?.parent = self.parent return } if parent.leftChild === self { //If self is the left child of its parent parent.leftChild = child child?.parent = parent } else if parent.rightChild === self { //If self is the right child of its parent parent.rightChild = child child?.parent = parent } } public func minimumValue() -> T { if let left = leftChild { return left.minimumValue() } else { return value } } public func maximumValue() -> T { if let right = rightChild { return right.maximumValue() } else { return value } } public func minimum() -> BinaryTreeNode { if let left = leftChild { return left.minimum() } else { return self } } public func maximum() -> BinaryTreeNode { if let right = rightChild { return right.maximum() } else { return self } } public func height()-> Int { if leftChild == nil && rightChild == nil { return 0 } return 1 + max(leftChild?.height() ?? 0, rightChild?.height() ?? 0) } public func depth() -> Int { guard var node = parent else { return 0 } var depth = 1 while let parent = node.parent { depth = depth + 1 node = parent } return depth } }
cc0-1.0
SusanDoggie/Doggie
Sources/DoggieCore/Concurrency/SerialRunLoop.swift
1
2999
// // SerialRunLoop.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. 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. // @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public class SerialRunLoop: @unchecked Sendable { private var queue: AsyncStream<@Sendable () async -> Void>.Continuation! private let in_runloop = TaskLocal(wrappedValue: false) public init(priority: TaskPriority? = nil) { let stream = AsyncStream { self.queue = $0 } let in_runloop = self.in_runloop Task.detached(priority: priority) { await in_runloop.withValue(true) { for await task in stream { await task() } } } } deinit { self.queue.finish() } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension SerialRunLoop { public var inRunloop: Bool { return in_runloop.get() } } @rethrows protocol _Rethrow { associatedtype Success func get() throws -> Success } extension _Rethrow { func _rethrowGet() rethrows -> Success { try get() } } extension Result: _Rethrow { } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension SerialRunLoop { public func perform<T: Sendable>(_ task: @Sendable @escaping () async throws -> T) async rethrows -> T { let result: Result<T, Error> = await withUnsafeContinuation { continuation in self.queue.yield { do { try await continuation.resume(returning: .success(task())) } catch { continuation.resume(returning: .failure(error)) } } } return try result._rethrowGet() } }
mit
kbelter/SnazzyList
SnazzyList/Classes/src/CollectionView/Protocols/GenericCollectionCellSelfSizingProtocol.swift
1
387
// // CollectionView.swift // Noteworth2 // // Created by Kevin on 12/20/18. // Copyright © 2018 Noteworth. All rights reserved. // import UIKit public protocol GenericCollectionCellSelfSizingProtocol { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath, with item: Any) -> CGSize }
apache-2.0
dasdom/IntentionsWithSwift
IntentionsWithSwift/ReverseIntention.swift
1
332
// // ReverseIntention.swift // IntentionsWithSwift // // Created by dasdom on 03.06.14. // Copyright (c) 2014 dasdom. All rights reserved. // import UIKit class ReverseIntention : ChangeIntention { func reverse() { modelContainer.model.setValue(textField.text.reverse, forKeyPath: modelKeyPath) } }
mit
haijianhuo/TopStore
Pods/JSQCoreDataKit/Source/Migrate.swift
2
6703
// // Created by Jesse Squires // https://www.jessesquires.com // // // Documentation // https://jessesquires.github.io/JSQCoreDataKit // // // GitHub // https://github.com/jessesquires/JSQCoreDataKit // // // License // Copyright © 2015 Jesse Squires // Released under an MIT license: https://opensource.org/licenses/MIT // import CoreData import Foundation /** An error type that specifies possible errors that are thrown by calling `CoreDataModel.migrate() throws`. */ public enum MigrationError: Error { /** Specifies that the `NSManagedObjectModel` corresponding to the existing persistent store was not found in the model's bundle. - parameter model: The model that failed to be migrated. */ case sourceModelNotFound(model: CoreDataModel) /** Specifies that an `NSMappingModel` was not found in the model's bundle in the progressive migration 'path'. - parameter sourceModel: The destination managed object model for which a mapping model was not found. */ case mappingModelNotFound(destinationModel: NSManagedObjectModel) } extension CoreDataModel { /** Progressively migrates the persistent store of the `CoreDataModel` based on mapping models found in the model's bundle. If the model returns false from `needsMigration`, then this function does nothing. - throws: If an error occurs, either an `NSError` or a `MigrationError` is thrown. If an `NSError` is thrown, it could specify any of the following: an error checking persistent store metadata, an error from `NSMigrationManager`, or an error from `NSFileManager`. - warning: Migration is only supported for on-disk persistent stores. A complete 'path' of mapping models must exist between the peristent store's version and the model's version. */ public func migrate() throws { guard needsMigration else { return } guard let storeURL = self.storeURL, let storeDirectory = storeType.storeDirectory() else { preconditionFailure("*** Error: migration is only available for on-disk persistent stores. Invalid model: \(self)") } // could also throw NSError from NSPersistentStoreCoordinator guard let sourceModel = try findCompatibleModel(withBundle: bundle, storeType: storeType.type, storeURL: storeURL) else { throw MigrationError.sourceModelNotFound(model: self) } let migrationSteps = try buildMigrationMappingSteps(bundle: bundle, sourceModel: sourceModel, destinationModel: managedObjectModel) for step in migrationSteps { let tempURL = storeDirectory.appendingPathComponent("migration." + ModelFileExtension.sqlite.rawValue) // could throw error from `migrateStoreFromURL` let manager = NSMigrationManager(sourceModel: step.source, destinationModel: step.destination) try manager.migrateStore(from: storeURL, sourceType: storeType.type, options: nil, with: step.mapping, toDestinationURL: tempURL, destinationType: storeType.type, destinationOptions: nil) // could throw file system errors try removeExistingStore() try FileManager.default.moveItem(at: tempURL, to: storeURL) } } } // MARK: Internal internal struct MigrationMappingStep { let source: NSManagedObjectModel let mapping: NSMappingModel let destination: NSManagedObjectModel } internal func findCompatibleModel(withBundle bundle: Bundle, storeType: String, storeURL: URL) throws -> NSManagedObjectModel? { let storeMetadata = try NSPersistentStoreCoordinator.metadataForPersistentStore(ofType: storeType, at: storeURL, options: nil) let modelsInBundle = findModelsInBundle(bundle) for model in modelsInBundle where model.isConfiguration(withName: nil, compatibleWithStoreMetadata: storeMetadata) { return model } return nil } internal func findModelsInBundle(_ bundle: Bundle) -> [NSManagedObjectModel] { guard let modelBundleDirectoryURLs = bundle.urls(forResourcesWithExtension: ModelFileExtension.bundle.rawValue, subdirectory: nil) else { return [] } let modelBundleDirectoryNames = modelBundleDirectoryURLs.flatMap { url -> String? in url.lastPathComponent } let modelVersionFileURLs = modelBundleDirectoryNames.flatMap { name -> [URL]? in bundle.urls(forResourcesWithExtension: ModelFileExtension.versionedFile.rawValue, subdirectory: name) } let managedObjectModels = Array(modelVersionFileURLs.joined()).flatMap { url -> NSManagedObjectModel? in NSManagedObjectModel(contentsOf: url) } return managedObjectModels } internal func buildMigrationMappingSteps(bundle: Bundle, sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel) throws -> [MigrationMappingStep] { var migrationSteps = [MigrationMappingStep]() var nextModel = sourceModel repeat { guard let nextStep = nextMigrationMappingStep(fromSourceModel: nextModel, bundle: bundle) else { throw MigrationError.mappingModelNotFound(destinationModel: nextModel) } migrationSteps.append(nextStep) nextModel = nextStep.destination } while nextModel.entityVersionHashesByName != destinationModel.entityVersionHashesByName return migrationSteps } internal func nextMigrationMappingStep(fromSourceModel sourceModel: NSManagedObjectModel, bundle: Bundle) -> MigrationMappingStep? { let modelsInBundle = findModelsInBundle(bundle) for nextDestinationModel in modelsInBundle where nextDestinationModel.entityVersionHashesByName != sourceModel.entityVersionHashesByName { if let mappingModel = NSMappingModel(from: [bundle], forSourceModel: sourceModel, destinationModel: nextDestinationModel) { return MigrationMappingStep(source: sourceModel, mapping: mappingModel, destination: nextDestinationModel) } } return nil }
mit
BinaryDennis/SwiftPocketBible
Extensions/EquatableExtensions.swift
1
264
extension Equatable { func isAny(of candidates: Self...) -> Bool { return candidates.contains(self) } } /* enum Direction: Equatable { case left, right, up, down } let myDirection = Direction.left myDirection.isAny(of: .up, .down, .left) */
mit
jasperblues/ICLoader
ICLoader.swift
1
7667
//////////////////////////////////////////////////////////////////////////////// // // JASPER BLUES // Copyright 2013 - 2020, Jasper Blues & Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// import UIKit import NanoFrame public class ICLoader: UIView { public static var logoImageName: String? = nil public static var labelFontName: String? = nil private(set) var backgroundView: UIView! private(set) var logoView: UIImageView! private(set) var centerDot: UIView! private(set) var leftDot: UIView! private(set) var rightDot: UIView! private(set) var label: UILabel! public class func present() { let lockQueue = DispatchQueue(label: "self") lockQueue.sync { let controller = UIApplication.shared.keyWindow?.rootViewController var visibleController: UIViewController? if controller is UINavigationController { visibleController = (controller as? UINavigationController)?.visibleViewController } else { visibleController = controller } let loader = ICLoader(withImageName: logoImageName!) DispatchQueue.main.async(execute: { visibleController?.view.addSubview(loader) visibleController?.view.bringSubviewToFront(loader) visibleController?.view.isUserInteractionEnabled = false UIView.transition(with: loader, duration: 0.33, options: [], animations: { loader.frame = visibleController!.view.bounds }) }) } } public class func dismiss() { let controller = UIApplication.shared.keyWindow?.rootViewController var visibleController: UIViewController? if controller is UINavigationController { visibleController = (controller as? UINavigationController)?.visibleViewController } else { visibleController = controller } DispatchQueue.main.async(execute: { for loader in ICLoader.loaders(for: visibleController?.view) { loader.layer.removeAllAnimations() UIView.transition(with: loader, duration: 0.25, options: [.transitionFlipFromTop], animations: { loader.alpha = 0.0 }) { finished in loader.removeFromSuperview() visibleController?.view.isUserInteractionEnabled = true } } }) } public class func loaders(for view: UIView?) -> [ICLoader] { var theHUDs: [ICLoader] = [] for candidate in view?.subviews ?? [] { if candidate is ICLoader { theHUDs.append(candidate as! ICLoader) } } return theHUDs } public class func setImageName(_ imageName: String?) { logoImageName = imageName } public class func setLabelFontName(_ fontName: String?) { labelFontName = fontName } //------------------------------------------------------------------------------------------- // MARK: - Initializers //------------------------------------------------------------------------------------------- public init(withImageName imageName: String) { if (imageName.count) == 0 { fatalError("ICLoader requires a logo image. Set with [ICLoader setImageName:anImageName]") } super.init(frame: CGRect.zero) backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 90)) backgroundView.backgroundColor = UIColor(hex: 0x666677, alpha: 0.8) backgroundView.layer.cornerRadius = 45 backgroundView.clipsToBounds = true addSubview(backgroundView) initLogo(imageName) initDots() initLabel() animate(toDot: rightDot) } public required init?(coder: NSCoder) { fatalError("init with coder is not supported") } //------------------------------------------------------------------------------------------- // MARK: - Overridden Methods //------------------------------------------------------------------------------------------- public override func layoutSubviews() { super.layoutSubviews() backgroundView.centerInSuperView() } //------------------------------------------------------------------------------------------- // MARK: - Private Methods //------------------------------------------------------------------------------------------- private func initLogo(_ logoImageName: String) { if let image = UIImage(named: logoImageName) { logoView = UIImageView(image: image) logoView.size = image.size logoView.center(in: CGRect(x: 0, y: 7, width: 90, height: 45)) logoView.contentMode = .scaleAspectFit backgroundView.addSubview(logoView) } } private func initDots() { let dodWidth: CGFloat = 5 let centerX = (backgroundView.frame.size.width - dodWidth) / 2 let dotY = ((backgroundView.frame.size.height - dodWidth) / 2) + 9 centerDot = UIView(frame: CGRect(x: centerX, y: dotY, width: dodWidth, height: dodWidth)) centerDot.backgroundColor = UIColor.white centerDot.layer.cornerRadius = centerDot.width / 2 centerDot.layer.opacity = 1.0 backgroundView.addSubview(centerDot) leftDot = UIView(frame: CGRect(x: centerX - 11, y: dotY, width: dodWidth, height: dodWidth)) leftDot.backgroundColor = UIColor.white leftDot.layer.cornerRadius = leftDot.width / 2 leftDot.layer.opacity = 0.5 backgroundView.addSubview(leftDot) rightDot = UIView(frame: CGRect(x: centerX + 11, y: dotY, width: dodWidth, height: dodWidth)) rightDot.backgroundColor = UIColor.white rightDot.layer.cornerRadius = rightDot.width / 2 rightDot.layer.opacity = 0.5 backgroundView.addSubview(rightDot) } private func initLabel() { label = UILabel(frame: CGRect(x: 2 + (backgroundView.frame.size.width - 65) / 2, y: 60, width: 65, height: 14)) label.backgroundColor = UIColor.clear label.textColor = UIColor.white label.textAlignment = .center label.font = ICLoader.labelFontName != nil ? UIFont(name: ICLoader.labelFontName!, size: 10) : UIFont.systemFont(ofSize: 10) label.text = "Loading..." backgroundView.addSubview(label) } private func animate(toDot dot: UIView?) { weak var weakSelf = self weak var centerDot = self.centerDot weak var leftDot = self.leftDot weak var rightDot = self.rightDot if let weakSelf = weakSelf { UIView.transition(with: weakSelf, duration: 0.4, options: .curveEaseInOut, animations: { centerDot?.layer.opacity = dot == centerDot ? 1.0 : 0.5 rightDot?.layer.opacity = dot == rightDot ? 1.0 : 0.5 leftDot?.layer.opacity = dot == leftDot ? 1.0 : 0.5 }) { complete in if dot == centerDot { weakSelf.animate(toDot: rightDot) } else if dot == rightDot { weakSelf.animate(toDot: leftDot) } else { weakSelf.animate(toDot: centerDot) } } } } }
apache-2.0
ScoutHarris/WordPress-iOS
WordPress/Classes/Extensions/WPStyleGuide+Aztec.swift
1
1573
import UIKit import WordPressShared extension WPStyleGuide { static let aztecFormatBarInactiveColor: UIColor = UIColor(hexString: "7B9AB1") static let aztecFormatBarActiveColor: UIColor = UIColor(hexString: "11181D") static let aztecFormatBarDisabledColor = WPStyleGuide.greyLighten20() static let aztecFormatBarDividerColor = WPStyleGuide.greyLighten30() static let aztecFormatBarBackgroundColor = UIColor.white static var aztecFormatPickerSelectedCellBackgroundColor: UIColor { get { return (UIDevice.isPad()) ? WPStyleGuide.lightGrey() : WPStyleGuide.greyLighten30() } } static var aztecFormatPickerBackgroundColor: UIColor { get { return (UIDevice.isPad()) ? .white : WPStyleGuide.lightGrey() } } static func configureBetaButton(_ button: UIButton) { button.titleLabel?.font = UIFont.systemFont(ofSize: 11.0) button.layer.borderWidth = 1.0 button.layer.cornerRadius = 3.0 button.tintColor = WPStyleGuide.darkGrey() button.setTitleColor(WPStyleGuide.darkGrey(), for: .disabled) button.layer.borderColor = WPStyleGuide.greyLighten20().cgColor let verticalInset = CGFloat(6.0) let horizontalInset = CGFloat(8.0) button.contentEdgeInsets = UIEdgeInsets(top: verticalInset, left: horizontalInset, bottom: verticalInset, right: horizontalInset) } }
gpl-2.0
duming91/Hear-You
Hear You/Services/Downloader.swift
1
5825
// // Downloader.swift // BaseKit // // Created by 董亚珣 on 16/4/1. // Copyright © 2016年 snow. All rights reserved. // import Foundation import UIKit class Downloader: NSObject { static let sharedDownloader = Downloader() lazy var session: NSURLSession = { let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil) return session }() struct ProgressReporter { struct Task { let downloadTask: NSURLSessionDataTask typealias FinishedAction = NSData -> Void let finishedAction: FinishedAction let progress = NSProgress() let tempData = NSMutableData() let imageTransform: (UIImage -> UIImage)? } let tasks: [Task] var finishedTasksCount = 0 typealias ReportProgress = (progress: Double, image: UIImage?) -> Void let reportProgress: ReportProgress? init(tasks: [Task], reportProgress: ReportProgress?) { self.tasks = tasks self.reportProgress = reportProgress } var totalProgress: Double { let completedUnitCount = tasks.map({ $0.progress.completedUnitCount }).reduce(0, combine: +) let totalUnitCount = tasks.map({ $0.progress.totalUnitCount }).reduce(0, combine: +) return Double(completedUnitCount) / Double(totalUnitCount) } } var progressReporters = [ProgressReporter]() class func downloadDataFromURL(URL: NSURL, reportProgress: ProgressReporter.ReportProgress?, finishedAction: ProgressReporter.Task.FinishedAction) { let downloadTask = sharedDownloader.session.dataTaskWithURL(URL) let task = ProgressReporter.Task(downloadTask: downloadTask, finishedAction: finishedAction, imageTransform: nil) let progressReporter = ProgressReporter(tasks: [task], reportProgress: reportProgress) sharedDownloader.progressReporters.append(progressReporter) downloadTask.resume() } } extension Downloader: NSURLSessionDataDelegate { private func reportProgressAssociatedWithDownloadTask(downloadTask: NSURLSessionDataTask, totalBytes: Int64) { for progressReporter in progressReporters { for i in 0..<progressReporter.tasks.count { if downloadTask == progressReporter.tasks[i].downloadTask { progressReporter.tasks[i].progress.totalUnitCount = totalBytes progressReporter.reportProgress?(progress: progressReporter.totalProgress, image: nil) return } } } } private func reportProgressAssociatedWithDownloadTask(downloadTask: NSURLSessionDataTask, didReceiveData data: NSData) -> Bool { for progressReporter in progressReporters { for i in 0..<progressReporter.tasks.count { if downloadTask == progressReporter.tasks[i].downloadTask { let didReceiveDataBytes = Int64(data.length) progressReporter.tasks[i].progress.completedUnitCount += didReceiveDataBytes progressReporter.tasks[i].tempData.appendData(data) let progress = progressReporter.tasks[i].progress let final = progress.completedUnitCount == progress.totalUnitCount progressReporter.reportProgress?(progress: progressReporter.totalProgress, image: nil) return final } } } return false } private func finishDownloadTask(downloadTask: NSURLSessionDataTask) { for i in 0..<progressReporters.count { for j in 0..<progressReporters[i].tasks.count { if downloadTask == progressReporters[i].tasks[j].downloadTask { let finishedAction = progressReporters[i].tasks[j].finishedAction let data = progressReporters[i].tasks[j].tempData finishedAction(data) progressReporters[i].finishedTasksCount += 1 // 若任务都已完成,移除此 progressReporter if progressReporters[i].finishedTasksCount == progressReporters[i].tasks.count { progressReporters.removeAtIndex(i) } return } } } } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { println("Downloader begin, expectedContentLength:\(response.expectedContentLength)") reportProgressAssociatedWithDownloadTask(dataTask, totalBytes: response.expectedContentLength) completionHandler(.Allow) } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { println("Downloader data.length: \(data.length)") let finish = reportProgressAssociatedWithDownloadTask(dataTask, didReceiveData: data) if finish { println("Downloader finish") finishDownloadTask(dataTask) } } }
gpl-3.0
Stitch7/Vaporizer
App/Application.swift
1
2285
// // Application.swift // Vaporizer // // Created by Christopher Reitz on 29.08.16. // Copyright © 2016 Christopher Reitz. All rights reserved. // import Foundation import Vapor import SwiftyBeaver import SwiftyBeaverVapor final class Application { // MARK: - Properties public var drop: Droplet // MARK: - Initializers public init(testing: Bool = false) { var args = CommandLine.arguments if testing { // Simulate passing `--env=testing` from the command line if testing is true args.append("--env=testing") } drop = Droplet(arguments: args) configureProviders() configureLogging() configurePreparations() configureMiddlewares() configureRoutes() } private func configurePreparations() { // Add preparations from the Preparations folder drop.preparations = preparations } private func configureLogging() { var destinations = [BaseDestination]() destinations.append(ConsoleDestination()) if let logfile = drop.config["app", "logfile"]?.string { let file = FileDestination() file.logFileURL = URL(string: "file://" + logfile)! destinations.append(file) } let provider = SwiftyBeaverProvider(destinations: destinations) drop.addProvider(provider) } private func configureProviders() { // Add providers from the Providers folder do { for provider in providers { try drop.addProvider(provider) } } catch { fatalError("Can not add provider. \(error)") } } private func configureMiddlewares() { // Add middlewares from the Middleware folder drop.middleware += middleware } private func configureRoutes() { // Add routes from the Routes folder publicRoutes(drop) // Protected routes requiring basic authorization let protect = BasicAuthMiddleware() let protectedGroup = drop.grouped(protect) protectedRoutes(drop, protectedGroup: protectedGroup) } // MARK: - Public public func start() { drop.log.info("Starting server") drop.run() } }
mit
twittemb/Weavy
WeavyDemo/WeavyDemo/Services/MoviesService.swift
1
1081
// // MoviesService.swift // WeavyDemo // // Created by Thibault Wittemberg on 17-11-16. // Copyright © 2017 Warp Factor. All rights reserved. // class MoviesService { func wishlistMovies () -> [Movie] { return MoviesRepository.movies.filter { !$0.watched } } func watchedMovies () -> [Movie] { return MoviesRepository.movies.filter { $0.watched } } func movie (forId id: Int) -> Movie { return MoviesRepository.movies.filter { $0.id == id }.first! } func cast (forId id: Int) -> Cast { return CastsRepository.casts.filter { $0.id == id }.first! } func casts (for movie: Movie) -> [Cast] { // Dumb condition to find the casting according to a movie if movie.id % 2 == 0 { return [CastsRepository.casts[0], CastsRepository.casts[2], CastsRepository.casts[4], CastsRepository.casts[6], CastsRepository.casts[8]] } return [CastsRepository.casts[1], CastsRepository.casts[3], CastsRepository.casts[5], CastsRepository.casts[7], CastsRepository.casts[9]] } }
mit
ifLab/WeCenterMobile-iOS
WeCenterMobile/Model/DataObject/DataObject.swift
3
1345
// // DataObject.swift // WeCenterMobile // // Created by Darren Liu on 15/5/8. // Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved. // import CoreData import Foundation enum SearchType: String { case All = "all" case Article = "articles" case Question = "questions" case Topic = "topics" case User = "users" } class DataObject: NSManagedObject { @NSManaged var id: NSNumber! private class func cast<T>(object: NSManagedObject, type: T.Type) -> T { return object as! T } class func cachedObjectWithID(ID: NSNumber) -> Self { return cast(DataManager.defaultManager!.autoGenerate(entityName, ID: ID), type: self) } class func allCachedObjects() -> [DataObject] /* [Self] in not supported. */ { return try! DataManager.defaultManager!.fetchAll(entityName) } class func deleteAllCachedObjects() { try! DataManager.defaultManager!.deleteAllObjectsWithEntityName(entityName) } class func temporaryObject() -> Self { return cast(DataManager.temporaryManager!.create(entityName), type: self) } class var entityName: String { let s = NSStringFromClass(self) return s.characters.split { $0 == "." }.map { String($0) }.last ?? s } }
gpl-2.0
WPO-Foundation/xrecord
CommandLine/CommandLine.swift
1
6993
/* * CommandLine.swift * Copyright (c) 2014 Ben Gollmer. * * 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. */ /* Required for setlocale(3) */ import Darwin let ShortOptionPrefix = "-" let LongOptionPrefix = "--" /* Stop parsing arguments when an ArgumentStopper (--) is detected. This is a GNU getopt * convention; cf. https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html */ let ArgumentStopper = "--" /* Allow arguments to be attached to flags when separated by this character. * --flag=argument is equivalent to --flag argument */ let ArgumentAttacher: Character = "=" /** * The CommandLine class implements a command-line interface for your app. * * To use it, define one or more Options (see Option.swift) and add them to your * CommandLine object, then invoke parse(). Each Option object will be populated with * the value given by the user. * * If any required options are missing or if an invalid value is found, parse() will return * false. You can then call printUsage() to output an automatically-generated usage message. */ open class CommandLine { fileprivate var _arguments: [String] fileprivate var _options: [Option] = [Option]() /** * Initializes a CommandLine object. * * - parameter arguments: Arguments to parse. If omitted, the arguments passed to the app * on the command line will automatically be used. * * - returns: An initalized CommandLine object. */ public init(arguments: [String] = Swift.CommandLine.arguments) { self._arguments = arguments /* Initialize locale settings from the environment */ setlocale(LC_ALL, "") } /* Returns all argument values from flagIndex to the next flag or the end of the argument array. */ fileprivate func _getFlagValues(flagIndex: Int) -> [String] { var args: [String] = [String]() var skipFlagChecks = false /* Grab attached arg, if any */ var attachedArg = _arguments[flagIndex].splitByCharacter(ArgumentAttacher, maxSplits: 1) if attachedArg.count > 1 { args.append(attachedArg[1]) } for i in flagIndex + 1 ..< _arguments.count { if !skipFlagChecks { if _arguments[i] == ArgumentStopper { skipFlagChecks = true continue } if _arguments[i].hasPrefix(ShortOptionPrefix) && Int(_arguments[i]) == nil && _arguments[i].toDouble() == nil { break } } args.append(_arguments[i]) } return args } /** * Adds an Option to the command line. * * - parameter option: The option to add. */ open func addOption(_ option: Option) { _options.append(option) } /** * Adds one or more Options to the command line. * * - parameter options: An array containing the options to add. */ open func addOptions(_ options: [Option]) { _options += options } /** * Adds one or more Options to the command line. * * - parameter options: The options to add. */ open func addOptions(_ options: Option...) { _options += options } /** * Sets the command line Options. Any existing options will be overwritten. * * - parameter options: An array containing the options to set. */ open func setOptions(_ options: [Option]) { _options = options } /** * Sets the command line Options. Any existing options will be overwritten. * * - parameter options: The options to set. */ open func setOptions(_ options: Option...) { _options = options } /** * Parses command-line arguments into their matching Option values. * * - returns: True if all arguments were parsed successfully, false if any option had an * invalid value or if a required option was missing. */ open func parse() -> (Bool, String?) { for (idx, arg) in _arguments.enumerated() { if arg == ArgumentStopper { break } if !arg.hasPrefix(ShortOptionPrefix) { continue } /* Swift strings don't have substringFromIndex(). Do a little dance instead. */ var flag = "" var skipChars = arg.hasPrefix(LongOptionPrefix) ? LongOptionPrefix.characters.count : ShortOptionPrefix.characters.count for c in arg.characters { if skipChars > 0 { skipChars -= 1 continue } flag.append(c) } /* Remove attached argument from flag */ flag = flag.splitByCharacter(ArgumentAttacher, maxSplits: 1)[0] var flagMatched = false for option in _options { if flag == option.shortFlag || flag == option.longFlag { let vals = self._getFlagValues(flagIndex: idx) if !option.match(vals) { return (false, "Invalid value for \(option.longFlag)") } flagMatched = true break } } /* Flags that do not take any arguments can be concatenated */ if !flagMatched && !arg.hasPrefix(LongOptionPrefix) { for (i, c) in flag.characters.enumerated() { let flagLength = flag.characters.count for option in _options { if String(c) == option.shortFlag { /* Values are allowed at the end of the concatenated flags, e.g. * -xvf <file1> <file2> */ let vals = (i == flagLength - 1) ? self._getFlagValues(flagIndex: idx) : [String]() if !option.match(vals) { return (false, "Invalid value for \(option.longFlag)") } break } } } } } /* Check to see if any required options were not matched */ for option in _options { if option.required && !option.isSet { return (false, "\(option.longFlag) is required") } } return (true, nil) } /** Prints a usage message to stdout. */ open func printUsage() { let name = _arguments[0] var flagWidth = 0 for opt in _options { flagWidth = max(flagWidth, " \(ShortOptionPrefix)\(opt.shortFlag), \(LongOptionPrefix)\(opt.longFlag):".characters.count) } print("Usage: \(name) [options]") for opt in _options { let flags = " \(ShortOptionPrefix)\(opt.shortFlag), \(LongOptionPrefix)\(opt.longFlag):".paddedToWidth(flagWidth) print("\(flags)\n \(opt.helpMessage)") } } }
bsd-3-clause
AutomationStation/BouncerBuddy
BouncerBuddyV6/BouncerBuddy/AppDelegate.swift
4
6093
// // AppDelegate.swift // BouncerBuddy // // Created by Sha Wu on 16/3/2. // Copyright © 2016年 Sheryl Hong. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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 throttle down OpenGL ES frame rates. 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 inactive 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "hong.BouncerBuddy" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("BouncerBuddy", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
apache-2.0
nathawes/swift
stdlib/private/StdlibCollectionUnittest/CheckRangeReplaceableCollectionType.swift
21
41497
//===----------------------------------------------------------------------===// // // 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 StdlibUnittest internal enum IndexSelection { case start case middle case end case last internal func index<C : Collection>(in c: C) -> C.Index { switch self { case .start: return c.startIndex case .middle: return c.index(c.startIndex, offsetBy: c.count / 2) case .end: return c.endIndex case .last: return c.index(c.startIndex, offsetBy: c.count - 1) } } } public struct ReplaceSubrangeTest { public let collection: [OpaqueValue<Int>] public let newElements: [OpaqueValue<Int>] public let rangeSelection: RangeSelection public let expected: [Int] public let closedExpected: [Int]? // Expected array for closed ranges public let loc: SourceLoc internal init( collection: [Int], newElements: [Int], rangeSelection: RangeSelection, expected: [Int], closedExpected: [Int]? = nil, file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.newElements = newElements.map(OpaqueValue.init) self.rangeSelection = rangeSelection self.expected = expected self.closedExpected = closedExpected self.loc = SourceLoc(file, line, comment: "replaceSubrange() test data") } } internal struct AppendTest { let collection: [OpaqueValue<Int>] let newElement: OpaqueValue<Int> let expected: [Int] let loc: SourceLoc internal init( collection: [Int], newElement: Int, expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.newElement = OpaqueValue(newElement) self.expected = expected self.loc = SourceLoc(file, line, comment: "append() test data") } } internal struct AppendContentsOfTest { let collection: [OpaqueValue<Int>] let newElements: [OpaqueValue<Int>] let expected: [Int] let loc: SourceLoc internal init( collection: [Int], newElements: [Int], expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.newElements = newElements.map(OpaqueValue.init) self.expected = expected self.loc = SourceLoc(file, line, comment: "append() test data") } } internal struct InsertTest { let collection: [OpaqueValue<Int>] let newElement: OpaqueValue<Int> let indexSelection: IndexSelection let expected: [Int] let loc: SourceLoc internal init( collection: [Int], newElement: Int, indexSelection: IndexSelection, expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.newElement = OpaqueValue(newElement) self.indexSelection = indexSelection self.expected = expected self.loc = SourceLoc(file, line, comment: "insert() test data") } } internal struct InsertContentsOfTest { let collection: [OpaqueValue<Int>] let newElements: [OpaqueValue<Int>] let indexSelection: IndexSelection let expected: [Int] let loc: SourceLoc internal init( collection: [Int], newElements: [Int], indexSelection: IndexSelection, expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.newElements = newElements.map(OpaqueValue.init) self.indexSelection = indexSelection self.expected = expected self.loc = SourceLoc(file, line, comment: "insert(contentsOf:at:) test data") } } internal struct RemoveAtIndexTest { let collection: [OpaqueValue<Int>] let indexSelection: IndexSelection let expectedRemovedElement: Int let expectedCollection: [Int] let loc: SourceLoc internal init( collection: [Int], indexSelection: IndexSelection, expectedRemovedElement: Int, expectedCollection: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.indexSelection = indexSelection self.expectedRemovedElement = expectedRemovedElement self.expectedCollection = expectedCollection self.loc = SourceLoc(file, line, comment: "remove(at:) test data") } } internal struct RemoveLastNTest { let collection: [OpaqueValue<Int>] let numberToRemove: Int let expectedCollection: [Int] let loc: SourceLoc internal init( collection: [Int], numberToRemove: Int, expectedCollection: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.numberToRemove = numberToRemove self.expectedCollection = expectedCollection self.loc = SourceLoc(file, line, comment: "removeLast(n: Int) test data") } } public struct RemoveSubrangeTest { public let collection: [OpaqueValue<Int>] public let rangeSelection: RangeSelection public let expected: [Int] public let loc: SourceLoc internal init( collection: [Int], rangeSelection: RangeSelection, expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.rangeSelection = rangeSelection self.expected = expected self.loc = SourceLoc(file, line, comment: "removeSubrange() test data") } } internal struct RemoveAllTest { let collection: [OpaqueValue<Int>] let expected: [Int] let loc: SourceLoc internal init( collection: [Int], expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.expected = expected self.loc = SourceLoc(file, line, comment: "removeAll() test data") } } internal struct ReserveCapacityTest { let collection: [OpaqueValue<Int>] let requestedCapacity: Int let loc: SourceLoc internal init( collection: [Int], requestedCapacity: Int, file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.requestedCapacity = requestedCapacity self.loc = SourceLoc(file, line, comment: "removeAll() test data") } } internal struct OperatorPlusTest { let lhs: [OpaqueValue<Int>] let rhs: [OpaqueValue<Int>] let expected: [Int] let loc: SourceLoc internal init( lhs: [Int], rhs: [Int], expected: [Int], file: String = #file, line: UInt = #line ) { self.lhs = lhs.map(OpaqueValue.init) self.rhs = rhs.map(OpaqueValue.init) self.expected = expected self.loc = SourceLoc(file, line, comment: "`func +` test data") } } let removeLastTests: [RemoveLastNTest] = [ RemoveLastNTest( collection: [1010], numberToRemove: 0, expectedCollection: [1010] ), RemoveLastNTest( collection: [1010], numberToRemove: 1, expectedCollection: [] ), RemoveLastNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 0, expectedCollection: [1010, 2020, 3030, 4040, 5050] ), RemoveLastNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 1, expectedCollection: [1010, 2020, 3030, 4040] ), RemoveLastNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 2, expectedCollection: [1010, 2020, 3030] ), RemoveLastNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 3, expectedCollection: [1010, 2020] ), RemoveLastNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 4, expectedCollection: [1010] ), RemoveLastNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 5, expectedCollection: [] ), ] let appendContentsOfTests: [AppendContentsOfTest] = [ AppendContentsOfTest( collection: [], newElements: [], expected: []), AppendContentsOfTest( collection: [1010], newElements: [], expected: [1010]), AppendContentsOfTest( collection: [1010, 2020, 3030, 4040], newElements: [], expected: [1010, 2020, 3030, 4040]), AppendContentsOfTest( collection: [], newElements: [1010], expected: [1010]), AppendContentsOfTest( collection: [1010], newElements: [2020], expected: [1010, 2020]), AppendContentsOfTest( collection: [1010], newElements: [2020, 3030, 4040], expected: [1010, 2020, 3030, 4040]), AppendContentsOfTest( collection: [1010, 2020, 3030, 4040], newElements: [5050, 6060, 7070, 8080], expected: [1010, 2020, 3030, 4040, 5050, 6060, 7070, 8080]), ] // Also used in RangeReplaceable.swift.gyb to test `replaceSubrange()` // overloads with the countable range types. public let replaceRangeTests: [ReplaceSubrangeTest] = [ ReplaceSubrangeTest( collection: [], newElements: [], rangeSelection: .emptyRange, expected: []), ReplaceSubrangeTest( collection: [], newElements: [1010], rangeSelection: .emptyRange, expected: [1010]), ReplaceSubrangeTest( collection: [], newElements: [1010, 2020, 3030], rangeSelection: .emptyRange, expected: [1010, 2020, 3030]), ReplaceSubrangeTest( collection: [4040], newElements: [1010, 2020, 3030], rangeSelection: .leftEdge, expected: [1010, 2020, 3030, 4040], closedExpected: [1010, 2020, 3030]), ReplaceSubrangeTest( collection: [1010, 2020, 3030], newElements: [4040], rangeSelection: .leftEdge, expected: [4040, 1010, 2020, 3030], closedExpected: [4040, 2020, 3030]), ReplaceSubrangeTest( collection: [1010], newElements: [2020, 3030, 4040], rangeSelection: .rightEdge, expected: [1010, 2020, 3030, 4040], closedExpected: [2020, 3030, 4040]), ReplaceSubrangeTest( collection: [1010, 2020, 3030], newElements: [4040], rangeSelection: .rightEdge, expected: [1010, 2020, 3030, 4040], closedExpected: [1010, 2020, 4040]), ReplaceSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050], newElements: [9090], rangeSelection: .offsets(1, 1), expected: [1010, 9090, 2020, 3030, 4040, 5050], closedExpected: [1010, 9090, 3030, 4040, 5050]), ReplaceSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050], newElements: [9090], rangeSelection: .offsets(1, 2), expected: [1010, 9090, 3030, 4040, 5050], closedExpected: [1010, 9090, 4040, 5050]), ReplaceSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050], newElements: [9090], rangeSelection: .offsets(1, 3), expected: [1010, 9090, 4040, 5050], closedExpected: [1010, 9090, 5050]), ReplaceSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050], newElements: [9090], rangeSelection: .offsets(1, 4), expected: [1010, 9090, 5050], closedExpected: [1010, 9090]), ReplaceSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050], newElements: [9090], rangeSelection: .offsets(1, 5), expected: [1010, 9090]), ReplaceSubrangeTest( collection: [1010, 2020, 3030], newElements: [8080, 9090], rangeSelection: .offsets(1, 2), expected: [1010, 8080, 9090, 3030], closedExpected: [1010, 8080, 9090]), ] public let removeRangeTests: [RemoveSubrangeTest] = [ RemoveSubrangeTest( collection: [], rangeSelection: .emptyRange, expected: []), RemoveSubrangeTest( collection: [1010], rangeSelection: .middle, expected: []), RemoveSubrangeTest( collection: [1010, 2020, 3030, 4040], rangeSelection: .leftHalf, expected: [3030, 4040]), RemoveSubrangeTest( collection: [1010, 2020, 3030, 4040], rangeSelection: .rightHalf, expected: [1010, 2020]), RemoveSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050], rangeSelection: .middle, expected: [1010, 5050]), RemoveSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050, 6060], rangeSelection: .leftHalf, expected: [4040, 5050, 6060]), RemoveSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050, 6060], rangeSelection: .rightHalf, expected: [1010, 2020, 3030]), RemoveSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050, 6060], rangeSelection: .middle, expected: [1010, 6060]), ] extension TestSuite { /// Adds a set of tests for `RangeReplaceableCollection`. /// /// - parameter makeCollection: a factory function that creates a collection /// instance with provided elements. /// /// This facility can be used to test collection instances that can't be /// constructed using APIs in the protocol (for example, `Array`s that wrap /// `NSArray`s). public func addRangeReplaceableCollectionTests< C : RangeReplaceableCollection, CollectionWithEquatableElement : RangeReplaceableCollection >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Element, extractValue: @escaping (C.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ([CollectionWithEquatableElement.Element]) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping (MinimalEquatableValue) -> CollectionWithEquatableElement.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Element) -> MinimalEquatableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1, collectionIsBidirectional: Bool = false ) where CollectionWithEquatableElement.Element : Equatable { var testNamePrefix = testNamePrefix if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } addCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset, collectionIsBidirectional: collectionIsBidirectional ) func makeWrappedCollection(_ elements: [OpaqueValue<Int>]) -> C { return makeCollection(elements.map(wrapValue)) } testNamePrefix += String(describing: C.Type.self) //===----------------------------------------------------------------------===// // init() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).init()/semantics") { let c = C() expectEqualSequence([], c.map { extractValue($0).value }) } //===----------------------------------------------------------------------===// // init(Sequence) //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).init(Sequence)/semantics") { for test in appendContentsOfTests { let c = C(test.newElements.map(wrapValue)) expectEqualSequence( test.newElements.map { $0.value }, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // replaceSubrange() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).replaceSubrange()/range/semantics") { for test in replaceRangeTests { var c = makeWrappedCollection(test.collection) let rangeToReplace = test.rangeSelection.range(in: c) let newElements = MinimalCollection(elements: test.newElements.map(wrapValue)) c.replaceSubrange(rangeToReplace, with: newElements) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).replaceSubrange()/closedRange/semantics") { for test in replaceRangeTests { guard let closedExpected = test.closedExpected else { continue } var c = makeWrappedCollection(test.collection) let rangeToReplace = test.rangeSelection.closedRange(in: c) let newElements = makeWrappedCollection(test.newElements) c.replaceSubrange(rangeToReplace, with: newElements) expectEqualSequence( closedExpected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // append() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).append()/semantics") { let tests: [AppendTest] = [ AppendTest( collection: [], newElement: 1010, expected: [1010]), AppendTest( collection: [1010], newElement: 2020, expected: [1010, 2020]), AppendTest( collection: [1010, 2020, 3030, 4040, 5050, 6060, 7070], newElement: 8080, expected: [1010, 2020, 3030, 4040, 5050, 6060, 7070, 8080]), ] for test in tests { var c = makeWrappedCollection(test.collection) let newElement = wrapValue(test.newElement) c.append(newElement) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // append(contentsOf:) //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).append(contentsOf:)/semantics") { for test in appendContentsOfTests { var c = makeWrappedCollection(test.collection) let newElements = MinimalCollection(elements: test.newElements.map(wrapValue)) c.append(contentsOf: newElements) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).OperatorPlusEquals") { for test in appendContentsOfTests { var c = makeWrappedCollection(test.collection) let newElements = MinimalCollection(elements: test.newElements.map(wrapValue)) c += newElements expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // insert() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).insert()/semantics") { let tests: [InsertTest] = [ InsertTest( collection: [], newElement: 1010, indexSelection: IndexSelection.start, expected: [1010]), InsertTest( collection: [2020], newElement: 1010, indexSelection: .start, expected: [1010, 2020]), InsertTest( collection: [1010], newElement: 2020, indexSelection: .end, expected: [1010, 2020]), InsertTest( collection: [2020, 3030, 4040, 5050], newElement: 1010, indexSelection: .start, expected: [1010, 2020, 3030, 4040, 5050]), InsertTest( collection: [1010, 2020, 3030, 4040], newElement: 5050, indexSelection: .end, expected: [1010, 2020, 3030, 4040, 5050]), InsertTest( collection: [1010, 2020, 4040, 5050], newElement: 3030, indexSelection: .middle, expected: [1010, 2020, 3030, 4040, 5050]), ] for test in tests { var c = makeWrappedCollection(test.collection) let newElement = wrapValue(test.newElement) c.insert(newElement, at: test.indexSelection.index(in: c)) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // insert(contentsOf:at:) //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).insert(contentsOf:at:)/semantics") { let tests: [InsertContentsOfTest] = [ InsertContentsOfTest( collection: [], newElements: [], indexSelection: IndexSelection.start, expected: []), InsertContentsOfTest( collection: [], newElements: [1010], indexSelection: .start, expected: [1010]), InsertContentsOfTest( collection: [], newElements: [1010, 2020, 3030, 4040], indexSelection: .start, expected: [1010, 2020, 3030, 4040]), InsertContentsOfTest( collection: [2020], newElements: [1010], indexSelection: .start, expected: [1010, 2020]), InsertContentsOfTest( collection: [1010], newElements: [2020], indexSelection: .end, expected: [1010, 2020]), InsertContentsOfTest( collection: [4040], newElements: [1010, 2020, 3030], indexSelection: .start, expected: [1010, 2020, 3030, 4040]), InsertContentsOfTest( collection: [1010], newElements: [2020, 3030, 4040], indexSelection: .end, expected: [1010, 2020, 3030, 4040]), InsertContentsOfTest( collection: [1010, 2020, 4040, 5050], newElements: [3030], indexSelection: .middle, expected: [1010, 2020, 3030, 4040, 5050]), InsertContentsOfTest( collection: [4040, 5050, 6060], newElements: [1010, 2020, 3030], indexSelection: .start, expected: [1010, 2020, 3030, 4040, 5050, 6060]), InsertContentsOfTest( collection: [1010, 2020, 3030], newElements: [4040, 5050, 6060], indexSelection: .end, expected: [1010, 2020, 3030, 4040, 5050, 6060]), InsertContentsOfTest( collection: [1010, 2020, 3030, 7070, 8080, 9090], newElements: [4040, 5050, 6060], indexSelection: .middle, expected: [1010, 2020, 3030, 4040, 5050, 6060, 7070, 8080, 9090]), ] for test in tests { var c = makeWrappedCollection(test.collection) let newElements = MinimalCollection(elements: test.newElements.map(wrapValue)) c.insert(contentsOf: newElements, at: test.indexSelection.index(in: c)) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // remove(at:) //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).remove(at:)/semantics") { let tests: [RemoveAtIndexTest] = [ RemoveAtIndexTest( collection: [1010], indexSelection: .start, expectedRemovedElement: 1010, expectedCollection: []), RemoveAtIndexTest( collection: [1010, 2020, 3030], indexSelection: .start, expectedRemovedElement: 1010, expectedCollection: [2020, 3030]), RemoveAtIndexTest( collection: [1010, 2020, 3030], indexSelection: .middle, expectedRemovedElement: 2020, expectedCollection: [1010, 3030]), RemoveAtIndexTest( collection: [1010, 2020, 3030], indexSelection: .last, expectedRemovedElement: 3030, expectedCollection: [1010, 2020]), ] for test in tests { var c = makeWrappedCollection(test.collection) let removedElement = c.remove(at: test.indexSelection.index(in: c)) expectEqualSequence( test.expectedCollection, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqual( test.expectedRemovedElement, extractValue(removedElement).value, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // removeFirst() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).removeFirst()/semantics") { for test in removeFirstTests.filter({ $0.numberToRemove == 1 }) { var c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) let removedElement = c.removeFirst() expectEqual(test.collection.first, extractValue(removedElement).value) expectEqualSequence( test.expectedCollection, c.map { extractValue($0).value }, "removeFirst() shouldn't mutate the tail of the collection", stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).removeFirst()/empty/semantics") { var c = makeWrappedCollection(Array<OpaqueValue<Int>>()) expectCrashLater() _ = c.removeFirst() // Should trap. } //===----------------------------------------------------------------------===// // removeFirst(n: Int) //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).removeFirst(n: Int)/semantics") { for test in removeFirstTests { var c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) c.removeFirst(test.numberToRemove) expectEqualSequence( test.expectedCollection, c.map { extractValue($0).value }, "removeFirst() shouldn't mutate the tail of the collection", stackTrace: SourceLocStack().with(test.loc) ) } } self.test("\(testNamePrefix).removeFirst(n: Int)/empty/semantics") { var c = makeWrappedCollection(Array<OpaqueValue<Int>>()) expectCrashLater() c.removeFirst(1) // Should trap. } self.test("\(testNamePrefix).removeFirst(n: Int)/removeNegative/semantics") { var c = makeWrappedCollection([1010, 2020, 3030].map(OpaqueValue.init)) expectCrashLater() c.removeFirst(-1) // Should trap. } self.test("\(testNamePrefix).removeFirst(n: Int)/removeTooMany/semantics") { var c = makeWrappedCollection([1010, 2020, 3030].map(OpaqueValue.init)) expectCrashLater() c.removeFirst(5) // Should trap. } //===----------------------------------------------------------------------===// // removeSubrange() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).removeSubrange()/range/semantics") { for test in removeRangeTests { var c = makeWrappedCollection(test.collection) let rangeToRemove = test.rangeSelection.range(in: c) c.removeSubrange(rangeToRemove) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).replaceSubrange()/closedRange/semantics") { for test in removeRangeTests.filter({ !$0.rangeSelection.isEmpty }) { var c = makeWrappedCollection(test.collection) let rangeToRemove = test.rangeSelection.closedRange(in: c) c.removeSubrange(rangeToRemove) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // removeAll() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).removeAll()/semantics") { let tests: [RemoveAllTest] = [ RemoveAllTest( collection: [], expected: []), RemoveAllTest( collection: [1010], expected: []), RemoveAllTest( collection: [1010, 2020, 3030, 4040, 5050], expected: []), ] for test in tests { var c = makeWrappedCollection(test.collection) c.removeAll() expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } for test in tests { var c = makeWrappedCollection(test.collection) c.removeAll(keepingCapacity: false) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } for test in tests { var c = makeWrappedCollection(test.collection) c.removeAll(keepingCapacity: true) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // reserveCapacity() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).reserveCapacity()/semantics") { let tests: [ReserveCapacityTest] = [ ReserveCapacityTest( collection: [], requestedCapacity: 0), ReserveCapacityTest( collection: [], requestedCapacity: 3), ReserveCapacityTest( collection: [], requestedCapacity: 100), ReserveCapacityTest( collection: [ 1010 ], requestedCapacity: 0), ReserveCapacityTest( collection: [ 1010 ], requestedCapacity: 3), ReserveCapacityTest( collection: [ 1010 ], requestedCapacity: 100), ReserveCapacityTest( collection: [ 1010, 2020, 3030 ], requestedCapacity: 0), ReserveCapacityTest( collection: [ 1010, 2020, 3030 ], requestedCapacity: 3), ReserveCapacityTest( collection: [ 1010, 2020, 3030 ], requestedCapacity: 100), ] for test in tests { var c = makeWrappedCollection(test.collection) c.reserveCapacity(test.requestedCapacity) expectEqualSequence( test.collection.map { $0.value }, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // + operator //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).OperatorPlus") { let tests: [OperatorPlusTest] = [ OperatorPlusTest( lhs: [], rhs: [], expected: []), OperatorPlusTest( lhs: [], rhs: [ 1010 ], expected: [ 1010 ]), OperatorPlusTest( lhs: [ 1010 ], rhs: [], expected: [ 1010 ]), OperatorPlusTest( lhs: [ 1010 ], rhs: [ 2020 ], expected: [ 1010, 2020 ]), OperatorPlusTest( lhs: [ 1010, 2020, 3030 ], rhs: [], expected: [ 1010, 2020, 3030 ]), OperatorPlusTest( lhs: [], rhs: [ 1010, 2020, 3030 ], expected: [ 1010, 2020, 3030 ]), OperatorPlusTest( lhs: [ 1010 ], rhs: [ 2020, 3030, 4040 ], expected: [ 1010, 2020, 3030, 4040 ]), OperatorPlusTest( lhs: [ 1010, 2020, 3030 ], rhs: [ 4040 ], expected: [ 1010, 2020, 3030, 4040 ]), OperatorPlusTest( lhs: [ 1010, 2020, 3030, 4040 ], rhs: [ 5050, 6060, 7070 ], expected: [ 1010, 2020, 3030, 4040, 5050, 6060, 7070 ]), OperatorPlusTest( lhs: [ 1010, 2020, 3030 ], rhs: [ 4040, 5050, 6060, 7070 ], expected: [ 1010, 2020, 3030, 4040, 5050, 6060, 7070 ]), ] // RangeReplaceableCollection + Sequence for test in tests { let lhs = makeWrappedCollection(test.lhs) let rhs = MinimalSequence(elements: test.rhs.map(wrapValue)) let result = lhs + rhs expectEqualSequence( test.expected, result.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.lhs.map { $0.value }, lhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } // Sequence + RangeReplaceableCollection for test in tests { let lhs = MinimalSequence(elements: test.lhs.map(wrapValue)) let rhs = makeWrappedCollection(test.rhs) let result = lhs + rhs expectEqualSequence( test.expected, result.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.rhs.map { $0.value }, rhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } // RangeReplaceableCollection + Collection for test in tests { let lhs = makeWrappedCollection(test.lhs) let rhs = MinimalCollection(elements: test.rhs.map(wrapValue)) let result = lhs + rhs expectEqualSequence( test.expected, result.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.lhs.map { $0.value }, lhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.rhs.map { $0.value }, rhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } // RangeReplaceableCollection + same RangeReplaceableCollection for test in tests { let lhs = makeWrappedCollection(test.lhs) let rhs = makeWrappedCollection(test.rhs) let result = lhs + rhs expectEqualSequence( test.expected, result.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.lhs.map { $0.value }, lhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.rhs.map { $0.value }, rhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } // RangeReplaceableCollection + MinimalRangeReplaceableCollection for test in tests { let lhs = makeWrappedCollection(test.lhs) let rhs = MinimalRangeReplaceableCollection( elements: test.rhs.map(wrapValue)) let result = lhs + rhs expectEqualSequence( test.expected, result.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.lhs.map { $0.value }, lhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.rhs.map { $0.value }, rhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } // MinimalRangeReplaceableCollection + RangeReplaceableCollection for test in tests { let lhs = MinimalRangeReplaceableCollection( elements: test.lhs.map(wrapValue)) let rhs = makeWrappedCollection(test.rhs) let result = lhs + rhs expectEqualSequence( test.expected, result.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.lhs.map { $0.value }, lhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.rhs.map { $0.value }, rhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// } // addRangeReplaceableCollectionTests public func addRangeReplaceableBidirectionalCollectionTests< C : BidirectionalCollection & RangeReplaceableCollection, CollectionWithEquatableElement : BidirectionalCollection & RangeReplaceableCollection >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Element, extractValue: @escaping (C.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ([CollectionWithEquatableElement.Element]) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping (MinimalEquatableValue) -> CollectionWithEquatableElement.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Element) -> MinimalEquatableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1 ) where CollectionWithEquatableElement.Element : Equatable { var testNamePrefix = testNamePrefix if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } addRangeReplaceableCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset, collectionIsBidirectional: true ) addBidirectionalCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset) func makeWrappedCollection(_ elements: [OpaqueValue<Int>]) -> C { return makeCollection(elements.map(wrapValue)) } testNamePrefix += String(describing: C.Type.self) //===----------------------------------------------------------------------===// // removeLast() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).removeLast()/whereIndexIsBidirectional/semantics") { for test in removeLastTests.filter({ $0.numberToRemove == 1 }) { var c = makeWrappedCollection(test.collection) let removedElement = c.removeLast() expectEqual( test.collection.last!.value, extractValue(removedElement).value, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.expectedCollection, c.map { extractValue($0).value }, "removeLast() shouldn't mutate the head of the collection", stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).removeLast()/whereIndexIsBidirectional/empty/semantics") { var c = makeWrappedCollection([]) expectCrashLater() _ = c.removeLast() // Should trap. } //===----------------------------------------------------------------------===// // removeLast(n: Int) //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/semantics") { for test in removeLastTests { var c = makeWrappedCollection(test.collection) c.removeLast(test.numberToRemove) expectEqualSequence( test.expectedCollection, c.map { extractValue($0).value }, "removeLast() shouldn't mutate the head of the collection", stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/empty/semantics") { var c = makeWrappedCollection([]) expectCrashLater() c.removeLast(1) // Should trap. } self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/removeNegative/semantics") { var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init)) expectCrashLater() c.removeLast(-1) // Should trap. } self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/removeTooMany/semantics") { var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init)) expectCrashLater() c.removeLast(3) // Should trap. } //===----------------------------------------------------------------------===// } // addRangeReplaceableBidirectionalCollectionTests public func addRangeReplaceableRandomAccessCollectionTests< C : RandomAccessCollection & RangeReplaceableCollection, CollectionWithEquatableElement : RandomAccessCollection & RangeReplaceableCollection >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Element, extractValue: @escaping (C.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ([CollectionWithEquatableElement.Element]) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping (MinimalEquatableValue) -> CollectionWithEquatableElement.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Element) -> MinimalEquatableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1 ) where CollectionWithEquatableElement.Element : Equatable { var testNamePrefix = testNamePrefix if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } addRangeReplaceableBidirectionalCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset) addRandomAccessCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset) testNamePrefix += String(describing: C.Type.self) // No extra checks for collections with random access traversal so far. } // addRangeReplaceableRandomAccessCollectionTests }
apache-2.0
practicalswift/swift
validation-test/stdlib/Slice/Slice_Of_MinimalMutableRandomAccessCollection_WithSuffix.swift
16
3432
// -*- swift -*- //===----------------------------------------------------------------------===// // Automatically Generated From validation-test/stdlib/Slice/Inputs/Template.swift.gyb // Do Not Edit Directly! //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // FIXME: the test is too slow when the standard library is not optimized. // REQUIRES: optimized_stdlib import StdlibUnittest import StdlibCollectionUnittest var SliceTests = TestSuite("Collection") let prefix: [Int] = [] let suffix: [Int] = [] func makeCollection(elements: [OpaqueValue<Int>]) -> Slice<MinimalMutableRandomAccessCollection<OpaqueValue<Int>>> { var baseElements = prefix.map(OpaqueValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(OpaqueValue.init)) let base = MinimalMutableRandomAccessCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfEquatable(elements: [MinimalEquatableValue]) -> Slice<MinimalMutableRandomAccessCollection<MinimalEquatableValue>> { var baseElements = prefix.map(MinimalEquatableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalEquatableValue.init)) let base = MinimalMutableRandomAccessCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfComparable(elements: [MinimalComparableValue]) -> Slice<MinimalMutableRandomAccessCollection<MinimalComparableValue>> { var baseElements = prefix.map(MinimalComparableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalComparableValue.init)) let base = MinimalMutableRandomAccessCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior = .trap SliceTests.addMutableRandomAccessCollectionTests( "Slice_Of_MinimalMutableRandomAccessCollection_WithSuffix.swift.", makeCollection: makeCollection, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, makeCollectionOfComparable: makeCollectionOfComparable, wrapValueIntoComparable: identityComp, extractValueFromComparable: identityComp, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: 6 , withUnsafeMutableBufferPointerIsSupported: false, isFixedLengthCollection: true ) runAllTests()
apache-2.0
renatoguarato/cidadaoalerta
apps/ios/cidadaoalerta/cidadaoalerta/DetalhesExecucaoFinanceiraViewController.swift
1
1956
// // DetalhesExecucaoFinanceiraViewController.swift // cidadaoalerta // // Created by Renato Guarato on 26/03/16. // Copyright © 2016 Renato Guarato. All rights reserved. // import UIKit class DetalhesExecucaoFinanceiraViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var items = [DetalheTabela]() override func viewDidLoad() { super.viewDidLoad() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "tableCell") self.tableView.dataSource = self self.tableView.delegate = self self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 160.0 self.automaticallyAdjustsScrollViewInsets = false self.items = [DetalheTabela("Número Proposta", "1591"), DetalheTabela("Modalidade", "Prestação de Contas em Análise"), DetalheTabela("Órgão Superior", "MINISTERIO DO DESENV. SOCIAL E COMBATE A FOME"), DetalheTabela("Valor", "R$ 347.926,32")] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func btnVoltar(sender: AnyObject) { self.navigationController?.popViewControllerAnimated(true) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! DetailViewCell let empenho = self.items[indexPath.row] cell.lblColunaDetalheExecucaoFinanceira.text = empenho.coluna cell.lblValorDetalheExecucaoFinanceira.text = empenho.valor return cell } }
gpl-3.0
FardadCo/LaraCrypt
Example/Tests/Tests.swift
1
759
import UIKit import XCTest import LaraCrypt class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
mit
blockchain/My-Wallet-V3-iOS
Modules/BlockchainComponentLibrary/Tests/BlockchainComponentLibraryTests/2 - Primitives/Buttons/AlertButtonTests.swift
1
736
// Copyright © Blockchain Luxembourg S.A. All rights reserved. @testable import BlockchainComponentLibrary import SnapshotTesting import SwiftUI import XCTest final class AlertButtonTests: XCTestCase { override func setUp() { super.setUp() isRecording = false } func testSnapshot() { let view = VStack(spacing: 5) { AlertButton_Previews.previews } .frame(width: 320) .fixedSize() .padding() assertSnapshots( matching: view, as: [ .image(traits: UITraitCollection(userInterfaceStyle: .light)), .image(traits: UITraitCollection(userInterfaceStyle: .dark)) ] ) } }
lgpl-3.0
aaronbrethorst/onebusaway-iphone
OneBusAway/ui/privacy/PIIViewController.swift
1
5004
// // PIIViewController.swift // org.onebusaway.iphone // // Created by Aaron Brethorst on 10/1/16. // Copyright © 2016 OneBusAway. All rights reserved. // import UIKit import OBAKit class PIIViewController: OBAStaticTableViewController { lazy var privacyBroker: PrivacyBroker = { return OBAApplication.shared().privacyBroker }() // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() self.title = NSLocalizedString("Information for Support", comment: "Title of the PIIViewController") self.tableView.tableHeaderView = OBAUIBuilder.footerView(withText: NSLocalizedString("This information is only sent to OneBusAway when you submit a support request. You can disable sending us any or all of this data, but it will limit our ability to diagnose and fix problems you are experiencing.", comment: "The footer label on the PIIViewController"), maximumWidth: self.tableView.frame.width) self.reloadData() // self.tableFooterView = OBAUIBuilder.footerView(text: NSLocalizedString("This information is only sent to OneBusAway when you submit a support request. You can disable sending us any or all of this data, but it will limit our ability to diagnose and fix problems you are experiencing.", comment: "The footer label on the PIIViewController"), maximumWidth: self.tableView.frame.width) } // MARK: - Table Sections func reloadData() { let regionSection = self.buildRegionSection() let locationSection = self.buildLocationSection() let logsSection = self.buildLogsSection() self.sections = [regionSection, locationSection, logsSection] self.tableView.reloadData() } func buildRegionSection() -> OBATableSection { let regionSection = OBATableSection.init(title: NSLocalizedString("Region", comment: "Region section title on PII controller")) regionSection.addRow { return OBASwitchRow.init(title: NSLocalizedString("Share Current Region", comment: "Region switch row on PII Controller"), action: { self.privacyBroker.toggleShareRegionInformation() self.reloadData() }, switchValue: self.privacyBroker.canShareRegionInformation) } regionSection.addRow { let row: OBATableRow = OBATableRow.init(title: NSLocalizedString("View Data", comment: "View data row on PII controller"), action: { self.showData(self.privacyBroker.shareableRegionInformation().description) }) row.accessoryType = .disclosureIndicator return row } return regionSection } func buildLocationSection() -> OBATableSection { let locationSection = OBATableSection.init(title: NSLocalizedString("Location", comment: "Location section title on PII controller")) locationSection.addRow { return OBASwitchRow.init(title: NSLocalizedString("Share Location", comment: "Location switch row on PII Controller"), action: { self.privacyBroker.toggleShareLocationInformation() self.reloadData() }, switchValue: self.privacyBroker.canShareLocationInformation) } locationSection.addRow { let row: OBATableRow = OBATableRow.init(title: NSLocalizedString("View Data", comment: "View data row on PII controller"), action: { var locationInfo = self.privacyBroker.shareableLocationInformation if locationInfo == nil { locationInfo = "NOPE" } self.showData(locationInfo!) }) row.accessoryType = .disclosureIndicator return row } return locationSection } func buildLogsSection() -> OBATableSection { let shareRow = OBASwitchRow.init(title: NSLocalizedString("Share Logs", comment: "Share logs action row title in the PII controller"), action: { self.privacyBroker.toggleShareLogs() self.reloadData() }, switchValue: self.privacyBroker.canShareLogs) let viewDataRow = OBATableRow.init(title: NSLocalizedString("View Data", comment: "View data row on PII controller"), action: { let logController = PTERootController.init() self.navigationController?.pushViewController(logController, animated: true) }) viewDataRow.accessoryType = .disclosureIndicator let section = OBATableSection.init(title: NSLocalizedString("Logs", comment: "Logs table section in the PII controller"), rows: [shareRow, viewDataRow]) return section } // MARK: - Data Display func showData(_ data: String) { let alert = UIAlertController.init(title: nil, message: data, preferredStyle: .alert) alert.addAction(UIAlertAction.init(title: OBAStrings.dismiss(), style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } }
apache-2.0
FindGF/_BiliBili
WTBilibili/Mine-我的/GameCenter-游戏中心/Model/WTGameCenterItem.swift
1
887
// // WTGameCenterItem.swift // WTBilibili // // Created by 无头骑士 GJ on 16/6/12. // Copyright © 2016年 无头骑士 GJ. All rights reserved. // 游戏中心模型 import UIKit /* "id":34, "title":"ICHU偶像进行曲", "summary":"把我变成真正的偶像吧!", "download_link":"http://acg.tv/u15b", "cover":"http://i2.hdslb.com/u_user/bf4e35133f507513abffc242967b2287.jpg", "hot":0, "new":0 */ class WTGameCenterItem: NSObject { // MARK: - 属性 var id: Int = 0 var title: String! var summary: String! var download_link: String! var cover: NSURL! var hot: Int = 0 var new: Int = 0 init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forUndefinedKey key: String) {} }
apache-2.0
zmian/xcore.swift
Sources/Xcore/SwiftUI/Components/DynamicTextField/Configuration/TextFieldConfiguration+Person.swift
1
1976
// // Xcore // Copyright © 2021 Xcore // MIT license, see LICENSE file for details // import SwiftUI extension TextFieldConfiguration { public enum PersonNameComponent: String { case fullName case firstName case middleName case lastName } } // MARK: - Person Components extension TextFieldConfiguration where Formatter == PassthroughTextFieldFormatter { public static func person(component: PersonNameComponent) -> Self { switch component { case .fullName: return fullName case .firstName: return firstName case .middleName: return middleName case .lastName: return lastName } } /// Name private static var fullName: Self { .init( id: #function, autocapitalization: .words, autocorrection: .default, spellChecking: .default, keyboard: .default, textContentType: .name ) } /// First Name private static var firstName: Self { .init( id: #function, autocapitalization: .words, autocorrection: .default, spellChecking: .default, keyboard: .default, textContentType: .givenName ) } /// Last Name private static var lastName: Self { .init( id: #function, autocapitalization: .words, autocorrection: .default, spellChecking: .default, keyboard: .default, textContentType: .familyName ) } /// Middle Name private static var middleName: Self { .init( id: #function, autocapitalization: .words, autocorrection: .default, spellChecking: .default, keyboard: .default, textContentType: .middleName ) } }
mit
otokunaga2/ibeacon-swift-tutorial
iBeaconTemplateSwift/AppDelegate.swift
1
6572
// // AppDelegate.swift // iBeaconTemplateSwift // // Created by James Nick Sears on 7/1/14. // Copyright (c) 2014 iBeaconModules.us. All rights reserved. // import UIKit import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate { var window: UIWindow? var locationManager: CLLocationManager? var lastProximity: CLProximity? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { // let uuidString = "00000000-F80B-1001-B000-001C4D47FBC6" let uuidString = "E2C56DB5-DFFB-48D2-B060-D0F5A71096E0" let beaconIdentifier = "iBeaconModules.us" let beaconUUID:NSUUID = NSUUID(UUIDString: uuidString) let beaconRegion:CLBeaconRegion = CLBeaconRegion(proximityUUID: beaconUUID, identifier: beaconIdentifier) locationManager = CLLocationManager() if(locationManager!.respondsToSelector("requestAlwaysAuthorization")) { locationManager!.requestAlwaysAuthorization() } locationManager!.delegate = self locationManager!.pausesLocationUpdatesAutomatically = false locationManager!.startMonitoringForRegion(beaconRegion) locationManager!.startRangingBeaconsInRegion(beaconRegion) locationManager!.startUpdatingLocation() if(application.respondsToSelector("registerUserNotificationSettings:")) { application.registerUserNotificationSettings( UIUserNotificationSettings( forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Sound, categories: nil ) ) } 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 throttle down OpenGL ES frame rates. 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 inactive 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:. } } extension AppDelegate: CLLocationManagerDelegate { func sendLocalNotificationWithMessage(message: String!, playSound: Bool) { let notification:UILocalNotification = UILocalNotification() notification.alertBody = message if(playSound) { // classic star trek communicator beep // http://www.trekcore.com/audio/ // // note: convert mp3 and wav formats into caf using: // "afconvert -f caff -d LEI16@44100 -c 1 in.wav out.caf" // http://stackoverflow.com/a/10388263 notification.soundName = "tos_beep.caf"; } UIApplication.sharedApplication().scheduleLocalNotification(notification) } func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) { let viewController:ViewController = window!.rootViewController as ViewController viewController.beacons = beacons as [CLBeacon]? viewController.tableView!.reloadData() NSLog("didRangeBeacons"); var message:String = "" var playSound = false if(beacons.count > 0) { let nearestBeacon:CLBeacon = beacons[0] as CLBeacon if(nearestBeacon.proximity == lastProximity || nearestBeacon.proximity == CLProximity.Unknown) { return; } lastProximity = nearestBeacon.proximity; switch nearestBeacon.proximity { case CLProximity.Far: message = "You are far away from the beacon" playSound = true case CLProximity.Near: message = "You are near the beacon" case CLProximity.Immediate: message = "You are in the immediate proximity of the beacon" case CLProximity.Unknown: return } } else { if(lastProximity == CLProximity.Unknown) { return; } message = "No beacons are nearby" playSound = true lastProximity = CLProximity.Unknown } NSLog("%@", message) sendLocalNotificationWithMessage(message, playSound: playSound) } func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) { manager.startRangingBeaconsInRegion(region as CLBeaconRegion) manager.startUpdatingLocation() NSLog("You entered the region") sendLocalNotificationWithMessage("You entered the region", playSound: false) } func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) { manager.stopRangingBeaconsInRegion(region as CLBeaconRegion) manager.stopUpdatingLocation() NSLog("You exited the region") sendLocalNotificationWithMessage("You exited the region", playSound: true) } }
mit
janslow/qlab-from-csv
QLab From CSV/QLabFromCsv/CsvParser.swift
1
3676
// // csv.swift // QLab From CSV // // Created by Jay Anslow on 20/12/2014. // Copyright (c) 2014 Jay Anslow. All rights reserved. // import Foundation public class CsvParser { public class func csv() -> CsvParser { return CsvParser(delimiter: ",") } private var delimiter : String init(delimiter : String) { self.delimiter = delimiter } func parse(contents : String) -> (headers: [String], rows: [Dictionary<String,String>])? { var lines: [String] = [] contents.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet()).enumerateLines { line, stop in lines.append(line) } if lines.count < 1 { log.error("CSV Parser: There must be at least one line including the header.") return nil } let headers = lines[0].componentsSeparatedByString(",").map({ (s : String) -> String in return s.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) }) var rows : [Dictionary<String, String>] = [] for (lineNumber, line) in enumerate(lines) { if lineNumber == 0 { continue } var row = Dictionary<String, String>() let scanner = NSScanner(string: line) let delimiter = "," let doubleQuote = NSCharacterSet(charactersInString: "\"") let whitespace = NSCharacterSet.whitespaceCharacterSet() for (index, header) in enumerate(headers) { scanner.scanCharactersFromSet(whitespace, intoString: nil) var value : NSString = "" if scanner.scanCharactersFromSet(doubleQuote, intoString: nil) { var result : NSString? while true { scanner.scanUpToCharactersFromSet(doubleQuote, intoString: &result) if result != nil { value = value + result! } if scanner.scanString("\"\"", intoString: nil) { value = value + "\"" } else { scanner.scanCharactersFromSet(doubleQuote, intoString: nil) break } } } else { var result : NSString? // Case where value is not quoted scanner.scanUpToString(delimiter, intoString: &result) if result != nil { value = result! } } // Trim whitespace var trimmedVal = value.stringByTrimmingCharactersInSet(whitespace) // If value is non-empty store it in the row if !trimmedVal.isEmpty { row[header] = trimmedVal } // Remove whitespace and comma scanner.scanCharactersFromSet(whitespace, intoString: nil) scanner.scanString(delimiter, intoString: nil) } rows.append(row) } return (headers, rows) } func parseFromFile(path : String) -> (headers: [String], rows: [Dictionary<String,String>])? { if let contents = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) { return parse(contents) } else { log.error("CSV Parser: Unable to read CSV file.") return nil } } }
mit
Fitbit/RxBluetoothKit
Tests/Autogenerated/_Peripheral+Convenience.generated.swift
2
18249
import Foundation import CoreBluetooth @testable import RxBluetoothKit import RxSwift // swiftlint:disable line_length extension _Peripheral { /// Function used to receive service with given identifier. It's taken from cache if it's available, /// or directly by `discoverServices` call /// - Parameter identifier: Unique identifier of _Service /// - Returns: `Single` which emits `next` event, when specified service has been found. /// /// Observable can ends with following errors: /// * `RxError.noElements` /// * `_BluetoothError.servicesDiscoveryFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func service(with identifier: ServiceIdentifier) -> Single<_Service> { return .deferred { [weak self] in guard let strongSelf = self else { throw _BluetoothError.destroyed } if let services = strongSelf.services, let service = services.first(where: { $0.uuid == identifier.uuid }) { return .just(service) } else { return strongSelf.discoverServices([identifier.uuid]) .map { if let service = $0.first { return service } throw RxError.noElements } } } } /// Function used to receive characteristic with given identifier. If it's available it's taken from cache. /// Otherwise - directly by `discoverCharacteristics` call /// - Parameter identifier: Unique identifier of _Characteristic, that has information /// about service which characteristic belongs to. /// - Returns: `Single` which emits `next` event, when specified characteristic has been found. /// /// Observable can ends with following errors: /// * `RxError.noElements` /// * `_BluetoothError.characteristicsDiscoveryFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func characteristic(with identifier: CharacteristicIdentifier) -> Single<_Characteristic> { return .deferred { [weak self] in guard let strongSelf = self else { throw _BluetoothError.destroyed } return strongSelf.service(with: identifier.service) .flatMap { service -> Single<_Characteristic> in if let characteristics = service.characteristics, let characteristic = characteristics.first(where: { $0.uuid == identifier.uuid }) { return .just(characteristic) } return service.discoverCharacteristics([identifier.uuid]) .map { if let characteristic = $0.first { return characteristic } throw RxError.noElements } } } } /// Function used to receive descriptor with given identifier. If it's available it's taken from cache. /// Otherwise - directly by `discoverDescriptor` call /// - Parameter identifier: Unique identifier of _Descriptor, that has information /// about characteristic which descriptor belongs to. /// - Returns: `Single` which emits `next` event, when specified descriptor has been found. /// /// Observable can ends with following errors: /// * `RxError.noElements` /// * `_BluetoothError.descriptorsDiscoveryFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func descriptor(with identifier: DescriptorIdentifier) -> Single<_Descriptor> { return .deferred { [weak self] in guard let strongSelf = self else { throw _BluetoothError.destroyed } return strongSelf.characteristic(with: identifier.characteristic) .flatMap { characteristic -> Single<_Descriptor> in if let descriptors = characteristic.descriptors, let descriptor = descriptors.first(where: { $0.uuid == identifier.uuid }) { return .just(descriptor) } return characteristic.discoverDescriptors() .map { if let descriptor = $0.filter({ $0.uuid == identifier.uuid }).first { return descriptor } throw RxError.noElements } } } } /// Function that allow to observe writes that happened for characteristic. /// - Parameter identifier: Identifier of characteristic of which value writes should be observed. /// - Returns: Observable that emits `next` with `_Characteristic` instance every time when write has happened. /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `_BluetoothError.characteristicWriteFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func observeWrite(for identifier: CharacteristicIdentifier) -> Observable<_Characteristic> { return characteristic(with: identifier) .asObservable() .flatMap { [weak self] in self?.observeWrite(for: $0) ?? .error(_BluetoothError.destroyed) } } /// Function that triggers write of data to characteristic. Write is called after subscribtion to `Observable` is made. /// Behavior of this function strongly depends on [CBCharacteristicWriteType](https://developer.apple.com/documentation/corebluetooth/cbcharacteristicwritetype), /// so be sure to check this out before usage of the method. /// - parameter data: Data that'll be written written to `_Characteristic` instance /// - parameter forCharacteristicWithIdentifier: unique identifier of characteristic, which also holds information about service characteristic belongs to. /// - parameter type: Type of write operation. Possible values: `.withResponse`, `.withoutResponse` /// - returns: Observable that emition depends on `CBCharacteristicWriteType` passed to the function call. /// Behavior is following: /// - `WithResponse` - Observable emits `next` with `_Characteristic` instance write was confirmed without any errors. /// Immediately after that `complete` is called. If any problem has happened, errors are emitted. /// - `WithoutResponse` - Observable emits `next` with `_Characteristic` instance once write was called. /// Immediately after that `.complete` is called. Result of this call is not checked, so as a user you are not sure /// if everything completed successfully. Errors are not emitted /// /// Observable can ends with following errors: /// * `_BluetoothError.characteristicWriteFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func writeValue(_ data: Data, for identifier: CharacteristicIdentifier, type: CBCharacteristicWriteType) -> Single<_Characteristic> { return characteristic(with: identifier) .flatMap { [weak self] in self?.writeValue(data, for: $0, type: type) ?? .error(_BluetoothError.destroyed) } } /// Function that allow to observe value updates for `_Characteristic` instance. /// - Parameter identifier: unique identifier of characteristic, which also holds information about service that characteristic belongs to. /// - Returns: Observable that emits `next` with `_Characteristic` instance every time when value has changed. /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `_BluetoothError.characteristicReadFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func observeValueUpdate(for identifier: CharacteristicIdentifier) -> Observable<_Characteristic> { return characteristic(with: identifier) .asObservable() .flatMap { [weak self] in self?.observeValueUpdate(for: $0).asObservable() ?? .error(_BluetoothError.destroyed) } } /// Function that triggers read of current value of the `_Characteristic` instance. /// Read is called after subscription to `Observable` is made. /// - Parameter identifier: unique identifier of characteristic, which also holds information about service that characteristic belongs to. /// - Returns: Observable which emits `next` with given characteristic when value is ready to read. Immediately after that /// `.complete` is emitted. /// /// Observable can ends with following errors: /// * `_BluetoothError.characteristicReadFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func readValue(for identifier: CharacteristicIdentifier) -> Single<_Characteristic> { return characteristic(with: identifier) .flatMap { [weak self] in self?.readValue(for: $0) ?? .error(_BluetoothError.destroyed) } } /// Setup characteristic notification in order to receive callbacks when given characteristic has been changed. /// Returned observable will emit `_Characteristic` on every notification change. /// It is possible to setup more observables for the same characteristic and the lifecycle of the notification will be shared among them. /// /// Notification is automaticaly unregistered once this observable is unsubscribed /// /// - parameter characteristic: `_Characteristic` for notification setup. /// - returns: `Observable` emitting `_Characteristic` when given characteristic has been changed. /// /// This is **infinite** stream of values. /// /// Observable can ends with following errors: /// * `_BluetoothError.characteristicReadFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func observeValueUpdateAndSetNotification(for identifier: CharacteristicIdentifier) -> Observable<_Characteristic> { return characteristic(with: identifier) .asObservable() .flatMap { [weak self] in self?.observeValueUpdateAndSetNotification(for: $0) ?? .error(_BluetoothError.destroyed) } } /// Function that triggers descriptors discovery for characteristic /// - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to. /// - Returns: `Single` that emits `next` with array of `_Descriptor` instances, once they're discovered. /// /// Observable can ends with following errors: /// * `_BluetoothError.descriptorsDiscoveryFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func discoverDescriptors(for identifier: CharacteristicIdentifier) -> Single<[_Descriptor]> { return characteristic(with: identifier) .flatMap { [weak self] in self?.discoverDescriptors(for: $0) ?? .error(_BluetoothError.destroyed) } } /// Function that allow to observe writes that happened for descriptor. /// - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to. /// - Returns: Observable that emits `next` with `_Descriptor` instance every time when write has happened. /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `_BluetoothError.descriptorWriteFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func observeWrite(for identifier: DescriptorIdentifier) -> Observable<_Descriptor> { return descriptor(with: identifier) .asObservable() .flatMap { [weak self] in self?.observeWrite(for: $0) ?? .error(_BluetoothError.destroyed) } } /// Function that triggers write of data to descriptor. Write is called after subscribtion to `Observable` is made. /// - parameter data: `Data` that'll be written to `_Descriptor` instance /// - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to. /// - returns: `Single` that emits `next` with `_Descriptor` instance, once value is written successfully. /// /// Observable can ends with following errors: /// * `_BluetoothError.descriptorWriteFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func writeValue(_ data: Data, for identifier: DescriptorIdentifier) -> Single<_Descriptor> { return descriptor(with: identifier) .flatMap { [weak self] in self?.writeValue(data, for: $0) ?? .error(_BluetoothError.destroyed) } } /// Function that allow to observe value updates for `_Descriptor` instance. /// - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to. /// - Returns: Observable that emits `next` with `_Descriptor` instance every time when value has changed. /// It's **infinite** stream, so `.complete` is never called. /// /// Observable can ends with following errors: /// * `_BluetoothError.descriptorReadFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func observeValueUpdate(for identifier: DescriptorIdentifier) -> Observable<_Descriptor> { return descriptor(with: identifier) .asObservable() .flatMap { [weak self] in self?.observeValueUpdate(for: $0) ?? .error(_BluetoothError.destroyed) } } /// Function that triggers read of current value of the `_Descriptor` instance. /// Read is called after subscription to `Observable` is made. /// - Parameter identifier: `_Descriptor` to read value from /// - Returns: Observable which emits `next` with given descriptor when value is ready to read. Immediately after that /// `.complete` is emitted. /// /// Observable can ends with following errors: /// * `_BluetoothError.descriptorReadFailed` /// * `_BluetoothError.peripheralDisconnected` /// * `_BluetoothError.destroyed` /// * `_BluetoothError.bluetoothUnsupported` /// * `_BluetoothError.bluetoothUnauthorized` /// * `_BluetoothError.bluetoothPoweredOff` /// * `_BluetoothError.bluetoothInUnknownState` /// * `_BluetoothError.bluetoothResetting` func readValue(for identifier: DescriptorIdentifier) -> Single<_Descriptor> { return descriptor(with: identifier) .flatMap { [weak self] in self?.readValue(for: $0) ?? .error(_BluetoothError.destroyed) } } }
apache-2.0
tensorflow/examples
lite/examples/classification_by_retrieval/ios/ImageClassifierBuilder/ModelData.swift
1
1398
// Copyright 2021 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// Manages the persistence of the list of models to a file on disk. class ModelData: ObservableObject { /// The list of loaded models. @Published var models: [Model] = [] /// The URL on disk where the models are persisted. static var fileURL: URL { FileManager.documentDirectory.appendingPathComponent("Models.data") } /// Loads synchronously the list of models in memory. func load() throws { guard FileManager.default.fileExists(atPath: Self.fileURL.path) else { return } let data = try Data(contentsOf: Self.fileURL) models = try JSONDecoder().decode([Model].self, from: data) } /// Saves synchronously the list of models to disk. func save() throws { try JSONEncoder().encode(models).write(to: Self.fileURL) } }
apache-2.0
carabina/DDMathParser
MathParser/ResolvedToken.swift
2
1611
// // ResolvedToken.swift // DDMathParser // // Created by Dave DeLong on 8/8/15. // // import Foundation public struct ResolvedToken { public enum Kind { case Number(Double) case Variable(String) case Identifier(String) case Operator(MathParser.Operator) } public let kind: Kind public let string: String public let range: Range<String.Index> } public extension ResolvedToken.Kind { public var number: Double? { guard case .Number(let o) = self else { return nil } return o } public var variable: String? { guard case .Variable(let v) = self else { return nil } return v } public var identifier: String? { guard case .Identifier(let i) = self else { return nil } return i } public var resolvedOperator: MathParser.Operator? { guard case .Operator(let o) = self else { return nil } return o } public var builtInOperator: BuiltInOperator? { return resolvedOperator?.builtInOperator } public var isNumber: Bool { return number != nil } public var isVariable: Bool { return variable != nil } public var isIdentifier: Bool { return identifier != nil } public var isOperator: Bool { return resolvedOperator != nil } } public struct TokenResolverError: ErrorType { public enum Kind { case CannotParseHexNumber case CannotParseLocalizedNumber case UnknownOperator case AmbiguousOperator } public let kind: Kind public let rawToken: RawToken }
mit
wikimedia/apps-ios-wikipedia
WMF Framework/Fetcher.swift
1
8245
import UIKit // Base class for combining a Session and Configuration to make network requests // Session handles constructing and making requests, Configuration handles url structure for the current target // TODO: Standardize on returning CancellationKey or URLSessionTask // TODO: Centralize cancellation and remove other cancellation implementations (ReadingListsAPI) // TODO: Think about utilizing a request buildler instead of so many separate functions // TODO: Utilize Result type where possible (Swift only) @objc(WMFFetcher) open class Fetcher: NSObject { @objc public let configuration: Configuration @objc public let session: Session public typealias CancellationKey = String private var tasks = [String: URLSessionTask]() private let semaphore = DispatchSemaphore.init(value: 1) @objc override public convenience init() { self.init(session: Session.shared, configuration: Configuration.current) } @objc required public init(session: Session, configuration: Configuration) { self.session = session self.configuration = configuration } @discardableResult public func requestMediaWikiAPIAuthToken(for URL: URL?, type: TokenType, cancellationKey: CancellationKey? = nil, completionHandler: @escaping (Result<Token, Error>) -> Swift.Void) -> URLSessionTask? { let parameters = [ "action": "query", "meta": "tokens", "type": type.stringValue, "format": "json" ] return performMediaWikiAPIPOST(for: URL, with: parameters) { (result, response, error) in if let error = error { completionHandler(Result.failure(error)) return } guard let query = result?["query"] as? [String: Any], let tokens = query["tokens"] as? [String: Any], let tokenValue = tokens[type.stringValue + "token"] as? String else { completionHandler(Result.failure(RequestError.unexpectedResponse)) return } guard !tokenValue.isEmpty else { completionHandler(Result.failure(RequestError.unexpectedResponse)) return } completionHandler(Result.success(Token(value: tokenValue, type: type))) } } @objc(requestMediaWikiAPIAuthToken:withType:cancellationKey:completionHandler:) @discardableResult public func requestMediaWikiAPIAuthToken(for URL: URL?, with type: TokenType, cancellationKey: CancellationKey? = nil, completionHandler: @escaping (Token?, Error?) -> Swift.Void) -> URLSessionTask? { return requestMediaWikiAPIAuthToken(for: URL, type: type, cancellationKey: cancellationKey) { (result) in switch result { case .failure(let error): completionHandler(nil, error) case .success(let token): completionHandler(token, nil) } } } @objc(performTokenizedMediaWikiAPIPOSTWithTokenType:toURL:withBodyParameters:cancellationKey:completionHandler:) @discardableResult public func performTokenizedMediaWikiAPIPOST(tokenType: TokenType = .csrf, to URL: URL?, with bodyParameters: [String: String]?, cancellationKey: CancellationKey? = nil, completionHandler: @escaping ([String: Any]?, HTTPURLResponse?, Error?) -> Swift.Void) -> CancellationKey? { let key = cancellationKey ?? UUID().uuidString let task = requestMediaWikiAPIAuthToken(for: URL, type: tokenType, cancellationKey: key) { (result) in switch result { case .failure(let error): completionHandler(nil, nil, error) self.untrack(taskFor: key) case .success(let token): var mutableBodyParameters = bodyParameters ?? [:] mutableBodyParameters[tokenType.parameterName] = token.value self.performMediaWikiAPIPOST(for: URL, with: mutableBodyParameters, cancellationKey: key, completionHandler: completionHandler) } } track(task: task, for: key) return key } @objc(performMediaWikiAPIPOSTForURL:withBodyParameters:cancellationKey:completionHandler:) @discardableResult public func performMediaWikiAPIPOST(for URL: URL?, with bodyParameters: [String: String]?, cancellationKey: CancellationKey? = nil, completionHandler: @escaping ([String: Any]?, HTTPURLResponse?, Error?) -> Swift.Void) -> URLSessionTask? { let components = configuration.mediaWikiAPIURForHost(URL?.host) let key = cancellationKey ?? UUID().uuidString let task = session.postFormEncodedBodyParametersToURL(to: components.url, bodyParameters: bodyParameters) { (result, response, error) in completionHandler(result, response, error) self.untrack(taskFor: key) } track(task: task, for: key) return task } @objc(performMediaWikiAPIGETForURL:withQueryParameters:cancellationKey:completionHandler:) @discardableResult public func performMediaWikiAPIGET(for URL: URL?, with queryParameters: [String: Any]?, cancellationKey: CancellationKey?, completionHandler: @escaping ([String: Any]?, HTTPURLResponse?, Error?) -> Swift.Void) -> URLSessionTask? { let components = configuration.mediaWikiAPIURForHost(URL?.host, with: queryParameters) let key = cancellationKey ?? UUID().uuidString let task = session.getJSONDictionary(from: components.url) { (result, response, error) in let returnError = error ?? WMFErrorForApiErrorObject(result?["error"] as? [AnyHashable : Any]) completionHandler(result, response, returnError) self.untrack(taskFor: key) } track(task: task, for: key) return task } @objc(trackTask:forKey:) public func track(task: URLSessionTask?, for key: String) { guard let task = task else { return } semaphore.wait() tasks[key] = task semaphore.signal() } @objc(untrackTaskForKey:) public func untrack(taskFor key: String) { semaphore.wait() tasks.removeValue(forKey: key) semaphore.signal() } @objc(cancelTaskForKey:) public func cancel(taskFor key: String) { semaphore.wait() tasks[key]?.cancel() tasks.removeValue(forKey: key) semaphore.signal() } @objc(cancelAllTasks) public func cancelAllTasks() { semaphore.wait() for (_, task) in tasks { task.cancel() } tasks.removeAll(keepingCapacity: true) semaphore.signal() } } // These are for bridging to Obj-C only @objc public extension Fetcher { @objc class var unexpectedResponseError: NSError { return RequestError.unexpectedResponse as NSError } @objc class var invalidParametersError: NSError { return RequestError.invalidParameters as NSError } @objc class var noNewDataError: NSError { return RequestError.noNewData as NSError } @objc class var cancelledError: NSError { return NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: [NSLocalizedDescriptionKey: RequestError.unexpectedResponse.localizedDescription]) } } @objc(WMFTokenType) public enum TokenType: Int { case csrf, login, createAccount var stringValue: String { switch self { case .login: return "login" case .createAccount: return "createaccount" case .csrf: return "csrf" } } var parameterName: String { switch self { case .login: return "logintoken" case .createAccount: return "createtoken" default: return "token" } } } @objc(WMFToken) public class Token: NSObject { @objc public var value: String @objc public var type: TokenType public var isAuthorized: Bool @objc init(value: String, type: TokenType) { self.value = value self.type = type self.isAuthorized = value != "+\\" } }
mit
tadija/AELog
Tests/AELogTests/XCTestManifests.swift
1
412
#if !canImport(ObjectiveC) import XCTest extension AELogTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__AELogTests = [ ("testLogPerformance", testLogPerformance), ] } public func __allTests() -> [XCTestCaseEntry] { return [ testCase(AELogTests.__allTests__AELogTests), ] } #endif
mit
robbdimitrov/pixelgram-ios
PixelGram/Classes/Shared/ViewModels/UserViewModel.swift
1
995
// // UserViewModel.swift // PixelGram // // Created by Robert Dimitrov on 10/27/17. // Copyright © 2017 Robert Dimitrov. All rights reserved. // import Foundation class UserViewModel { private var user: User init(with user: User) { self.user = user } var avatarURL: URL? { if user.avatarURL.count > 0 { return URL(string: APIClient.shared.urlForImage(user.avatarURL)) } return nil } var nameText: String { return user.name } var usernameText: String { return user.username } var emailText: String { return user.email } var imagesNumberText: String { return "\(user.images)" } var likesNumberText: String { return "\(user.likes)" } var bioText: String? { return user.bio; } var isCurrentUser: Bool { return user.id == (Session.shared.currentUser?.id ?? "") } }
mit
nmartinson/Bluetooth-Camera-Controller
BLE Test/HelpViewController.swift
1
2202
// // HelpViewController.swift // Adafruit Bluefruit LE Connect // // Created by Collin Cunningham on 10/6/14. // Copyright (c) 2014 Adafruit Industries. All rights reserved. // import Foundation import UIKit //@objc protocol HelpViewControllerDelegate : Any{ // // func helpViewControllerDidFinish(controller : HelpViewController) // //} class HelpViewController : UIViewController { // @IBOutlet var delegate : HelpViewControllerDelegate? @IBOutlet var versionLabel : UILabel? @IBOutlet var textView : UITextView? required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // override init() { // super.init() // } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) preferredContentSize = CGSizeMake(320.0, 480.0) //popover size on iPad } override func viewDidLoad() { super.viewDidLoad() if (IS_IPAD == true) { self.preferredContentSize = self.view.frame.size; //popover size on iPad } else if (IS_IPHONE == true) { self.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal } //Set the app version # in the Help/Info view let versionString: String = "v" + ((NSBundle.mainBundle().infoDictionary)?["CFBundleShortVersionString"] as! String!) // let bundleVersionString: String = "b" + ((NSBundle.mainBundle().infoDictionary)?["CFBundleVersion"] as String!) // Build number // versionLabel?.text = versionString + " " + bundleVersionString versionLabel?.text = versionString } override func viewDidAppear(animated : Bool){ super.viewDidAppear(animated) textView?.flashScrollIndicators() //indicate add'l content below screen } // @IBAction func done(sender : AnyObject) { // //// delegate?.helpViewControllerDidFinish(self) // // } }
bsd-3-clause
luinily/hOme
hOme/UI/NewIRKitCommandViewController.swift
1
3477
// // NewIRKitCommandViewController.swift // hOme // // Created by Coldefy Yoann on 2016/02/27. // Copyright © 2016年 YoannColdefy. All rights reserved. // import Foundation import UIKit class NewIRKitCommandViewController: UITableViewController { @IBOutlet weak var format: UILabel! @IBOutlet weak var frequence: UILabel! @IBOutlet weak var data: UILabel! @IBOutlet weak var table: UITableView! @IBOutlet weak var createButton: UIBarButtonItem! @IBOutlet weak var nameTextField: UITextField! private let _nameSection = 0 private let _signalSection = 1 private let _getSignalSection = 2 private let _getSignalRow = 0 private let _testCommandRow = 1 private var _command: CommandProtocol? private var _device: DeviceProtocol? private var _irSignal: IRKITSignal? private var _name: String = "" private var _onClose: (() -> Void)? override func viewDidLoad() { updateView() nameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .editingDidEnd) nameTextField.becomeFirstResponder() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if (indexPath as NSIndexPath).section == _getSignalSection { if (indexPath as NSIndexPath).row == _getSignalRow { getData() } else if (indexPath as NSIndexPath).row == _testCommandRow { testCommand() } tableView.cellForRow(at: indexPath)?.isSelected = false } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case _nameSection: return _device?.name case _signalSection: return _device?.connector?.name case _getSignalSection: return "" default: return "" } } @IBAction func cancel(_ sender: AnyObject) { _onClose?() self.dismiss(animated: true, completion: nil) } @IBAction func create(_ sender: AnyObject) { createCommand() _onClose?() self.dismiss(animated: true, completion: nil) } func setDevice(_ device: DeviceProtocol) { _device = device } func setOnClose(_ onClose: @escaping () -> Void) { _onClose = onClose } func textFieldDidChange() { if let name = nameTextField.text { _name = name } updateView() } private func getData() { if let irKit = _device?.connector as? IRKitConnector { irKit.getData() { data in if data.hasSignal() { self._irSignal = data self.updateView() } } } } private func testCommand() { if let irKit = _device?.connector as? IRKitConnector, let irSignal = _irSignal { if irSignal.hasSignal() { irKit.sendDataToIRKit(irSignal) { } } } } private func updateView() { if let irSignal = _irSignal { format.text = irSignal.format frequence.text = String(irSignal.frequence) data.text = String(describing: irSignal.data) } else { format.text = "None" frequence.text = "None" data.text = "None" } createButton.isEnabled = checkInputs() table.reloadData() } private func checkInputs() -> Bool { if let irSignal = _irSignal { return (_name != "") && irSignal.hasSignal() } return false } private func createCommand() { if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let device = _device, let irSignal = _irSignal { if let command = appDelegate.homeApplication.createNewCommand(device: device, name: _name) as? IRKitCommand { command.setIRSignal(signal: irSignal) _command = command } } } }
mit
alskipp/Argo
Argo/Types/Decoded/Monad.swift
1
1355
/** flatMap a function over a `Decoded` value (right associative) - If the value is a failing case (`.TypeMismatch`, `.MissingKey`), the function will not be evaluated and this will return the value - If the value is `.Success`, the function will be applied to the unwrapped value - parameter x: A value of type `Decoded<T>` - parameter f: A transformation function from type `T` to type `Decoded<U>` - returns: A value of type `Decoded<U>` */ public func >>- <T, U>(x: Decoded<T>, @noescape f: T -> Decoded<U>) -> Decoded<U> { return x.flatMap(f) } /** flatMap a function over a `Decoded` value (left associative) - If the value is a failing case (`.TypeMismatch`, `.MissingKey`), the function will not be evaluated and this will return the value - If the value is `.Success`, the function will be applied to the unwrapped value - parameter x: A value of type `Decoded<T>` - parameter f: A transformation function from type `T` to type `Decoded<U>` - returns: A value of type `Decoded<U>` */ public func -<< <T, U>(@noescape f: T -> Decoded<U>, x: Decoded<T>) -> Decoded<U> { return x.flatMap(f) } public extension Decoded { func flatMap<U>(@noescape f: T -> Decoded<U>) -> Decoded<U> { switch self { case let .Success(value): return f(value) case let .Failure(error): return .Failure(error) } } }
mit
silence0201/Swift-Study
AdvancedSwift/集合/Array/Arrays - Mutation and Stateful Closures.playgroundpage/Contents.swift
1
2149
/*: #### Mutation and Stateful Closures When iterating over an array, you could use `map` to perform side effects (e.g. inserting the elements into some lookup table). We don't recommend doing this. Take a look at the following: ``` swift-example array.map { item in table.insert(item) } ``` This hides the side effect (the mutation of the lookup table) in a construct that looks like a transformation of the array. If you ever see something like the above, then it's a clear case for using a plain `for` loop instead of a function like `map`. The `forEach` method would also be more appropriate than `map` in this case, but it has its own issues. We'll look at `forEach` in a bit. Performing side effects is different than deliberately giving the closure *local* state, which is a particularly useful technique, and it's what makes closures — functions that can capture and mutate variables outside their scope — so powerful a tool when combined with higher-order functions. For example, the `accumulate` function described above could be implemented with `map` and a stateful closure, like this: */ //#-editable-code extension Array { func accumulate<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) -> Result) -> [Result] { var running = initialResult return map { next in running = nextPartialResult(running, next) return running } } } //#-end-editable-code /*: This creates a temporary variable to store the running value and then uses `map` to create an array of the running value as it progresses: */ //#-editable-code [1,2,3,4].accumulate(0, +) //#-end-editable-code /*: Note that this code assumes that `map` performs its transformation in order over the sequence. In the case of our `map` above, it does. But there are possible implementations that could transform the sequence out of order — for example, one that performs the transformation of the elements concurrently. The official standard library version of `map` doesn't specify whether or not it transforms the sequence in order, though it seems like a safe bet. */
mit
luinily/hOme
hOme/UI/DeviceCommandCell.swift
1
436
// // DeviceCommandCell.swift // hOme // // Created by Coldefy Yoann on 2016/04/20. // Copyright © 2016年 YoannColdefy. All rights reserved. // import Foundation import UIKit class DeviceCommandCell: UITableViewCell { @IBOutlet weak var label: UILabel! private var _command: CommandProtocol? = nil var command: CommandProtocol? { get {return _command} set { _command = newValue label.text = newValue?.name } } }
mit
kesun421/firefox-ios
Sync/KeyBundle.swift
3
11801
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import FxA import Account import SwiftyJSON private let KeyLength = 32 open class KeyBundle: Hashable { let encKey: Data let hmacKey: Data open class func fromKB(_ kB: Data) -> KeyBundle { let salt = Data() let contextInfo = FxAClient10.KW("oldsync") let len: UInt = 64 // KeyLength + KeyLength, without type nonsense. let derived = (kB as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: len)! return KeyBundle(encKey: derived.subdata(in: 0..<KeyLength), hmacKey: derived.subdata(in: KeyLength..<(2 * KeyLength))) } open class func random() -> KeyBundle { // Bytes.generateRandomBytes uses SecRandomCopyBytes, which hits /dev/random, which // on iOS is populated by the OS from kernel-level sources of entropy. // That should mean that we don't need to seed or initialize anything before calling // this. That is probably not true on (some versions of) OS X. return KeyBundle(encKey: Bytes.generateRandomBytes(32), hmacKey: Bytes.generateRandomBytes(32)) } open class var invalid: KeyBundle { return KeyBundle(encKeyB64: "deadbeef", hmacKeyB64: "deadbeef")! } public init?(encKeyB64: String, hmacKeyB64: String) { guard let e = Bytes.decodeBase64(encKeyB64), let h = Bytes.decodeBase64(hmacKeyB64) else { return nil } self.encKey = e self.hmacKey = h } public init(encKey: Data, hmacKey: Data) { self.encKey = encKey self.hmacKey = hmacKey } fileprivate func _hmac(_ ciphertext: Data) -> (data: UnsafeMutablePointer<CUnsignedChar>, len: Int) { let hmacAlgorithm = CCHmacAlgorithm(kCCHmacAlgSHA256) let digestLen: Int = Int(CC_SHA256_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen) CCHmac(hmacAlgorithm, hmacKey.getBytes(), hmacKey.count, ciphertext.getBytes(), ciphertext.count, result) return (result, digestLen) } open func hmac(_ ciphertext: Data) -> Data { let (result, digestLen) = _hmac(ciphertext) let data = NSMutableData(bytes: result, length: digestLen) result.deinitialize() return data as Data } /** * Returns a hex string for the HMAC. */ open func hmacString(_ ciphertext: Data) -> String { let (result, digestLen) = _hmac(ciphertext) let hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.deinitialize() return String(hash) } open func encrypt(_ cleartext: Data, iv: Data?=nil) -> (ciphertext: Data, iv: Data)? { let iv = iv ?? Bytes.generateRandomBytes(16) let (success, b, copied) = self.crypt(cleartext, iv: iv, op: CCOperation(kCCEncrypt)) let byteCount = cleartext.count + kCCBlockSizeAES128 if success == CCCryptorStatus(kCCSuccess) { // Hooray! let d = Data(bytes: b, count: Int(copied)) b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size) return (d, iv) } b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size) return nil } // You *must* verify HMAC before calling this. open func decrypt(_ ciphertext: Data, iv: Data) -> String? { let (success, b, copied) = self.crypt(ciphertext, iv: iv, op: CCOperation(kCCDecrypt)) let byteCount = ciphertext.count + kCCBlockSizeAES128 if success == CCCryptorStatus(kCCSuccess) { // Hooray! let d = Data(bytes: b, count: Int(copied)) let s = NSString(data: d, encoding: String.Encoding.utf8.rawValue) b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size) return s as String? } b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size) return nil } fileprivate func crypt(_ input: Data, iv: Data, op: CCOperation) -> (status: CCCryptorStatus, buffer: UnsafeMutableRawPointer, count: Int) { let resultSize = input.count + kCCBlockSizeAES128 var copied: Int = 0 let result = UnsafeMutableRawPointer.allocate(bytes: resultSize, alignedTo: MemoryLayout<Void>.size) let success: CCCryptorStatus = CCCrypt(op, CCHmacAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), encKey.getBytes(), kCCKeySizeAES256, iv.getBytes(), input.getBytes(), input.count, result, resultSize, &copied ) return (success, result, copied) } open func verify(hmac: Data, ciphertextB64: Data) -> Bool { let expectedHMAC = hmac let computedHMAC = self.hmac(ciphertextB64) return (expectedHMAC == computedHMAC) } /** * Swift can't do functional factories. I would like to have one of the following * approaches be viable: * * 1. Derive the constructor from the consumer of the factory. * 2. Accept a type as input. * * Neither of these are viable, so we instead pass an explicit constructor closure. * * Most of these approaches produce either odd compiler errors, or -- worse -- * compile and then yield runtime EXC_BAD_ACCESS (see Radar 20230159). * * For this reason, be careful trying to simplify or improve this code. */ open func factory<T: CleartextPayloadJSON>(_ f: @escaping (JSON) -> T) -> (String) -> T? { return { (payload: String) -> T? in let potential = EncryptedJSON(json: payload, keyBundle: self) if !potential.isValid() { return nil } let cleartext = potential.cleartext if cleartext == nil { return nil } return f(cleartext!) } } // TODO: how much do we want to move this into EncryptedJSON? open func serializer<T: CleartextPayloadJSON>(_ f: @escaping (T) -> JSON) -> (Record<T>) -> JSON? { return { (record: Record<T>) -> JSON? in let json = f(record.payload) if json.isNull() { // This should never happen, but if it does, we don't want to leak this // record to the server! return nil } let bytes: Data do { // Get the most basic kind of encoding: no pretty printing. // This can throw; if so, we return nil. // `rawData` simply calls JSONSerialization.dataWithJSONObject:options:error, which // guarantees UTF-8 encoded output. bytes = try json.rawData(options: []) } catch { return nil } // Given a valid non-null JSON object, we don't ever expect a round-trip to fail. assert(!JSON(bytes).isNull()) // We pass a null IV, which means "generate me a new one". // We then include the generated IV in the resulting record. if let (ciphertext, iv) = self.encrypt(bytes, iv: nil) { // So we have the encrypted payload. Now let's build the envelope around it. let ciphertext = ciphertext.base64EncodedString // The HMAC is computed over the base64 string. As bytes. Yes, I know. if let encodedCiphertextBytes = ciphertext.data(using: String.Encoding.ascii, allowLossyConversion: false) { let hmac = self.hmacString(encodedCiphertextBytes) let iv = iv.base64EncodedString // The payload is stringified JSON. Yes, I know. let payload: Any = JSON(object: ["ciphertext": ciphertext, "IV": iv, "hmac": hmac]).stringValue()! as Any let obj = ["id": record.id, "sortindex": record.sortindex, // This is how SwiftyJSON wants us to express a null that we want to // serialize. Yes, this is gross. "ttl": record.ttl ?? NSNull(), "payload": payload] return JSON(object: obj) } } return nil } } open func asPair() -> [String] { return [self.encKey.base64EncodedString, self.hmacKey.base64EncodedString] } open var hashValue: Int { return "\(self.encKey.base64EncodedString) \(self.hmacKey.base64EncodedString)".hashValue } } public func == (lhs: KeyBundle, rhs: KeyBundle) -> Bool { return (lhs.encKey == rhs.encKey) && (lhs.hmacKey == rhs.hmacKey) } open class Keys: Equatable { let valid: Bool let defaultBundle: KeyBundle var collectionKeys: [String: KeyBundle] = [String: KeyBundle]() public init(defaultBundle: KeyBundle) { self.defaultBundle = defaultBundle self.valid = true } public init(payload: KeysPayload?) { if let payload = payload, payload.isValid() { if let keys = payload.defaultKeys { self.defaultBundle = keys self.collectionKeys = payload.collectionKeys self.valid = true return } } self.defaultBundle = KeyBundle.invalid self.valid = false } public convenience init(downloaded: EnvelopeJSON, master: KeyBundle) { let f: (JSON) -> KeysPayload = { KeysPayload($0) } let keysRecord = Record<KeysPayload>.fromEnvelope(downloaded, payloadFactory: master.factory(f)) self.init(payload: keysRecord?.payload) } open class func random() -> Keys { return Keys(defaultBundle: KeyBundle.random()) } open func forCollection(_ collection: String) -> KeyBundle { if let bundle = collectionKeys[collection] { return bundle } return defaultBundle } open func encrypter<T>(_ collection: String, encoder: RecordEncoder<T>) -> RecordEncrypter<T> { return RecordEncrypter(bundle: forCollection(collection), encoder: encoder) } open func asPayload() -> KeysPayload { let json: JSON = JSON([ "id": "keys", "collection": "crypto", "default": self.defaultBundle.asPair(), "collections": mapValues(self.collectionKeys, f: { $0.asPair() }) ]) return KeysPayload(json) } } /** * Yup, these are basically typed tuples. */ public struct RecordEncoder<T: CleartextPayloadJSON> { let decode: (JSON) -> T let encode: (T) -> JSON } public struct RecordEncrypter<T: CleartextPayloadJSON> { let serializer: (Record<T>) -> JSON? let factory: (String) -> T? init(bundle: KeyBundle, encoder: RecordEncoder<T>) { self.serializer = bundle.serializer(encoder.encode) self.factory = bundle.factory(encoder.decode) } init(serializer: @escaping (Record<T>) -> JSON?, factory: @escaping (String) -> T?) { self.serializer = serializer self.factory = factory } } public func ==(lhs: Keys, rhs: Keys) -> Bool { return lhs.valid == rhs.valid && lhs.defaultBundle == rhs.defaultBundle && lhs.collectionKeys == rhs.collectionKeys }
mpl-2.0
edmw/Volumio_ios
Pods/Dropper/Pod/Classes/DropperDelegate.swift
2
470
// // DropperDelegate.swift // Pods // // Created by Ozzie Kirkby on 2016-05-14. // // import Foundation public protocol DropperDelegate { func DropperSelectedRow(_ path: IndexPath, contents: String) func DropperSelectedRow(_ path: IndexPath, contents: String, tag: Int) } public extension DropperDelegate { func DropperSelectedRow(_ path: IndexPath, contents: String) {} func DropperSelectedRow(_ path: IndexPath, contents: String, tag: Int) {} }
gpl-3.0
stripe/stripe-ios
StripeIdentity/StripeIdentity/Source/Categories/UINavigationController+StripeIdentity.swift
1
2824
// // UINavigationController+StripeIdentity.swift // StripeIdentity // // Created by Jaime Park on 2/10/22. // Copyright © 2022 Stripe, Inc. All rights reserved. // @_spi(STP) import StripeUICore import UIKit extension UINavigationController { func configureBorderlessNavigationBar() { if #available(iOS 13.0, *) { let appearance = UINavigationBarAppearance() appearance.copyButtonAppearance(from: UINavigationBar.appearance().standardAppearance) appearance.configureWithTransparentBackground() navigationBar.standardAppearance = appearance navigationBar.scrollEdgeAppearance = appearance } else { navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() navigationBar.backgroundColor = .clear } } func setNavigationBarBackgroundColor(with backgroundColor: UIColor?) { let bgColor = backgroundColor ?? .systemBackground if #available(iOS 13.0, *) { navigationBar.standardAppearance.backgroundColor = bgColor navigationBar.scrollEdgeAppearance?.backgroundColor = bgColor } else { navigationBar.backgroundColor = bgColor } } } @available(iOS 13.0, *) extension UINavigationBarAppearance { fileprivate func copyButtonAppearance(from other: UINavigationBarAppearance) { // Button appearances will be undefined if using the default configuration. // Copying the default undefined configuration will result in an // NSInternalInconsistencyException. We can check for undefined by // copying the values to an optional type and checking for nil. let otherButtonAppearance: UIBarButtonItemAppearance? = other.buttonAppearance let otherDoneButtonAppearance: UIBarButtonItemAppearance? = other.doneButtonAppearance let otherBackButtonAppearance: UIBarButtonItemAppearance? = other.backButtonAppearance if let otherButtonAppearance = otherButtonAppearance { buttonAppearance = otherButtonAppearance } else { buttonAppearance.configureWithDefault(for: .plain) } if let otherDoneButtonAppearance = otherDoneButtonAppearance { doneButtonAppearance = otherDoneButtonAppearance } else { doneButtonAppearance.configureWithDefault(for: .done) } if let otherBackButtonAppearance = otherBackButtonAppearance { backButtonAppearance = otherBackButtonAppearance } else { backButtonAppearance.configureWithDefault(for: .plain) } setBackIndicatorImage( other.backIndicatorImage, transitionMaskImage: other.backIndicatorTransitionMaskImage ) } }
mit
GraphKit/MaterialKit
Sources/iOS/Button.swift
1
8926
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit open class Button: UIButton, Pulseable { /** A CAShapeLayer used to manage elements that would be affected by the clipToBounds property of the backing layer. For example, this allows the dropshadow effect on the backing layer, while clipping the image to a desired shape within the visualLayer. */ open let visualLayer = CAShapeLayer() /// A Pulse reference. fileprivate var pulse: Pulse! /// PulseAnimation value. open var pulseAnimation: PulseAnimation { get { return pulse.animation } set(value) { pulse.animation = value } } /// PulseAnimation color. @IBInspectable open var pulseColor: UIColor { get { return pulse.color } set(value) { pulse.color = value } } /// Pulse opacity. @IBInspectable open var pulseOpacity: CGFloat { get { return pulse.opacity } set(value) { pulse.opacity = value } } /// A property that accesses the backing layer's background @IBInspectable open override var backgroundColor: UIColor? { didSet { layer.backgroundColor = backgroundColor?.cgColor } } /// A preset property for updated contentEdgeInsets. open var contentEdgeInsetsPreset = EdgeInsetsPreset.none { didSet { contentEdgeInsets = EdgeInsetsPresetToValue(preset: contentEdgeInsetsPreset) } } /// Sets the normal and highlighted image for the button. @IBInspectable open var image: UIImage? { didSet { setImage(image, for: .normal) setImage(image, for: .highlighted) } } /// Sets the normal and highlighted title for the button. @IBInspectable open var title: String? { didSet { setTitle(title, for: .normal) setTitle(title, for: .highlighted) guard nil != title else { return } guard nil == titleColor else { return } titleColor = Color.blue.base } } /// Sets the normal and highlighted titleColor for the button. @IBInspectable open var titleColor: UIColor? { didSet { setTitleColor(titleColor, for: .normal) setTitleColor(titleColor, for: .highlighted) } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) tintColor = Color.blue.base prepare() } /** An initializer that initializes the object with a CGRect object. If AutoLayout is used, it is better to initilize the instance using the init() initializer. - Parameter frame: A CGRect instance. */ public override init(frame: CGRect) { super.init(frame: frame) tintColor = Color.blue.base prepare() } /// A convenience initializer. public convenience init() { self.init(frame: .zero) } /** A convenience initializer that acceps an image and tint - Parameter image: A UIImage. - Parameter tintColor: A UI */ public convenience init(image: UIImage?, tintColor: UIColor = Color.blue.base) { self.init() prepare(with: image, tintColor: tintColor) prepare() } /** A convenience initializer that acceps a title and title - Parameter title: A String. - Parameter titleColor: A UI */ public convenience init(title: String?, titleColor: UIColor = Color.blue.base) { self.init() prepare(with: title, titleColor: titleColor) prepare() } open override func layoutSubviews() { super.layoutSubviews() layoutShape() layoutVisualLayer() layoutShadowPath() } /** Triggers the pulse animation. - Parameter point: A Optional point to pulse from, otherwise pulses from the center. */ open func pulse(point: CGPoint? = nil) { let p = point ?? center pulse.expandAnimation(point: p) Animation.delay(time: 0.35) { [weak self] in self?.pulse.contractAnimation() } } /** A delegation method that is executed when the view has began a touch event. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) pulse.expandAnimation(point: layer.convert(touches.first!.location(in: self), from: layer)) } /** A delegation method that is executed when the view touch event has ended. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) pulse.contractAnimation() } /** A delegation method that is executed when the view touch event has been cancelled. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) pulse.contractAnimation() } open func bringImageViewToFront() { guard let v = imageView else { return } bringSubview(toFront: v) } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open func prepare() { contentScaleFactor = Screen.scale prepareVisualLayer() preparePulse() } } extension Button { /// Prepares the visualLayer property. fileprivate func prepareVisualLayer() { visualLayer.zPosition = 0 visualLayer.masksToBounds = true layer.addSublayer(visualLayer) } /// Prepares the pulse motion. fileprivate func preparePulse() { pulse = Pulse(pulseView: self, pulseLayer: visualLayer) } /** Prepares the Button with an image and tint - Parameter image: A UIImage. - Parameter tintColor: A UI */ fileprivate func prepare(with image: UIImage?, tintColor: UIColor) { self.image = image self.tintColor = tintColor } /** Prepares the Button with a title and title - Parameter title: A String. - Parameter titleColor: A UI */ fileprivate func prepare(with title: String?, titleColor: UIColor) { self.title = title self.titleColor = titleColor } } extension Button { /// Manages the layout for the visualLayer property. fileprivate func layoutVisualLayer() { visualLayer.frame = bounds visualLayer.cornerRadius = cornerRadius } }
agpl-3.0
ECP-CANDLE/Supervisor
workflows/common/swift/log_app.swift
1
1143
// LOG APP (void o) log_start(string algorithm) { file out<turbine_output/"log_start_out.txt">; file err<turbine_output/"log_start_err.txt">; string ps = join(file_lines(input(param_set)), " "); string t_log = turbine_output/"turbine.log"; if (file_exists(t_log)) { string sys_env = join(file_lines(input(t_log)), ", "); (out, err) = run_log_start(log_runner, ps, sys_env, algorithm, site) => o = propagate(); } else { (out, err) = run_log_start(log_runner, ps, "", algorithm, site) => o = propagate(); } } (void o) log_end() { file out <"%s/log_end_out.txt" % turbine_output>; file err <"%s/log_end_err.txt" % turbine_output>; (out, err) = run_log_end(log_runner, site) => o = propagate(); } app (file out, file err) run_log_start(file shfile, string ps, string sys_env, string algorithm, string site) { "bash" shfile "start" emews_root propose_points max_iterations ps algorithm exp_id sys_env site @stdout=out @stderr=err; } app (file out, file err) run_log_end(file shfile, string site) { "bash" shfile "end" emews_root exp_id site @stdout=out @stderr=err; }
mit
austinzheng/swift-compiler-crashes
fixed/26020-swift-parser-skipsingle.swift
7
232
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {({{(}}} class B{{{ {{{{{{{{{{{{{{{{{{ a " init{{ {class case,
mit
chronotruck/CTKFlagPhoneNumber
ExampleOBJC/OBJCExample/dummy.swift
1
155
// // dummy.swift // OBJCExample // // Created by Aurelien on 28/05/2019. // Copyright © 2019 chronotruck. All rights reserved. // import Foundation
apache-2.0
austinzheng/swift-compiler-crashes
crashes-duplicates/09694-llvm-foldingset-swift-classtype-nodeequals.swift
11
297
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class b<U { class A { class a { { } let NSManagedObject { class a { } if true { class b: a } } { } class d func a { class A : d
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/15423-swift-sourcemanager-getmessage.swift
11
227
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { deinit { return ( ) { protocol A { class case ,
mit
CoderSLZeng/SLWeiBo
SLWeiBo/SLWeiBo/Classes/Home/Controller/HomeTableViewController.swift
1
10947
// // HomeTableViewController.swift // SLWeiBo // // Created by Anthony on 17/3/6. // Copyright © 2017年 SLZeng. All rights reserved. // import UIKit import SDWebImage import MJRefresh class HomeTableViewController: BaseTableViewController { // MARK: - 懒加载属性 /// 标题按钮 fileprivate lazy var titleBtn : TitleButton = TitleButton() /* 注意:在闭包中如果使用当前对象的属性或者调用方法,也需要加self 两个地方需要使用self : 1> 如果在一个函数中出现歧义 2> 在闭包中使用当前对象的属性和方法也需要加self */ /// 转场动画 fileprivate lazy var popoverAnimator : PopoverAnimator = PopoverAnimator { [weak self] (presented) in self?.titleBtn.isSelected = presented } /// 微博视图模型 fileprivate lazy var viewModels : [StatusViewModel] = [StatusViewModel]() /// 更新微博提示框 fileprivate lazy var tipLabel : UILabel = UILabel() /// 自定义渐变的转场动画 fileprivate lazy var photoBrowserAnimator : PhotoBrowserAnimator = PhotoBrowserAnimator() // MARK: - 系统回调函数 override func viewDidLoad() { super.viewDidLoad() // 1.判断用户是否登录 if !isLogin { // 设置访客视图 visitorView.setupVisitorViewInfo(nil, title: "关注一些人,回这里看看有什么惊喜") return } // 2.设置导航条 setupNavigationBar() // 3.设置预估高度值 tableView.estimatedRowHeight = 200 // 4.设置头部刷新控件 setupRefreshHeaderView() // 5.设置底部刷新控件 setupRefreshFooterView() // 6.设置更新微博提示框 setupTipLabel() // 6.监听通知 setupNatifications() } } // MARK: - 设置UI界面 extension HomeTableViewController { /** 设置导航条 */ fileprivate func setupNavigationBar() { // 1.添加左右按钮 navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: #selector(HomeTableViewController.leftBtnClick)) navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(HomeTableViewController.rightBtnClick)) // 2.添加标题按钮 // 获取用户名称 let title = UserAccountViewModel.shareIntance.account?.screen_name ?? "CoderSLZeng" titleBtn.setTitle(title + " ", for: UIControlState()) titleBtn.addTarget(self, action: #selector(HomeTableViewController.titleBtnClick(_:)), for: .touchUpInside) navigationItem.titleView = titleBtn } /** 设置头部刷新控件 */ fileprivate func setupRefreshHeaderView() { // 1.创建headerView let refreshHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(HomeTableViewController.loadNewStatuses)) // 2.设置header的属性 refreshHeader?.setTitle("下拉刷新", for: .idle) refreshHeader?.setTitle("释放更新", for: .pulling) refreshHeader?.setTitle("加载中...", for: .refreshing) // 3.设置tableView的header tableView.mj_header = refreshHeader // 4.进入刷新状态 tableView.mj_header.beginRefreshing() } /** 设置底部刷新控件 */ fileprivate func setupRefreshFooterView() { tableView.mj_footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: #selector(HomeTableViewController.loadMoreStatuses)) } /** 设置更新微博提示框 */ fileprivate func setupTipLabel() { // 1.添加父控件中 navigationController?.navigationBar.insertSubview(tipLabel, at: 0) // 2.设置边框尺寸 tipLabel.frame = CGRect(x: 0, y: 10, width: UIScreen.main.bounds.width, height: 32) // 3.设置属性 tipLabel.backgroundColor = UIColor.orange tipLabel.textColor = UIColor.white tipLabel.font = UIFont.systemFont(ofSize: 14) tipLabel.textAlignment = .center tipLabel.isHidden = true } fileprivate func setupNatifications() { NotificationCenter.default.addObserver(self, selector: #selector(HomeTableViewController.showPhotoBrowser(_:)), name: NSNotification.Name(rawValue: ShowPhotoBrowserNote), object: nil) } } // MARK: - 监听事件处理 extension HomeTableViewController { @objc fileprivate func leftBtnClick() { myLog("") } @objc fileprivate func rightBtnClick() { // 1.创建二维码控制器 let sb = UIStoryboard(name: "QRCode", bundle: nil) let vc = sb.instantiateInitialViewController()! // 2.弹出二维码控制器 present(vc, animated: true, completion: nil) } @objc fileprivate func titleBtnClick(_ button: TitleButton) { // 1.创建弹出的控制器 let popoverVc = PopoverViewController() // 2.设置控制器的modal样式 popoverVc.modalPresentationStyle = .custom // 3.设置转场的代理 popoverVc.transitioningDelegate = popoverAnimator // 4.设置展示出来的尺寸 popoverAnimator.presentedFrame = CGRect(x: 100, y: 55, width: 180, height: 250) // 5.弹出控制器 present(popoverVc, animated: true, completion: nil) } @objc fileprivate func showPhotoBrowser(_ note : Notification) { // 0.取出数据 let indexPath = note.userInfo![ShowPhotoBrowserIndexKey] as! IndexPath let picURLs = note.userInfo![ShowPhotoBrowserUrlsKey] as! [URL] let object = note.object as! PicCollectionView // 1.创建控制器 let photoBrowserVc = PhotoBrowserController(indexPath: indexPath, picURLs: picURLs) // 2.设置modal样式 photoBrowserVc.modalPresentationStyle = .custom // 3.设置转场的代理 photoBrowserVc.transitioningDelegate = photoBrowserAnimator // 4.设置动画的代理 photoBrowserAnimator.presentedDelegate = object photoBrowserAnimator.indexPath = indexPath photoBrowserAnimator.dismissDelegate = photoBrowserVc // 5.以modal的形式弹出控制器 present(photoBrowserVc, animated: true, completion: nil) } /// 加载最新的数据 @objc fileprivate func loadNewStatuses() { loadStatuses(true) } /// 加载更多的数据 @objc fileprivate func loadMoreStatuses() { loadStatuses(false) } } // MARK:- 请求数据 extension HomeTableViewController { /// 加载微博数据 fileprivate func loadStatuses(_ isNewData : Bool) { // 1.获取since_id/max_id var since_id = 0 var max_id = 0 if isNewData { since_id = viewModels.first?.status?.mid ?? 0 } else { max_id = viewModels.last?.status?.mid ?? 0 max_id = max_id == 0 ? 0 : (max_id - 1) } // 2.请求数据 NetworkTools.shareInstance.loadStatuses(since_id, max_id: max_id) { (result, error) -> () in // 1.错误校验 if error != nil { myLog(error) return } // 2.获取可选类型中的数据 guard let resultArray = result else { return } // 3.遍历微博对应的字典 var tempViewModel = [StatusViewModel]() for statusDict in resultArray { let status = Status(dict: statusDict) let viewModel = StatusViewModel(status: status) tempViewModel.append(viewModel) } // 4.将数据放入到成员变量的数组中 if isNewData { self.viewModels = tempViewModel + self.viewModels } else { self.viewModels += tempViewModel } // 5.缓存图片 self.cacheImages(tempViewModel) } } /** 缓存图片 */ fileprivate func cacheImages(_ viewModels : [StatusViewModel]) { // 0.创建group let group = DispatchGroup() // 1.缓存图片 for viewmodel in viewModels { for picURL in viewmodel.picURLs { group.enter() SDWebImageManager.shared().loadImage(with: picURL, options: [], progress: nil, completed: { (_, _, _, _, _, _) in group.leave() }) } } // 2.刷新表格 group.notify(queue: DispatchQueue.main) { () -> Void in self.tableView.reloadData() // 停止刷新 self.tableView.mj_header.endRefreshing() self.tableView.mj_footer.endRefreshing() // 显示更新微博提示框 self.showTipLabel(viewModels.count) } } /// 显示更新微博提示的框 fileprivate func showTipLabel(_ count : Int) { // 1.设置属性 tipLabel.isHidden = false tipLabel.text = count == 0 ? "没有更新的微博" : "更新了\(count) 条形微博" // 2.执行动画 UIView.animate(withDuration: 1.0, animations: { () -> Void in self.tipLabel.frame.origin.y = 44 }, completion: { (_) -> Void in UIView.animate(withDuration: 1.0, delay: 1.5, options: [], animations: { () -> Void in self.tipLabel.frame.origin.y = 10 }, completion: { (_) -> Void in self.tipLabel.isHidden = true }) }) } } // MARK:- tableView的数据源方法 extension HomeTableViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModels.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 1.创建cell let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as! HomeViewCell // 2.给cell设置数据 cell.viewModel = viewModels[indexPath.row] return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // 1.获取模型对象 let viewModel = viewModels[indexPath.row] return viewModel.cellHeight } }
mit
mono0926/firebase-verifier
Sources/Error.swift.swift
1
847
// // Error.swift.swift // Bits // // Created by mono on 2017/08/03. // import Foundation let verifyIdTokenDocsMessage = "See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token." let projectIdMatchMessage = "Make sure the ID token comes from the same Firebase project as the service account used to authenticate this SDK." public enum VerificationErrorType { case notFound(key: String), incorrect(key: String), emptyProjectId, expirationTimeIsPast, issuedAtTimeisFuture } public struct VerificationError: Error { public let type: VerificationErrorType public let message: String? } extension VerificationError: CustomStringConvertible { public var description: String { return "type: \(type)\nmessage: \(String(describing: message))" } }
mit
hollance/swift-algorithm-club
CounterClockWise/CounterClockWise.playground/Contents.swift
2
2335
/* CounterClockWise(CCW) Algorithm The user cross-multiplies corresponding coordinates to find the area encompassing the polygon, and subtracts it from the surrounding polygon to find the area of the polygon within. This code is based on the "Shoelace formula" by Carl Friedrich Gauss https://en.wikipedia.org/wiki/Shoelace_formula */ import Foundation // MARK : Point struct for defining 2-D coordinate(x,y) public struct Point{ // Coordinate(x,y) var x: Int var y: Int public init(x: Int ,y: Int){ self.x = x self.y = y } } // MARK : Function that determine the area of a simple polygon whose vertices are described // by their Cartesian coordinates in the plane. func ccw(points: [Point]) -> Int{ let polygon = points.count var orientation = 0 // Take the first x-coordinate and multiply it by the second y-value, // then take the second x-coordinate and multiply it by the third y-value, // and repeat as many times until it is done for all wanted points. for i in 0..<polygon{ orientation += (points[i%polygon].x*points[(i+1)%polygon].y - points[(i+1)%polygon].x*points[i%polygon].y) } // If the points are labeled sequentially in the counterclockwise direction, // then the sum of the above determinants is positive and the absolute value signs can be omitted // if they are labeled in the clockwise direction, the sum of the determinants will be negative. // This is because the formula can be viewed as a special case of Green's Theorem. switch orientation { case Int.min..<0: return -1 // if operation < 0 : ClockWise case 0: return 0 // if operation == 0 : Parallel default: return 1 // if operation > 0 : CounterClockWise } } // A few simple tests // Triangle var p1 = Point(x: 5, y: 8) var p2 = Point(x: 9, y: 1) var p3 = Point(x: 3, y: 6) print(ccw(points: [p1,p2,p3])) // -1 means ClockWise // Quadrilateral var p4 = Point(x: 5, y: 8) var p5 = Point(x: 2, y: 3) var p6 = Point(x: 6, y: 1) var p7 = Point(x: 9, y: 3) print(ccw(points: [p4,p5,p6,p7])) // 1 means CounterClockWise // Pentagon var p8 = Point(x: 5, y: 11) var p9 = Point(x: 3, y: 4) var p10 = Point(x: 5, y: 6) var p11 = Point(x: 9, y: 5) var p12 = Point(x: 12, y: 8) print(ccw(points: [p8,p9,p10,p11,p12])) // 1 means CounterClockWise
mit
open-telemetry/opentelemetry-swift
Sources/OpenTelemetryApi/Trace/DefaultTracerProvider.swift
1
362
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation public class DefaultTracerProvider: TracerProvider { public static let instance = DefaultTracerProvider() public func get(instrumentationName: String, instrumentationVersion: String? = nil) -> Tracer { return DefaultTracer.instance } }
apache-2.0
raymondshadow/SwiftDemo
SwiftApp/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift
2
3825
// // Signal+Subscription.swift // RxCocoa // // Created by Krunoslav Zaher on 9/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift extension SharedSequenceConvertibleType where SharingStrategy == SignalSharingStrategy { /** Creates new subscription and sends elements to observer. In this form it's equivalent to `subscribe` method, but it communicates intent better. - parameter to: Observer that receives events. - returns: Disposable object that can be used to unsubscribe the observer from the subject. */ public func emit<O: ObserverType>(to observer: O) -> Disposable where O.E == E { return self.asSharedSequence().asObservable().subscribe(observer) } /** Creates new subscription and sends elements to observer. In this form it's equivalent to `subscribe` method, but it communicates intent better. - parameter to: Observer that receives events. - returns: Disposable object that can be used to unsubscribe the observer from the subject. */ public func emit<O: ObserverType>(to observer: O) -> Disposable where O.E == E? { return self.asSharedSequence().asObservable().map { $0 as E? }.subscribe(observer) } /** Creates new subscription and sends elements to `BehaviorRelay`. - parameter relay: Target relay for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the relay. */ public func emit(to relay: BehaviorRelay<E>) -> Disposable { return self.emit(onNext: { e in relay.accept(e) }) } /** Creates new subscription and sends elements to `BehaviorRelay`. - parameter relay: Target relay for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the relay. */ public func emit(to relay: BehaviorRelay<E?>) -> Disposable { return self.emit(onNext: { e in relay.accept(e) }) } /** Creates new subscription and sends elements to relay. - parameter relay: Target relay for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the relay. */ public func emit(to relay: PublishRelay<E>) -> Disposable { return self.emit(onNext: { e in relay.accept(e) }) } /** Creates new subscription and sends elements to relay. - parameter to: Target relay for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the relay. */ public func emit(to relay: PublishRelay<E?>) -> Disposable { return self.emit(onNext: { e in relay.accept(e) }) } /** Subscribes an element handler, a completion handler and disposed handler to an observable sequence. Error callback is not exposed because `Signal` can't error out. - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. gracefully completed, errored, or if the generation is canceled by disposing subscription) - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has gracefully completed, errored, or if the generation is canceled by disposing subscription) - returns: Subscription object used to unsubscribe from the observable sequence. */ public func emit(onNext: ((E) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable { return self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed) } }
apache-2.0
gozer/voice-web
ios/voicebank-ios-wrapper/Recorder.swift
1
5071
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. import Foundation import AVFoundation import WebKit class Recorder: NSObject, AVAudioRecorderDelegate { var recordingSession: AVAudioSession! var audioRecorder: AVAudioRecorder! var audioFilename: URL? = nil var webView: WKWebView? = nil var audioPlayer:AVAudioPlayer! var metertimer : Timer? = nil var hasMicPermission: Bool = false override init() { super.init() let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] self.audioFilename = documentsDirectory.appendingPathComponent("recording.m4a") self.recordingSession = AVAudioSession.sharedInstance() do { try self.recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.defaultToSpeaker]) try self.recordingSession.setActive(true) } catch { // failed to record! } } func startRecording() { // first we declare the closure to start recording let record = { () -> Void in self.audioRecorder.record() self.audioRecorder.isMeteringEnabled = true; self.metertimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.updateAudioMeter), userInfo: nil, repeats: true); } // then we check if we have mic permission if (!self.hasMicPermission){ // if not, we ask it requestPermission(completion:{(allowed: Bool) -> Void in if (!allowed) { // if permission wasn't given, we let the webapp now self.hasMicPermission = false self.webView?.evaluateJavaScript("nativemsgs('nomicpermission')") } else { // if permission was given, we start recording if (self.createRecorder()) { self.hasMicPermission = true record() self.webView?.evaluateJavaScript("nativemsgs('capturestarted')") } else { self.webView?.evaluateJavaScript("nativemsgs('errorrecording')") } } }) } else { // if we have permission, then we start capturing record() self.webView?.evaluateJavaScript("nativemsgs('capturestarted')") } } func requestPermission(completion: @escaping (Bool) -> Void) { // first we show the permissions popup recordingSession.requestRecordPermission() { [unowned self] allowed in DispatchQueue.main.async { completion(allowed) } } } func stopRecording() { self.audioRecorder.stop() self.metertimer?.invalidate() } func stopPlayingCapture() { self.audioPlayer.stop() } func createRecorder() -> Bool { let settings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 48000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] do { self.audioRecorder = try AVAudioRecorder(url: self.audioFilename!, settings: settings) } catch { return false } self.audioRecorder.delegate = self return true } func playCapture() { do { try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.speaker) try audioPlayer = AVAudioPlayer(contentsOf: self.audioFilename!) audioPlayer.prepareToPlay() audioPlayer.play() } catch { self.webView?.evaluateJavaScript("nativemsgs('errorplaying')") } } func updateAudioMeter() { self.audioRecorder.updateMeters() let dBLevel = self.audioRecorder.averagePower(forChannel: 0) let peaklevel = self.audioRecorder.peakPower(forChannel: 0) NSLog("peaklevel \(peaklevel) dblevel \(dBLevel) ") webView?.evaluateJavaScript("levels('\(dBLevel)', '\(peaklevel)')") } func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { if (flag){ do { let data: NSData = try NSData(contentsOfFile: self.audioFilename!.path) // Convert swift dictionary into encoded json let encodedData = data.base64EncodedString(options: .endLineWithLineFeed) // This WKWebView API to calls 'reloadData' function defined in js webView?.evaluateJavaScript("uploadData('\(encodedData)')") } catch { // failed to record! } } } }
mpl-2.0
wqhiOS/WeiBo
WeiBo/WeiBoTests/WeiBoTests.swift
1
957
// // WeiBoTests.swift // WeiBoTests // // Created by wuqh on 2017/6/12. // Copyright © 2017年 吴启晗. All rights reserved. // import XCTest @testable import WeiBo class WeiBoTests: 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. } } }
mit
buscarini/vitemo
vitemo/Carthage/Checkouts/SwiftFilePath/SwiftFilePath/Path.swift
2
3100
// // Path.swift // SwiftFilePath // // Created by nori0620 on 2015/01/08. // Copyright (c) 2015年 Norihiro Sakamoto. All rights reserved. // public class Path { // MARK: - Class methods public class func isDir(path:NSString) -> Bool { var isDirectory: ObjCBool = false let isFileExists = NSFileManager.defaultManager().fileExistsAtPath(path as String, isDirectory:&isDirectory) return isDirectory ? true : false } // MARK: - Instance properties and initializer lazy var fileManager = NSFileManager.defaultManager() public let path_string:String public init(_ p: String) { self.path_string = p } // MARK: - Instance val public var attributes:NSDictionary?{ get { return self.loadAttributes() } } public var asString: String { return path_string } public var exists: Bool { return fileManager.fileExistsAtPath(path_string) } public var isDir: Bool { return Path.isDir(path_string); } public var basename:NSString { return path_string.lastPathComponent } public var parent: Path{ return Path( path_string.stringByDeletingLastPathComponent ) } // MARK: - Instance methods public func toString() -> String { return path_string } public func remove() -> Result<Path,NSError> { assert(self.exists,"To remove file, file MUST be exists") var error: NSError? let result = fileManager.removeItemAtPath(path_string, error:&error) return result ? Result(success: self) : Result(failure: error!); } public func copyTo(toPath:Path) -> Result<Path,NSError> { assert(self.exists,"To copy file, file MUST be exists") var error: NSError? let result = fileManager.copyItemAtPath(path_string, toPath: toPath.toString(), error: &error) return result ? Result(success: self) : Result(failure: error!) } public func moveTo(toPath:Path) -> Result<Path,NSError> { assert(self.exists,"To move file, file MUST be exists") var error: NSError? let result = fileManager.moveItemAtPath(path_string, toPath: toPath.toString(), error: &error) return result ? Result(success: self) : Result(failure: error!) } private func loadAttributes() -> NSDictionary? { assert(self.exists,"File must be exists to load file.< \(path_string) >") var loadError: NSError? let result = self.fileManager.attributesOfItemAtPath(path_string, error: &loadError) if let error = loadError { println("Error< \(error.localizedDescription) >") } return result } } // MARK: - extension Path: Printable { public var description: String { return "\(NSStringFromClass(self.dynamicType))<path:\(path_string)>" } }
mit
ChristianKienle/highway
Sources/Task/TerminalTasks 2.swift
1
1844
// // Commands.swift // // Created by Stijn on 29/05/2018. // import Foundation import os import SourceryAutoProtocols import XCBuild public enum TerminalTask: RawRepresentable, Equatable, AutoCases { case git(ArgumentExecutableProtocol) case cat(ArgumentExecutableProtocol) case sourcery(ArgumentExecutableProtocol) case xcodebuild(ArgumentExecutableProtocol) case xcodebuildTests(TestOptionsProtocol) // MARK: - Executable var executable: ArgumentExecutableProtocol { switch self { case let .xcodebuild(exec): return exec case let .git(exec): return exec case let .sourcery(exec): return exec case let .cat(exec): return exec case let .xcodebuildTests(testOptions): return testOptions } } // MARK: - Equatable public static func == (lhs: TerminalTask, rhs: TerminalTask) -> Bool { switch (lhs, rhs) { case (.xcodebuild, .xcodebuild): return true case (.git, .git): return true case (.sourcery, .sourcery ): return true default: return false } } // MARK: - RawRepresentable public typealias RawValue = String public var rawValue: String { switch self { case .xcodebuild: return "xcodebuild" case .sourcery: return "sourcery" case .cat: return "cat" case .git: return "git" case .xcodebuildTests: return "xcodebuild" } } public init?(rawValue: String) { switch rawValue { default: os_log("not possible %@", type: .error, rawValue) return nil } } }
mit
rnystrom/GitHawk
Classes/Repository/RepositoryIssueSummaryModel.swift
1
1870
// // RepositoryIssueSummaryModel.swift // Freetime // // Created by Ryan Nystrom on 9/3/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit import StyledTextKit final class RepositoryIssueSummaryModel: ListSwiftDiffable { let id: String let title: StyledTextRenderer let number: Int let created: Date let author: String let status: IssueStatus let pullRequest: Bool let labels: [RepositoryLabel] let ciStatus: RepositoryIssueCIStatus? // quicker comparison for diffing rather than scanning the labels array let labelSummary: String init( id: String, title: StyledTextRenderer, number: Int, created: Date, author: String, status: IssueStatus, pullRequest: Bool, labels: [RepositoryLabel], ciStatus: RepositoryIssueCIStatus? ) { self.id = id self.title = title self.number = number self.created = created self.author = author self.status = status self.pullRequest = pullRequest self.labels = labels self.labelSummary = labels.reduce("", { $0 + $1.name }) self.ciStatus = ciStatus } // MARK: ListSwiftDiffable var identifier: String { return id } func isEqual(to value: ListSwiftDiffable) -> Bool { guard let object = value as? RepositoryIssueSummaryModel else { return false } return id == object.id && number == object.number && pullRequest == object.pullRequest && status == object.status && author == object.author && created == object.created && title.string == object.title.string && labelSummary == object.labelSummary && ciStatus == object.ciStatus } }
mit
qiscus/qiscus-sdk-ios
Qiscus/Qiscus/View/ChatPreviewDocVC.swift
1
10267
// // ChatPreviewDocVC.swift // qonsultant // // Created by Ahmad Athaullah on 7/27/16. // Copyright © 2016 qiscus. All rights reserved. // import UIKit import WebKit import SwiftyJSON import RealmSwift open class ChatPreviewDocVC: UIViewController, UIWebViewDelegate, WKNavigationDelegate { var webView = WKWebView() var url: String = "" var fileName: String = "" var progressView = UIProgressView(progressViewStyle: UIProgressViewStyle.bar) var roomName:String = "" var accountLinking = false var accountData:JSON? var accountLinkURL:String = "" var accountRedirectURL:String = "" var file:QFile? = nil deinit{ self.webView.removeObserver(self, forKeyPath: "estimatedProgress") } // MARK: - UI Lifecycle override open func viewDidLoad() { super.viewDidLoad() self.webView.navigationDelegate = self self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil) if !self.accountLinking { let shareButton = UIBarButtonItem(title: "Share", style: .plain, target: self, action: #selector(ChatPreviewDocVC.share)) self.navigationItem.rightBarButtonItem = shareButton } } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !accountLinking { self.navigationItem.setTitleWithSubtitle(title: self.roomName, subtitle: self.fileName) }else{ if let data = accountData { self.title = data["params"]["view_title"].stringValue self.accountLinkURL = data["url"].stringValue self.accountRedirectURL = data["redirect_url"].stringValue } } self.webView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(webView) self.view.addSubview(progressView) let constraints = [ NSLayoutConstraint(item: webView, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1, constant: 0), NSLayoutConstraint(item: webView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: webView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1, constant: 0), NSLayoutConstraint(item: webView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0), NSLayoutConstraint(item: self.progressView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: self.progressView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 0), NSLayoutConstraint(item: self.progressView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 0) ] view.addConstraints(constraints) view.layoutIfNeeded() //self.webView.backgroundColor = UIColor.red if !self.accountLinking{ if let openFile = self.file { if QFileManager.isFileExist(inLocalPath: openFile.localPath) { let url = URL(fileURLWithPath: openFile.localPath) self.webView.loadFileURL(url, allowingReadAccessTo: url) }else{ if let openURL = URL(string: openFile.url.replacingOccurrences(of: " ", with: "%20")){ self.webView.load(URLRequest(url: openURL)) } } }else if let openURL = URL(string: self.url.replacingOccurrences(of: " ", with: "%20")){ self.webView.load(URLRequest(url: openURL)) } }else{ if let openURL = URL(string: self.accountLinkURL.replacingOccurrences(of: " ", with: "%20")) { self.webView.load(URLRequest(url: openURL)) } } } override open func viewWillDisappear(_ animated: Bool) { self.progressView.removeFromSuperview() super.viewWillDisappear(animated) } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - WebView Delegate override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let objectSender = object as? WKWebView { if (keyPath! == "estimatedProgress") && (objectSender == self.webView) { progressView.isHidden = self.webView.estimatedProgress == 1 progressView.setProgress(Float(self.webView.estimatedProgress), animated: true) }else{ super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } }else{ super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } open func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int(0.2 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in self.progressView.progress = 0.0 } if !self.accountLinking { if let file = self.file { if !QFileManager.isFileExist(inLocalPath: file.localPath){ let remoteURL = file.url.replacingOccurrences(of: " ", with: "%20") if let url = URL(string: remoteURL) { do { let data = try Data(contentsOf: url as URL) let directoryPath = QFileManager.directoryPath(forDirectory: .comment) let path = "\(directoryPath)/\(file.filename.replacingOccurrences(of: " ", with: "_"))" try? data.write(to: URL(fileURLWithPath: path), options: [.atomic]) let realm = try! Realm(configuration: Qiscus.dbConfiguration) realm.refresh() try! realm.write { file.localPath = path } } catch { } } } } } } open func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int(0.2 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in self.progressView.progress = 0.0 //self.setupTableMessage(error.localizedDescription) } } open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { decisionHandler(WKNavigationActionPolicy.allow) if self.accountLinking { if let urlToLoad = webView.url { let urlString = urlToLoad.absoluteString if urlString == self.accountRedirectURL.replacingOccurrences(of: " ", with: "%20") { let _ = self.navigationController?.popViewController(animated: true) } } } } open func webViewDidFinishLoad(_ webView: UIWebView) { self.progressView.isHidden = true } // MARK: - Navigation open func goBack(_ sender: AnyObject) { let _ = self.navigationController?.popViewController(animated: true) } // MARK: - Custom Component open func backButton(_ target: UIViewController, action: Selector) -> UIBarButtonItem{ let backIcon = UIImageView() backIcon.contentMode = .scaleAspectFit let backLabel = UILabel() backLabel.text = "" backLabel.textColor = QiscusChatVC.currentNavbarTint backLabel.font = UIFont.systemFont(ofSize: 12) let image = Qiscus.image(named: "ic_back")?.withRenderingMode(.alwaysTemplate) backIcon.image = image backIcon.tintColor = QiscusChatVC.currentNavbarTint if UIApplication.shared.userInterfaceLayoutDirection == .leftToRight { backIcon.frame = CGRect(x: 0,y: 0,width: 10,height: 15) backLabel.frame = CGRect(x: 15,y: 0,width: 45,height: 15) }else{ backIcon.frame = CGRect(x: 50,y: 0,width: 10,height: 15) backLabel.frame = CGRect(x: 0,y: 0,width: 45,height: 15) } let backButton = UIButton(frame:CGRect(x: 0,y: 0,width: 60,height: 20)) backButton.addSubview(backIcon) backButton.addSubview(backLabel) backButton.addTarget(target, action: action, for: UIControlEvents.touchUpInside) return UIBarButtonItem(customView: backButton) } @objc func share(){ if let file = self.file { if QFileManager.isFileExist(inLocalPath: file.localPath){ let url = URL(fileURLWithPath: file.localPath) let activityViewController = UIActivityViewController(activityItems: [url], applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.view self.present(activityViewController, animated: true, completion: nil) }else{ if let url = URL(string: file.url) { let activityViewController = UIActivityViewController(activityItems: [url], applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.view self.present(activityViewController, animated: true, completion: nil) } } } } }
mit
ukitaka/UILifeCycleClosure
Example/UILifeCycleClosure/Example.swift
1
469
// // Example.swift // UILifeCycleClosure // // Created by Yuki Takahashi on 2015/10/13. // Copyright © 2015年 CocoaPods. All rights reserved. // import Foundation protocol ExampleProtocol : class { static var exampleTitle : String { get } static var exampleDescription : String { get } static var exampleIdentifier : String { get } } extension ExampleProtocol { static var exampleDescription : String { return "" } }
mit
cnoon/swift-compiler-crashes
crashes-duplicates/21113-no-stacktrace.swift
11
239
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension NSSet { enum S { deinit { let a { case let { { class case ,
mit
SuPair/firefox-ios
Sync/Synchronizers/Bookmarks/ThreeWayTreeMerger.swift
5
68073
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Deferred import Foundation import Shared import Storage import XCGLogger private let log = Logger.syncLogger private func negate<T>(_ f: @escaping (T) throws -> Bool) -> (T) throws -> Bool { return { try !f($0) } } extension Collection { func exclude(_ predicate: @escaping (Self.Iterator.Element) throws -> Bool) throws -> [Self.Iterator.Element] { return try self.filter(negate(predicate)) } } /** * This class takes as input three 'trees'. * * The mirror is always complete, never contains deletions, never has * orphans, and has a single root. * * Each of local and remote can contain a number of subtrees (each of which must * be a folder or root), a number of deleted GUIDs, and a number of orphans (records * with no known parent). * * As output it produces a merged tree. The tree contains the new structure, * including every record that we're keeping, and also makes note of any deletions. * * The merged tree can be walked to yield a set of operations against the original * three trees. Those operations will make the upstream source and local storage * match the merge output. * * It's very likely that there's almost no overlap between local and remote, and * thus no real conflicts to resolve -- a three-way merge isn't always a bad thing * -- but we won't know until we compare records. * * * Even though this is called 'three way merge', it also handles the case * of a two-way merge (one without a shared parent; for the roots, this will only * be on a first sync): content-based and structural merging is needed at all * layers of the hierarchy, so we simply generalize that to also apply to roots. * * In a sense, a two-way merge is solved by constructing a shared parent consisting of * roots, which are implicitly shared. * * (Special care must be taken to not deduce that one side has deleted a root, of course, * as would be the case of a Sync server that doesn't contain * a Mobile Bookmarks folder -- the set of roots can only grow, not shrink.) * * * To begin with we structurally reconcile. If necessary we will lazily fetch the * attributes of records in order to do a content-based reconciliation. Once we've * matched up any records that match (including remapping local GUIDs), we're able to * process _content_ changes, which is much simpler. * * We have to handle an arbitrary combination of the following structural operations: * * * Creating a folder. * Created folders might now hold existing items, new items, or nothing at all. * * Creating a bookmark. * It might be in a new folder or an existing folder. * * Moving one or more leaf records to an existing or new folder. * * Reordering the children of a folder. * * Deleting an entire subtree. * * Deleting an entire subtree apart from some moved nodes. * * Deleting a leaf node. * * Transplanting a subtree: moving a folder but not changing its children. * * And, of course, the non-structural operations such as renaming or changing URLs. * * We ignore all changes to roots themselves; the only acceptable operation on a root * is to change its children. The Places root is entirely immutable. * * Steps: * * Construct a collection of subtrees for local and buffer, and a complete tree for the mirror. * The more thorough this step, the more confidence we have in consistency. * * Fetch all local and remote deletions. These won't be included in structure (for obvious * reasons); we hold on to them explicitly so we can spot the difference between a move * and a deletion. * * Walk each subtree, top-down. At each point if there are two back-pointers to * the mirror node for a GUID, we have a potential conflict, and we have all three * parts that we need to resolve it via a content-based or structure-based 3WM. * * Observations: * * If every GUID on each side is present in the mirror, we have no new records. * * If a non-root GUID is present on both sides but not in the mirror, then either * we're re-syncing from scratch, or (unlikely) we have a random collision. * * Otherwise, we have a GUID that we don't recognize. We will structure+content reconcile * this later -- we first make sure we have handled any tree moves, so that the addition * of a bookmark to a moved folder on A, and the addition of the same bookmark to the non- * moved version of the folder, will collide successfully. * * When we look at a child list: * * It's the same. Great! Keep walking down. * * There are added GUIDs. * * An added GUID might be a move from elsewhere. Coordinate with the removal step. * * An added GUID might be a brand new record. If there are local additions too, * check to see if they value-reconcile, and keep the remote GUID. * * There are removed GUIDs. * * A removed GUID might have been deleted. Deletions win. * * A missing GUID might be a move -- removed from here and added to another folder. * Process this as a move. * * The order has changed. * * When we get to a subtree that contains no changes, we can never hit conflicts, and * application becomes easier. * * When we run out of subtrees on both sides, we're done. * * Note that these trees don't include values. This is because we usually don't need them: * if there are no conflicts, or no shared parents, we can do everything we need to do * at this stage simply with structure and GUIDs, and then flush rows straight from the * buffer into the mirror with a single SQL INSERT. We do need to fetch values later * in some cases: to amend child lists or otherwise construct outbound records. We do * need to fetch values immediately in other cases: in order to reconcile conflicts. * Those should ordinarily be uncommon, and because we know most of the conflicting * GUIDs up-front, we can prime a cache of records. */ class ThreeWayTreeMerger { let local: BookmarkTree let mirror: BookmarkTree let remote: BookmarkTree var merged: MergedTree // Don't merge twice. var mergeAttempted: Bool = false let itemSources: ItemSources // Sets computed by looking at the three trees. These are used for diagnostics, // to simplify operations, to pre-fetch items for value comparison, and for testing. let mirrorAllGUIDs: Set<GUID> // Excluding deletions. let localAllGUIDs: Set<GUID> // Excluding deletions. let remoteAllGUIDs: Set<GUID> // Excluding deletions. let localAdditions: Set<GUID> // New records added locally, not present in the mirror. let remoteAdditions: Set<GUID> // New records from the server, not present in the mirror. let allDeletions: Set<GUID> // Records deleted locally or remotely. var allChangedGUIDs: Set<GUID> // Everything added or changed locally or remotely. let conflictingGUIDs: Set<GUID> // Anything added or changed both locally and remotely. let nonRemoteKnownGUIDs: Set<GUID> // Everything existing, added, or deleted locally or in the mirror. // For now, track just one list. We might need to split this later. var done: Set<GUID> = Set() // Local records that we identified as being the same as remote records. var duped: Set<GUID> = Set() init(local: BookmarkTree, mirror: BookmarkTree, remote: BookmarkTree, itemSources: ItemSources) { precondition(mirror.root != nil) assert((mirror.root!.children?.count ?? 0) == BookmarkRoots.RootChildren.count) precondition(mirror.orphans.isEmpty) precondition(mirror.deleted.isEmpty) precondition(mirror.subtrees.count == 1) // These are runtime-tested in merge(). assert to make sure that tests // don't do anything stupid, and we don't slip past those constraints. //assert(local.isFullyRootedIn(mirror)) //assert(remote.isFullyRootedIn(mirror)) self.local = local self.mirror = mirror self.remote = remote self.itemSources = itemSources self.merged = MergedTree(mirrorRoot: self.mirror.root!) // We won't get here unless every local and remote orphan is correctly rooted // when overlaid on the mirror, so we don't need to exclude orphans here. self.mirrorAllGUIDs = self.mirror.modified self.localAllGUIDs = self.local.modified self.remoteAllGUIDs = self.remote.modified self.localAdditions = localAllGUIDs.subtracting(mirrorAllGUIDs) self.remoteAdditions = remoteAllGUIDs.subtracting(mirrorAllGUIDs) self.allDeletions = self.local.deleted.union(self.remote.deleted) self.allChangedGUIDs = localAllGUIDs.union(self.remoteAllGUIDs) self.conflictingGUIDs = localAllGUIDs.intersection(remoteAllGUIDs) self.nonRemoteKnownGUIDs = self.mirrorAllGUIDs.union(self.localAllGUIDs).union(self.local.deleted) } fileprivate func nullOrMatch(_ a: String?, _ b: String?) -> Bool { guard let a = a, let b = b else { return true } return a == b } /** * When we have a folder match and new records on each side -- records * not mentioned in the buffer -- it's possible that the new records * are the same but have different GUIDs. * This function will look at value matches to identify a local * equivalent in this folder, returning nil if none are found. * * Note that we don't match records that have already been matched, and * we don't match any for which a GUID is known in the mirror or remote. */ fileprivate func findNewLocalNodeMatchingContentOfRemoteNote(_ remote: BookmarkTreeNode, inFolder parent: GUID, withLocalChildren children: [BookmarkTreeNode], havingSeen seen: Set<GUID>) -> BookmarkTreeNode? { // TODO: don't compute this list once per incoming child! Profile me. let candidates = children.filter { child in let childGUID = child.recordGUID return !seen.contains(childGUID) && // Not already used in this folder. !self.remoteAdditions.contains(childGUID) && // Not locally and remotely added with same GUID. !self.remote.deleted.contains(childGUID) && // Not remotely deleted. !self.done.contains(childGUID) // Not already processed elsewhere in the tree. } guard let remoteValue = self.itemSources.buffer.getBufferItemWithGUID(remote.recordGUID).value.successValue else { log.error("Couldn't find remote value for \(remote.recordGUID).") return nil } let guids = candidates.map { $0.recordGUID } guard let items = self.itemSources.local.getLocalItemsWithGUIDs(guids).value.successValue else { log.error("Couldn't find local values for \(candidates.count) candidates.") return nil } // Return the first candidate that's a value match. guard let localItem = (guids.compactMap { items[$0] }.find { $0.sameAs(remoteValue) }) else { log.debug("Didn't find a local value match for new remote record \(remote.recordGUID).") return nil } log.debug("Found a local match \(localItem.guid) for new remote record \(remote.recordGUID) in parent \(parent).") // Find the original contributing child node by GUID. return children.find { $0.recordGUID == localItem.guid } } fileprivate func takeMirrorChildrenInMergedNode(_ result: MergedTreeNode) throws { guard let mirrorChildren = result.mirror?.children else { preconditionFailure("Expected children.") } let out: [MergedTreeNode] = try mirrorChildren.compactMap { child in // TODO: handle deletions. That might change the below from 'Unchanged' // to 'New'. let childGUID = child.recordGUID if self.done.contains(childGUID) { log.warning("Not taking mirror child \(childGUID): already done. This is unexpected.") return nil } let localCounterpart = self.local.find(childGUID) let remoteCounterpart = self.remote.find(childGUID) return try self.mergeNode(childGUID, localNode: localCounterpart, mirrorNode: child, remoteNode: remoteCounterpart) } result.mergedChildren = out result.structureState = MergeState.unchanged } fileprivate func oneWayMergeChildListsIntoMergedNode(_ result: MergedTreeNode, fromRemote remote: BookmarkTreeNode) throws { guard case .folder = remote else { preconditionFailure("Expected folder from which to merge children.") } result.structureState = MergeState.remote // If the list changes, this will switch to .new. try self.mergeChildListsIntoMergedNode(result, fromLocal: nil, remote: remote, mirror: self.mirror.find(remote.recordGUID)) } fileprivate func oneWayMergeChildListsIntoMergedNode(_ result: MergedTreeNode, fromLocal local: BookmarkTreeNode) throws { guard case .folder = local else { preconditionFailure("Expected folder from which to merge children.") } result.structureState = MergeState.local // If the list changes, this will switch to .new. try self.mergeChildListsIntoMergedNode(result, fromLocal: local, remote: nil, mirror: self.mirror.find(local.recordGUID)) } fileprivate func mergeChildListsIntoMergedNode(_ result: MergedTreeNode, fromLocal local: BookmarkTreeNode?, remote: BookmarkTreeNode?, mirror: BookmarkTreeNode?) throws { precondition(local != nil || remote != nil, "Expected either local or remote folder for merge.") // The most trivial implementation: take everything in the first list, then append // everything new in the second list. // Anything present in both is resolved. // We can't get away from handling deletions and moves, etc. -- one might have // created a folder on two devices and moved existing items on one, some of which // might have been deleted on the other. // This kind of shit is why bookmark sync is hard. // See each of the test cases in TestBookmarkTreeMerging, which have helpful diagrams. var out: [MergedTreeNode] = [] var seen: Set<GUID> = Set() var changed = false func processRemoteOrphansForNode(_ node: BookmarkTreeNode) throws -> [MergedTreeNode]? { // Now we recursively merge down into our list of orphans. If those contain deleted // subtrees, excess leaves will be flattened up; we'll get a single list of nodes // here, and we'll take them as additional children. let guid = node.recordGUID func isLocallyDeleted(_ child: BookmarkTreeNode) throws -> Bool { return try checkForLocalDeletionOfRemoteNode(child, mirrorNode: self.mirror.find(child.recordGUID)) } guard let orphans = try node.children?.exclude(isLocallyDeleted), !orphans.isEmpty else { log.debug("No remote orphans from local deletion of \(guid).") return nil } let mergedOrphans = try orphans.map { (orphan: BookmarkTreeNode) throws -> MergedTreeNode in let guidO = orphan.recordGUID let locO = self.local.find(guidO) let remO = orphan let mirO = self.mirror.find(guidO) log.debug("Merging up remote orphan \(guidO).") return try self.mergeNode(guidO, localNode: locO, mirrorNode: mirO, remoteNode: remO) } log.debug("Collected \(mergedOrphans.count) remote orphans for deleted folder \(guid).") if mergedOrphans.isEmpty { return nil } changed = true return mergedOrphans } func processLocalOrphansForNode(_ node: BookmarkTreeNode) throws -> [MergedTreeNode]? { // Now we recursively merge down into our list of orphans. If those contain deleted // subtrees, excess leaves will be flattened up; we'll get a single list of nodes // here, and we'll take them as additional children. let guid = node.recordGUID if case .folder = node {} else { log.debug("\(guid) isn't a folder, so it won't have orphans.") return nil } func isRemotelyDeleted(_ child: BookmarkTreeNode) throws -> Bool { return try checkForRemoteDeletionOfLocalNode(child, mirrorNode: self.mirror.find(child.recordGUID)) } guard let orphans = try node.children?.exclude(isRemotelyDeleted), !orphans.isEmpty else { log.debug("No local orphans from remote deletion of folder \(guid).") return nil } let mergedOrphans = try orphans.map { (orphan: BookmarkTreeNode) throws -> MergedTreeNode in let guidO = orphan.recordGUID let locO = orphan let remO = self.remote.find(guidO) let mirO = self.mirror.find(guidO) log.debug("Merging up local orphan \(guidO).") return try self.mergeNode(guidO, localNode: locO, mirrorNode: mirO, remoteNode: remO) } log.debug("Collected \(mergedOrphans.count) local orphans for deleted folder \(guid).") if mergedOrphans.isEmpty { return nil } changed = true return mergedOrphans } func checkForLocalDeletionOfRemoteNode(_ node: BookmarkTreeNode, mirrorNode: BookmarkTreeNode?) throws -> Bool { let guid = node.recordGUID guard self.local.deleted.contains(guid) else { return false } // It was locally deleted. This would be good enough for us, // but we need to ensure that any remote children are recursively // deleted or handled as orphans. log.warning("Quietly accepting local deletion of record \(guid).") changed = true self.merged.deleteRemotely.insert(guid) self.merged.acceptLocalDeletion.insert(guid) if mirrorNode != nil { self.merged.deleteFromMirror.insert(guid) } if let orphans = try processRemoteOrphansForNode(node) { out.append(contentsOf: try self.relocateOrphansTo(result, orphans: orphans)) } return true } func checkForRemoteDeletionOfLocalNode(_ node: BookmarkTreeNode, mirrorNode: BookmarkTreeNode?) throws -> Bool { let guid = node.recordGUID guard self.remote.deleted.contains(guid) else { return false } // It was remotely deleted. This would be good enough for us, // but we need to ensure that any local children are recursively // deleted or handled as orphans. log.warning("Quietly accepting remote deletion of record \(guid).") self.merged.deleteLocally.insert(guid) self.merged.acceptRemoteDeletion.insert(guid) if mirrorNode != nil { self.merged.deleteFromMirror.insert(guid) } if let orphans = try processLocalOrphansForNode(node) { out.append(contentsOf: try self.relocateOrphansTo(result, orphans: orphans)) } return true } // Do a recursive merge of each child. if let remote = remote, let children = remote.children { try children.forEach { rem in let guid = rem.recordGUID seen.insert(guid) if self.done.contains(guid) { log.debug("Processing children of \(result.guid). Child \(guid) already seen elsewhere!") return } if try checkForLocalDeletionOfRemoteNode(rem, mirrorNode: self.mirror.find(guid)) { log.debug("Child \(guid) is locally deleted.") return } let mir = self.mirror.find(guid) if let localByGUID = self.local.find(guid) { // Let's check the parent of the local match. If it differs, then the matching // record is elsewhere in the local tree, and we need to decide which place to // keep it. // We do so by finding the modification time of the parent on each side, // unless one of the records is explicitly non-modified. if let localParentGUID = self.local.parents[guid] { // Oh hey look! Ad hoc three-way merge! let mirrorParentGUID = self.mirror.parents[guid] if localParentGUID != result.guid { log.debug("Local child \(guid) is in folder \(localParentGUID), but remotely is in \(result.guid).") if mirrorParentGUID != localParentGUID { log.debug("… and locally it has changed since our last sync, moving from \(mirrorParentGUID ?? "nil") to \(localParentGUID).") // Find out which parent is most recent. if let localRecords = self.itemSources.local.getLocalItemsWithGUIDs([localParentGUID, guid]).value.successValue, let remoteRecords = self.itemSources.buffer.getBufferItemsWithGUIDs([result.guid, guid]).value.successValue { let latestLocalTimestamp = max(localRecords[guid]?.localModified ?? 0, localRecords[localParentGUID]?.localModified ?? 0) let latestRemoteTimestamp = max(remoteRecords[guid]?.serverModified ?? 0, remoteRecords[result.guid]?.serverModified ?? 0) log.debug("Latest remote timestamp: \(latestRemoteTimestamp). Latest local timestamp: \(latestLocalTimestamp).") if latestLocalTimestamp > latestRemoteTimestamp { log.debug("Keeping record in its local position. We'll merge these later.") return } log.debug("Taking remote, because it's later. Merging now.") } } else { log.debug("\(guid) didn't move from \(mirrorParentGUID ?? "nil") since our last sync. Taking remote parent.") } } else { log.debug("\(guid) is locally in \(localParentGUID) and remotely in \(result.guid). Easy.") } } out.append(try self.mergeNode(guid, localNode: localByGUID, mirrorNode: mir, remoteNode: rem)) return } // We don't ever have to handle moves in this case: we only search this directory. let localByContent: BookmarkTreeNode? if let localChildren = local?.children { localByContent = self.findNewLocalNodeMatchingContentOfRemoteNote(rem, inFolder: result.guid, withLocalChildren: localChildren, havingSeen: seen) } else { localByContent = nil } out.append(try self.mergeNode(guid, localNode: localByContent, mirrorNode: mir, remoteNode: rem)) } } if let local = local, let children = local.children { try children.forEach { loc in let guid = loc.recordGUID if seen.contains(guid) { log.debug("Already saw local child \(guid).") return } if self.done.contains(guid) { log.debug("Already saw local child \(guid) elsewhere.") return } if try checkForRemoteDeletionOfLocalNode(loc, mirrorNode: self.mirror.find(guid)) { return } let mir = self.mirror.find(guid) let rem = self.remote.find(guid) changed = true out.append(try self.mergeNode(guid, localNode: loc, mirrorNode: mir, remoteNode: rem)) } } // Walk the mirror node's children. Any that are deleted on only one side might contribute // orphans, so descend into those nodes' children on the other side. if let expectedParent = mirror?.recordGUID, let mirrorChildren = mirror?.children { try mirrorChildren.forEach { child in let potentiallyDeleted = child.recordGUID if seen.contains(potentiallyDeleted) || self.done.contains(potentiallyDeleted) { return } let locallyDeleted = self.local.deleted.contains(potentiallyDeleted) let remotelyDeleted = self.remote.deleted.contains(potentiallyDeleted) if !locallyDeleted && !remotelyDeleted { log.debug("Mirror child \(potentiallyDeleted) no longer here, but not deleted on either side: must be elsewhere.") return } if locallyDeleted && remotelyDeleted { log.debug("Mirror child \(potentiallyDeleted) was deleted both locally and remoted. We cool.") self.merged.deleteFromMirror.insert(potentiallyDeleted) self.merged.acceptLocalDeletion.insert(potentiallyDeleted) self.merged.acceptRemoteDeletion.insert(potentiallyDeleted) return } if locallyDeleted { // See if the remote side still thinks this is the parent. let parent = self.remote.parents[potentiallyDeleted] if parent == nil || parent == expectedParent { log.debug("Remote still thinks \(potentiallyDeleted) is here. Processing for orphans.") if let parentOfOrphans = self.remote.find(potentiallyDeleted), let orphans = try processRemoteOrphansForNode(parentOfOrphans) { out.append(contentsOf: try self.relocateOrphansTo(result, orphans: orphans)) } } // Accept the local deletion, and make a note to apply it elsewhere. self.merged.deleteFromMirror.insert(potentiallyDeleted) self.merged.deleteRemotely.insert(potentiallyDeleted) self.merged.acceptLocalDeletion.insert(potentiallyDeleted) return } // Remotely deleted. let parent = self.local.parents[potentiallyDeleted] if parent == nil || parent == expectedParent { log.debug("Local still thinks \(potentiallyDeleted) is here. Processing for orphans.") if let parentOfOrphans = self.local.find(potentiallyDeleted), let orphans = try processLocalOrphansForNode(parentOfOrphans) { out.append(contentsOf: try self.relocateOrphansTo(result, orphans: orphans)) } } // Accept the remote deletion, and make a note to apply it elsewhere. self.merged.deleteFromMirror.insert(potentiallyDeleted) self.merged.deleteLocally.insert(potentiallyDeleted) self.merged.acceptRemoteDeletion.insert(potentiallyDeleted) } } log.debug("Setting \(result.guid)'s children to \(out.map { $0.guid }).") result.mergedChildren = out // If the child list didn't change, then we don't need .new. if changed { let newStructure = out.map { $0.asMergedTreeNode() } result.structureState = MergeState.new(value: BookmarkTreeNode.folder(guid: result.guid, children: newStructure)) return } log.debug("Child list didn't change for \(result.guid). Keeping structure state \(result.structureState).") } fileprivate func resolveThreeWayValueConflict(_ guid: GUID) throws -> MergeState<BookmarkMirrorItem> { // TODO return try self.resolveTwoWayValueConflict(guid, localGUID: guid) } fileprivate func resolveTwoWayValueConflict(_ guid: GUID, localGUID: GUID) throws -> MergeState<BookmarkMirrorItem> { // We don't check for all roots, because we might have to // copy them to the mirror or buffer, so we need to pick // a direction. The Places root is never uploaded. if BookmarkRoots.RootGUID == guid { log.debug("Two-way value merge on the root: always unaltered.") return MergeState.unchanged } let localRecord = self.itemSources.local.getLocalItemWithGUID(localGUID).value.successValue let remoteRecord = self.itemSources.buffer.getBufferItemWithGUID(guid).value.successValue if let local = localRecord { if let remote = remoteRecord { // Two-way. // If they're the same, take the remote record. It saves us having to rewrite // local values to keep a remote GUID. if local.sameAs(remote) { log.debug("Local record \(local.guid) same as remote \(remote.guid). Taking remote.") return MergeState.remote } log.debug("Comparing local (\(local.localModified ??? "0")) to remote (\(remote.serverModified)) clock for two-way value merge of \(guid).") if let localModified = local.localModified, localModified > remote.serverModified { // If we're taking the local record because it was modified, check to see // whether the remote record has a creation date that we want to keep. let dateAddedRemote = remote.dateAdded ?? remote.serverModified if (local.dateAdded ?? UInt64.max) > dateAddedRemote { return MergeState.new(value: local.copyWithDateAdded(dateAddedRemote)) } return MergeState.local } return MergeState.remote } // No remote! log.debug("Expected two-way merge for \(guid), but no remote item found.") return MergeState.local } if let _ = remoteRecord { // No local! log.debug("Expected two-way merge for \(guid), but no local item found.") return MergeState.remote } // Can't two-way merge with nothing! log.error("Expected two-way merge for \(guid), but no local or remote item found!") throw BookmarksMergeError() } // This will never be called with two primary .unknown values. fileprivate func threeWayMerge(_ guid: GUID, localNode: BookmarkTreeNode, remoteNode: BookmarkTreeNode, mirrorNode: BookmarkTreeNode?) throws -> MergedTreeNode { if mirrorNode == nil { log.debug("Two-way merge for \(guid).") } else { log.debug("Three-way merge for \(guid).") } if remoteNode.isUnknown { if localNode.isUnknown { preconditionFailure("Two unknown nodes!") } log.debug("Taking local node in two/three-way merge: remote bafflingly unchanged.") // TODO: value-unchanged return MergedTreeNode.forLocal(localNode) } if localNode.isUnknown { log.debug("Taking remote node in two/three-way merge: local bafflingly unchanged.") // TODO: value-unchanged return MergedTreeNode.forRemote(remoteNode) } let result = MergedTreeNode(guid: guid, mirror: mirrorNode) result.local = localNode result.remote = remoteNode // Value merge. This applies regardless. if localNode.isUnknown { result.valueState = MergeState.remote } else if remoteNode.isUnknown { result.valueState = MergeState.local } else { if mirrorNode == nil { result.valueState = try self.resolveTwoWayValueConflict(guid, localGUID: localNode.recordGUID) } else { result.valueState = try self.resolveThreeWayValueConflict(guid) } } switch localNode { case let .folder(_, localChildren): if case let .folder(_, remoteChildren) = remoteNode { // Structural merge. if localChildren.sameElements(remoteChildren) { // Great! log.debug("Local and remote records have same children in two-way merge.") result.structureState = MergeState.new(value: localNode) // TODO: what if it's the same as the mirror? try self.mergeChildListsIntoMergedNode(result, fromLocal: localNode, remote: remoteNode, mirror: mirrorNode) return result } // Merge the two folder lists. // We know that each side is internally consistent: that is, each // node in this list is present in the tree once only. But when we // combine the two lists, we might be inadvertently duplicating a // record that has already been, or will soon be, found in the other // tree. We need to be careful to make sure that we don't feature // a node in the tree more than once. // Remember to check deletions. log.debug("Local and remote records have different children. Merging.") // Assume it'll be the same as the remote one; mergeChildListsIntoMergedNode // sets this to New if the structure changes. result.structureState = MergeState.remote try self.mergeChildListsIntoMergedNode(result, fromLocal: localNode, remote: remoteNode, mirror: mirrorNode) return result } case .nonFolder: if case .nonFolder = remoteNode { log.debug("Two non-folders with GUID \(guid) collide. Taking remote.") return result } default: break } // Otherwise, this must be a GUID collision between different types. // TODO: Assign a new GUID to the local record // but do not upload a deletion; these shouldn't merge. log.debug("Remote and local records with same GUID \(guid) but different types. Consistency error.") throw BookmarksMergeConsistencyError() } fileprivate func twoWayMerge(_ guid: GUID, localNode: BookmarkTreeNode, remoteNode: BookmarkTreeNode) throws -> MergedTreeNode { return try self.threeWayMerge(guid, localNode: localNode, remoteNode: remoteNode, mirrorNode: nil) } fileprivate func unchangedIf(_ out: MergedTreeNode, original: BookmarkMirrorItem?, new: BookmarkMirrorItem?) -> MergedTreeNode { guard let original = original, let new = new else { return out } if new.sameAs(original) { out.valueState = MergeState.unchanged } return out } fileprivate func takeLocalIfChanged(_ local: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) -> MergedTreeNode { let guid = local.recordGUID let localValues = self.itemSources.local.getLocalItemWithGUID(guid).value.successValue let mirrorValues = self.itemSources.mirror.getMirrorItemWithGUID(guid).value.successValue // We don't expect these to ever fail to exist. assert(localValues != nil) let merged = MergedTreeNode.forLocal(local, mirror: mirror) return unchangedIf(merged, original: mirrorValues, new: localValues) } fileprivate func takeRemoteIfChanged(_ remote: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) -> MergedTreeNode { let guid = remote.recordGUID let remoteValues = self.itemSources.buffer.getBufferItemWithGUID(guid).value.successValue let mirrorValues = self.itemSources.mirror.getMirrorItemWithGUID(guid).value.successValue assert(remoteValues != nil) let merged = MergedTreeNode.forRemote(remote, mirror: mirror) return unchangedIf(merged, original: mirrorValues, new: remoteValues) } fileprivate var folderNameCache: [GUID: String?] = [:] func getNameForFolder(_ folder: MergedTreeNode) throws -> String? { if let name = self.folderNameCache[folder.guid] { return name } let name = try self.fetchNameForFolder(folder) self.folderNameCache[folder.guid] = name return name } func fetchNameForFolder(_ folder: MergedTreeNode) throws -> String? { switch folder.valueState { case let .new(v): return v.title case .unchanged: if let mirror = folder.mirror?.recordGUID, let title = self.itemSources.mirror.getMirrorItemWithGUID(mirror).value.successValue?.title { return title } case .remote: if let remote = folder.remote?.recordGUID, let title = self.itemSources.buffer.getBufferItemWithGUID(remote).value.successValue?.title { return title } case .local: if let local = folder.local?.recordGUID, let title = self.itemSources.local.getLocalItemWithGUID(local).value.successValue?.title { return title } case .unknown: break } throw BookmarksMergeConsistencyError() } func relocateOrphansTo(_ mergedNode: MergedTreeNode, orphans: [MergedTreeNode]?) throws -> [MergedTreeNode] { guard let orphans = orphans else { return [] } let parentName = try self.getNameForFolder(mergedNode) return try orphans.map { try self.relocateMergedTreeNode($0, parentID: mergedNode.guid, parentName: parentName) } } func relocateMergedTreeNode(_ node: MergedTreeNode, parentID: GUID, parentName: String?) throws -> MergedTreeNode { func copyWithMirrorItem(_ item: BookmarkMirrorItem?) throws -> MergedTreeNode { guard let item = item else { throw BookmarksMergeConsistencyError() } if item.parentID == parentID && item.parentName == parentName { log.debug("Don't need to relocate \(node.guid)'s for value table.") return node } log.debug("Relocating \(node.guid) to parent \(parentID).") let n = MergedTreeNode(guid: node.guid, mirror: node.mirror) n.local = node.local n.remote = node.remote n.mergedChildren = node.mergedChildren n.structureState = node.structureState n.valueState = .new(value: item.copyWithParentID(parentID, parentName: parentName)) return n } switch node.valueState { case .unknown: return node case .unchanged: return try copyWithMirrorItem(self.itemSources.mirror.getMirrorItemWithGUID(node.guid).value.successValue) case .local: return try copyWithMirrorItem(self.itemSources.local.getLocalItemWithGUID(node.guid).value.successValue) case .remote: return try copyWithMirrorItem(self.itemSources.buffer.getBufferItemWithGUID(node.guid).value.successValue) case let .new(value): return try copyWithMirrorItem(value) } } // A helper that'll rewrite the resulting node's value to have the right parent. func mergeNode(_ guid: GUID, intoFolder parentID: GUID, withParentName parentName: String?, localNode: BookmarkTreeNode?, mirrorNode: BookmarkTreeNode?, remoteNode: BookmarkTreeNode?) throws -> MergedTreeNode { let m = try self.mergeNode(guid, localNode: localNode, mirrorNode: mirrorNode, remoteNode: remoteNode) // We could check the parent pointers in the tree, but looking at the values themselves // will catch any mismatches between the value and structure tables. return try self.relocateMergedTreeNode(m, parentID: parentID, parentName: parentName) } // We'll end up looking at deletions and such as we go. // TODO: accumulate deletions into the three buckets as we go. // // TODO: if a local or remote node is kept but put in a different folder, we actually // need to generate a .new node, so we can take the parentid and parentNode that we // must preserve. func mergeNode(_ guid: GUID, localNode: BookmarkTreeNode?, mirrorNode: BookmarkTreeNode?, remoteNode: BookmarkTreeNode?) throws -> MergedTreeNode { if let localGUID = localNode?.recordGUID { log.verbose("Merging nodes with GUID \(guid). Local match is \(localGUID).") } else { log.verbose("Merging nodes with GUID \(guid). No local match.") } // TODO: if the local node has a different GUID, it's because we did a value-based // merge. Make sure the local row with the differing local GUID doesn't // stick around. // We'll never get here with no nodes at all… right? precondition((localNode != nil) || (mirrorNode != nil) || (remoteNode != nil)) // Note that not all of the input nodes must share a GUID: we might have decided, based on // value comparison in an earlier recursive call, that a local node will be replaced by a // remote node, and we'll need to mark the local GUID as a deletion, using its values and // structure during our reconciling. // But we will never have the mirror and remote differ. precondition(nullOrMatch(remoteNode?.recordGUID, mirrorNode?.recordGUID)) precondition(nullOrMatch(remoteNode?.recordGUID, guid)) precondition(nullOrMatch(mirrorNode?.recordGUID, guid)) // Immediately mark this GUID -- and the local GUID, if it differs -- as done. // This avoids repeated code in each conditional branch, and avoids the possibility of // certain moves causing us to hit the same node again. self.done.insert(guid) if let otherGUID = localNode?.recordGUID, otherGUID != guid { log.debug("Marking superseded local record \(otherGUID) as merged.") self.done.insert(otherGUID) self.duped.insert(otherGUID) } func takeRemoteAndMergeChildren(_ remote: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) throws -> MergedTreeNode { let merged = self.takeRemoteIfChanged(remote, mirror: mirror) if case .folder = remote { log.debug("… and it's a folder. Taking remote children.") try self.oneWayMergeChildListsIntoMergedNode(merged, fromRemote: remote) } return merged } func takeLocalAndMergeChildren(_ local: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) throws -> MergedTreeNode { let merged = self.takeLocalIfChanged(local, mirror: mirror) if case .folder = local { log.debug("… and it's a folder. Taking local children.") try self.oneWayMergeChildListsIntoMergedNode(merged, fromLocal: local) } return merged } func takeMirrorNode(_ mirror: BookmarkTreeNode) throws -> MergedTreeNode { let merged = MergedTreeNode.forUnchanged(mirror) if case .folder = mirror { try self.takeMirrorChildrenInMergedNode(merged) } return merged } // If we ended up here with two unknowns, just proceed down the mirror. // We know we have a mirror, else we'd have a non-unknown edge. if (localNode?.isUnknown ?? true) && (remoteNode?.isUnknown ?? true) { precondition(mirrorNode != nil) log.verbose("Record \(guid) didn't change from mirror.") self.done.insert(guid) return try takeMirrorNode(mirrorNode!) } guard let mirrorNode = mirrorNode else { // No mirror node: at most a two-way merge. if let loc = localNode, !loc.isUnknown { if let rem = remoteNode { // Two-way merge; probably a disconnect-reconnect scenario. return try self.twoWayMerge(guid, localNode: loc, remoteNode: rem) } // No remote. Node only exists locally. // However! The children might be mentioned in the mirror or // remote tree. log.verbose("Node \(guid) only exists locally.") return try takeLocalAndMergeChildren(loc) } // No local. guard let rem = remoteNode, !rem.isUnknown else { // No remote! // This should not occur: we have preconditions above. preconditionFailure("Unexpectedly got past our preconditions!") } // Node only exists remotely. Take it. log.verbose("Node \(guid) only exists remotely.") return try takeRemoteAndMergeChildren(rem) } // We have a mirror node. if let loc = localNode, !loc.isUnknown { if let rem = remoteNode, !rem.isUnknown { log.debug("Both local and remote changes to mirror item \(guid). Resolving conflict.") return try self.threeWayMerge(guid, localNode: loc, remoteNode: rem, mirrorNode: mirrorNode) } log.verbose("Local-only change to mirror item \(guid).") return try takeLocalAndMergeChildren(loc, mirror: mirrorNode) } if let rem = remoteNode, !rem.isUnknown { log.verbose("Remote-only change to mirror item \(guid).") return try takeRemoteAndMergeChildren(rem, mirror: mirrorNode) } log.verbose("Record \(guid) didn't change from mirror.") return try takeMirrorNode(mirrorNode) } func merge() -> Deferred<Maybe<BookmarksMergeResult>> { return self.produceMergedTree() >>== self.produceMergeResultFromMergedTree } func produceMergedTree() -> Deferred<Maybe<MergedTree>> { // Don't ever do this work twice. if self.mergeAttempted { return deferMaybe(self.merged) } // Both local and remote should reach a single root when overlayed. If not, it means that // the tree is inconsistent -- there isn't a full tree present either on the server (or // local) or in the mirror, or the changes aren't congruent in some way. If we reach this // state, we cannot proceed. // // This is assert()ed in the initializer, too, so that we crash hard and early in developer // builds and tests. if !self.local.isFullyRootedIn(self.mirror) { log.warning("Local bookmarks not fully rooted when overlayed on mirror. This is most unusual.") return deferMaybe(BookmarksMergeErrorTreeIsUnrooted(roots: self.local.subtreeGUIDs)) } if !self.remote.isFullyRootedIn(mirror) { log.warning("Remote bookmarks not fully rooted when overlayed on mirror. Partial read or write in buffer?") // This might be a temporary state: another client might not have uploaded all of its // records yet. Another batch might arrive in a second, or it might arrive a month // later if the user just closed the lid of their laptop and went on vacation! // // This can also be a semi-stable state; e.g., Bug 1235269. It's theoretically // possible for us to try to recover by requesting reupload from other devices // by changing syncID, or through some new command. // // Regardless, we can't proceed until this situation changes. return deferMaybe(BookmarksMergeErrorTreeIsUnrooted(roots: self.remote.subtreeGUIDs)) } log.debug("Processing \(self.localAllGUIDs.count) local changes and \(self.remoteAllGUIDs.count) remote changes.") log.debug("\(self.local.subtrees.count) local subtrees and \(self.remote.subtrees.count) remote subtrees.") log.debug("Local is adding \(self.localAdditions.count) records, and remote is adding \(self.remoteAdditions.count).") log.debug("Local and remote have \(self.allDeletions.count) deletions.") if !conflictingGUIDs.isEmpty { log.warning("Expecting conflicts between local and remote: \(self.conflictingGUIDs.joined(separator: ", ")).") } // Pre-fetch items so we don't need to do async work later. return self.prefetchItems() >>> self.walkProducingMergedTree } fileprivate func prefetchItems() -> Success { return self.itemSources.prefetchWithGUIDs(self.allChangedGUIDs) } // This should only be called once. // Callers should ensure validity of inputs. fileprivate func walkProducingMergedTree() -> Deferred<Maybe<MergedTree>> { let root = self.merged.root assert((root.mirror?.children?.count ?? 0) == BookmarkRoots.RootChildren.count) // Get to walkin'. root.structureState = MergeState.unchanged // We never change the root. root.valueState = MergeState.unchanged root.local = self.local.find(BookmarkRoots.RootGUID) do { try root.mergedChildren = root.mirror!.children!.map { let guid = $0.recordGUID let loc = self.local.find(guid) let mir = self.mirror.find(guid) let rem = self.remote.find(guid) return try self.mergeNode(guid, localNode: loc, mirrorNode: mir, remoteNode: rem) } } catch let error as MaybeErrorType { return deferMaybe(error) } catch let error { return deferMaybe(BookmarksMergeError(error: error)) } // If the buffer contains deletions for records that aren't in the mirror or in local, // then we'll never normally encounter them, and thus we'll never accept the deletion. // Check for that here. let additionalRemoteDeletions = self.remote.deleted.subtracting(self.done) log.debug("Additional remote deletions: \(additionalRemoteDeletions.count).") self.merged.acceptRemoteDeletion.formUnion(additionalRemoteDeletions) self.mergeAttempted = true // Validate. Note that we might end up with *more* records than this -- records // that didn't change naturally aren't present in the change list on either side. let expected = self.allChangedGUIDs.subtracting(self.allDeletions).subtracting(self.duped) assert(self.merged.allGUIDs.isSuperset(of: expected)) assert(self.merged.allGUIDs.intersection(self.allDeletions).isEmpty) return deferMaybe(self.merged) } /** * Input to this function will be a merged tree: a collection of known deletions, * and a tree of nodes that reflect an action and pointers to the edges and the * mirror, something like this: * * ------------------------------------------------------------------------------- * Deleted locally: folderBBBBBB * Deleted remotely: folderDDDDDD * Deleted from mirror: folderBBBBBB, folderDDDDDD * Accepted local deletions: folderDDDDDD * Accepted remote deletions: folderBBBBBB * Root: * [V: □ M □ root________ Unchanged ] * [S: Unchanged ] * .. * [V: □ M □ menu________ Unchanged ] * [S: Unchanged ] * .. * [V: □ M L folderCCCCCC Unchanged ] * [S: New ] * .. * [V: R □ □ bookmarkFFFF Remote ] * [V: □ M □ toolbar_____ Unchanged ] * [S: Unchanged ] * .. * [V: R M □ folderAAAAAA Unchanged ] * [S: New ] * .. * [V: □ □ L r_FpO9_RAXp3 Local ] * [V: □ M □ unfiled_____ Unchanged ] * [S: Unchanged ] * .. * [V: □ M □ mobile______ Unchanged ] * [S: Unchanged ] * .. * ------------------------------------------------------------------------------- * * We walk this tree from the root, breadth-first in order to process folders before * their children. We look at the valueState and structureState (for folders) to decide * whether to spit out actions into the completion ops. * * Changes recorded in the completion ops are along the lines of "copy the record with * this GUID from local into the mirror", "upload this record from local", "delete this * record". Dependencies are encoded by the sequence of completion ops: for example, we * don't want to drop local changes and update the mirror until the server reflects our * local state, and we achieve that by only running the local completion op if the * upload succeeds. * * There's a lot of boilerplate in this function. That's partly because the lines of * switch statements are easier to read through and match up to expected behavior, but * also because it's simpler than threading all of the edge cases around. */ func produceMergeResultFromMergedTree(_ mergedTree: MergedTree) -> Deferred<Maybe<BookmarksMergeResult>> { let upstreamOp = UpstreamCompletionOp() let bufferOp = BufferCompletionOp() let localOp = LocalOverrideCompletionOp() func accumulateNonRootFolder(_ node: MergedTreeNode) { assert(node.isFolder) guard let children = node.mergedChildren else { preconditionFailure("Shouldn't have a non-Unknown folder without known children.") } let childGUIDs = children.map { $0.guid } // Recurse first — because why not? // We don't expect deep enough bookmark trees that we'll overflow the stack, so // we don't bother making a queue. children.forEach(accumulateNode) // Verify that computed child lists match the right source node. switch node.structureState { case .remote: assert(node.remote?.children?.map { $0.recordGUID } ?? [] == childGUIDs) case .local: assert(node.local?.children?.map { $0.recordGUID } ?? [] == childGUIDs) case let .new(treeNode): assert(treeNode.children?.map { $0.recordGUID } ?? [] == childGUIDs) default: break } switch node.valueState { case .unknown: return // Never occurs: guarded by precondition. case .unchanged: // We can't have Unchanged value without a mirror node… assert(node.hasMirror) switch node.structureState { case .unknown: return // Never occurs: guarded by precondition. case .unchanged: // Nothing changed! return case .remote: // Nothing special to do: no need to amend server. break case .local: upstreamOp.amendChildrenFromMirror[node.guid] = childGUIDs case .new: // No change in value, but a new structure. // Construct a new upstream record from the old mirror value, // and update the mirror structure. upstreamOp.amendChildrenFromMirror[node.guid] = childGUIDs } // We always need to do this for Remote, Local, New. localOp.mirrorStructures[node.guid] = childGUIDs case .local: localOp.mirrorValuesToCopyFromLocal.insert(node.guid) // Generate a new upstream record. upstreamOp.amendChildrenFromLocal[node.guid] = childGUIDs // Update the structure in the mirror if necessary. if case .unchanged = node.structureState { return } localOp.mirrorStructures[node.guid] = childGUIDs case .remote: localOp.mirrorValuesToCopyFromBuffer.insert(node.guid) // Update the structure in the mirror if necessary. switch node.structureState { case .unchanged: return case .remote: localOp.mirrorStructures[node.guid] = childGUIDs default: // We need to upload a new record. upstreamOp.amendChildrenFromBuffer[node.guid] = childGUIDs localOp.mirrorStructures[node.guid] = childGUIDs } case let .new(value): // We can only do this if we stuffed the BookmarkMirrorItem with the right children. // Verify that with a precondition. precondition(value.children ?? [] == childGUIDs) localOp.mirrorStructures[node.guid] = childGUIDs if node.hasMirror { localOp.mirrorItemsToUpdate[node.guid] = value } else { localOp.mirrorItemsToInsert[node.guid] = value } let record = Record<BookmarkBasePayload>(id: node.guid, payload: value.asPayload()) upstreamOp.records.append(record) } } func accumulateRoot(_ node: MergedTreeNode) { log.debug("Accumulating \(node.guid).") assert(node.isFolder) assert(BookmarkRoots.Real.contains(node.guid)) guard let children = node.mergedChildren else { preconditionFailure("Shouldn't have a non-Unknown folder without known children.") } // Recurse first — because why not? children.forEach(accumulateNode) let mirrorVersionIsVirtual = self.mirror.virtual.contains(node.guid) // Note that a root can be Unchanged, but be missing from the mirror. That's OK: roots // don't really have values. Take whichever we find. if node.mirror == nil || mirrorVersionIsVirtual { if node.hasLocal { localOp.mirrorValuesToCopyFromLocal.insert(node.guid) } else if node.hasRemote { localOp.mirrorValuesToCopyFromBuffer.insert(node.guid) } else { log.warning("No values to copy into mirror for \(node.guid). Need to synthesize root. Empty merge?") } } log.debug("Need to accumulate a root.") if case .unchanged = node.structureState { if !mirrorVersionIsVirtual { log.debug("Root \(node.guid) is unchanged and already in the mirror.") return } } let childGUIDs = children.map { $0.guid } localOp.mirrorStructures[node.guid] = childGUIDs switch node.structureState { case .remote: log.debug("Root \(node.guid) taking remote structure.") return case .local: log.debug("Root \(node.guid) taking local structure.") upstreamOp.amendChildrenFromLocal[node.guid] = childGUIDs case .new: log.debug("Root \(node.guid) taking new structure.") if node.hasMirror && !mirrorVersionIsVirtual { log.debug("… uploading with mirror value.") upstreamOp.amendChildrenFromMirror[node.guid] = childGUIDs } else if node.hasLocal { log.debug("… uploading with local value.") upstreamOp.amendChildrenFromLocal[node.guid] = childGUIDs } else if node.hasRemote { log.debug("… uploading with remote value.") upstreamOp.amendChildrenFromBuffer[node.guid] = childGUIDs } else { log.warning("No values to copy to remote for \(node.guid). Need to synthesize root. Empty merge?") } default: // Filler. return } } func accumulateNode(_ node: MergedTreeNode) { precondition(!node.valueState.isUnknown) precondition(!node.isFolder || !node.structureState.isUnknown) // These two clauses are common to all: if we walk through a node, // it means it's been processed, and no longer needs to be kept // on the edges. if node.hasLocal { let localGUID = node.local!.recordGUID log.debug("Marking \(localGUID) to drop from local.") localOp.processedLocalChanges.insert(localGUID) } if node.hasRemote { log.debug("Marking \(node.guid) to drop from buffer.") bufferOp.processedBufferChanges.insert(node.guid) } if node.isFolder { if BookmarkRoots.Real.contains(node.guid) { accumulateRoot(node) return } // We have to consider structure, and we have to recurse. accumulateNonRootFolder(node) return } // Value didn't change, and no structure to handle. Done. if node.valueState.isUnchanged { precondition(node.hasMirror, "Can't have an unchanged non-root without there being a mirror record.") } // Not new. Emit copy directives. switch node.valueState { case .remote: localOp.mirrorValuesToCopyFromBuffer.insert(node.guid) case .local: let localGUID = node.local!.recordGUID // If we're taking the local value, we expect to keep the local GUID. // TODO: this restriction isn't strictly required, but we know that our // content-based merges will only ever take the remote value. precondition(localGUID == node.guid, "Can't take local value without keeping local GUID.") guard let value = self.itemSources.local.getLocalItemWithGUID(localGUID).value.successValue else { assertionFailure("Couldn't fetch local value for new item \(localGUID). This should never happen.") return } let record = Record<BookmarkBasePayload>(id: localGUID, payload: value.asPayload()) upstreamOp.records.append(record) localOp.mirrorValuesToCopyFromLocal.insert(localGUID) // New. Emit explicit insertions into all three places, // and eliminate any existing records for this GUID. // Note that we don't check structure: this isn't a folder. case let .new(value): // // TODO: ensure that `value` has the right parent GUID!!! // Reparenting means that the moved node has _new_ values // pointing to the _new_ parent. // // It also must have the correct child list. That isn't a // problem in this value-only branch. // // Upstream. let record = Record<BookmarkBasePayload>(id: node.guid, payload: value.asPayload()) upstreamOp.records.append(record) // Mirror. No structure needed. if node.hasMirror { localOp.mirrorItemsToUpdate[node.guid] = value } else { localOp.mirrorItemsToInsert[node.guid] = value } default: return // Deliberately incomplete switch. } } // Upload deleted records for anything we need to delete. // Each one also ends up being dropped from the buffer. if !mergedTree.deleteRemotely.isEmpty { upstreamOp.records.append(contentsOf: mergedTree.deleteRemotely.map { Record<BookmarkBasePayload>(id: $0, payload: BookmarkBasePayload.deletedPayload($0)) }) bufferOp.processedBufferChanges.formUnion(mergedTree.deleteRemotely) } // Drop deleted items from the mirror. localOp.mirrorItemsToDelete.formUnion(mergedTree.deleteFromMirror) // Anything we deleted on either end and accepted, add to the processed lists to be // automatically dropped. localOp.processedLocalChanges.formUnion(mergedTree.acceptLocalDeletion) bufferOp.processedBufferChanges.formUnion(mergedTree.acceptRemoteDeletion) // We draw a terminological distinction between accepting a local deletion (which // drops it from the local table) and deleting an item that's locally modified // (which drops it from the local table, and perhaps also from the mirror). // Either way, we put it in the list to drop. // The former is `localOp.processedLocalChanges`, accumulated as we walk local. // The latter is `mergedTree.deleteLocally`, accumulated as we process incoming deletions. localOp.processedLocalChanges.formUnion(mergedTree.deleteLocally) // Now walk the final tree to get the substantive changes. accumulateNode(mergedTree.root) // Postconditions. // None of the work items appear in more than one place. assert(Set(upstreamOp.amendChildrenFromBuffer.keys).isDisjoint(with: Set(upstreamOp.amendChildrenFromLocal.keys))) assert(Set(upstreamOp.amendChildrenFromBuffer.keys).isDisjoint(with: Set(upstreamOp.amendChildrenFromMirror.keys))) assert(Set(upstreamOp.amendChildrenFromLocal.keys).isDisjoint(with: Set(upstreamOp.amendChildrenFromMirror.keys))) assert(localOp.mirrorItemsToDelete.isDisjoint(with: Set(localOp.mirrorItemsToInsert.keys))) assert(localOp.mirrorItemsToDelete.isDisjoint(with: Set(localOp.mirrorItemsToUpdate.keys))) assert(Set(localOp.mirrorItemsToInsert.keys).isDisjoint(with: Set(localOp.mirrorItemsToUpdate.keys))) assert(localOp.mirrorValuesToCopyFromBuffer.isDisjoint(with: Set(localOp.mirrorValuesToCopyFromLocal))) // Pass through the item sources so we're able to apply the parts of the result that // are in reference to storage. let result = BookmarksMergeResult(uploadCompletion: upstreamOp, overrideCompletion: localOp, bufferCompletion: bufferOp, itemSources: self.itemSources) return deferMaybe(result) } }
mpl-2.0
JHStone/DYZB
DYZB/DYZB/Classes/Main/View/CollectionNormalCell.swift
1
316
// // CollectionNormalCell.swift // DYZB // // Created by gujianhua on 2017/3/31. // Copyright © 2017年 谷建华. All rights reserved. // import UIKit class CollectionNormalCell: UICollectionViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
mit
aroyarexs/PASTA
Tests/PASTATangibleTests.swift
1
15482
// // Created by Aaron Krämer on 21.08.17. // Copyright (c) 2017 Aaron Krämer. All rights reserved. // import Quick import Nimble import Metron @testable import PASTA class PASTATangibleTests: QuickSpec { override func spec() { var m1: PASTAMarker! var m2: PASTAMarker! var m3: PASTAMarker! var tangible: PASTATangible! beforeEach { m1 = PASTAMarker(center: CGPoint(x: 0, y: 10), radius: 5) m2 = PASTAMarker(center: CGPoint.zero, radius: 5) m3 = PASTAMarker(center: CGPoint(x: 10, y: 0), radius: 5) tangible = PASTATangible(markers: [m1, m2, m3]) } describe("a Tangible") { it("is active") { expect(tangible.isActive).to(beFalse()) } it("has center") { expect(tangible.center).to(equal(CGPoint(x: 5, y: 5))) } it("has markers") { expect(tangible.markers.count).to(equal(3)) } it("has radius") { expect(tangible.radius).to(beCloseTo(14.1421/2.0)) } it("has orientation") { let angle = CGVector(angle: Angle(.pi/2 * -1), magnitude: 1) .angle(between: tangible.initialOrientationVector) expect(angle.degrees).to(equal(0)) expect(tangible.orientationVector).toNot(beNil()) } it("is similar to itself") { expect(tangible ~ tangible).to(beTrue()) } it("has interior angle") { let m1UuidString = m1.markerSnapshot.uuidString let m2UuidString = m2.markerSnapshot.uuidString let m3UuidString = m3.markerSnapshot.uuidString expect(tangible.pattern.angle(atMarkerWith: m1UuidString).degrees).to(beCloseTo(45)) expect(tangible.pattern.angle(atMarkerWith: m2UuidString).degrees).to(beCloseTo(90)) expect(tangible.pattern.angle(atMarkerWith: m3UuidString).degrees).to(beCloseTo(45)) } it("markers their tangible property is set") { expect(m1.tangible).toNot(beNil()) expect(m2.tangible).toNot(beNil()) expect(m3.tangible).toNot(beNil()) } context("rotated") { it("has orientation") { let vectorBeforeRotation = tangible.orientationVector let angle = Angle(56, unit: .degrees) m1.center = LineSegment(a: tangible.center, b: m1.center).rotatedAroundA(angle).b m2.center = LineSegment(a: tangible.center, b: m2.center).rotatedAroundA(angle).b m3.center = LineSegment(a: tangible.center, b: m3.center).rotatedAroundA(angle).b let up = CGVector(angle: Angle(.pi/2 * -1), magnitude: 1) let angle1 = up.angle(between: tangible.initialOrientationVector) expect(angle1.degrees).to(beCloseTo(56)) expect(tangible.orientationVector).toNot(beNil()) guard let v = tangible.orientationVector, let v2 = vectorBeforeRotation else { fail() return } var angle2 = v.angle(between: v2) angle2 = angle2 < Angle(0) ? angle2.inversed : angle2 expect(angle2.degrees).to(beCloseTo(56)) } } context("one is moving") { var beforeRadius: CGFloat! beforeEach { beforeRadius = tangible.radius m1.center = m1.center.applying(.init(translationX: 0, y: -5)) m1.tangible?.markerMoved(m1) } it("center changes") { expect(tangible.center.y) < tangible.previousCenter.y } it("radius changes") { expect(tangible.radius) < beforeRadius } } context("one active marker") { beforeEach { m2.isActive = true } it("has two inactive") { expect(tangible.inactiveMarkers.count) == 2 } it("will replace an inactive marker") { let marker = PASTAMarker(center: CGPoint(x: 2, y: 9), radius: 5) marker.isActive = true let success = tangible.replaceInactiveMarker(with: marker) expect(success) == true expect(tangible.markers.contains(marker)) == true expect(tangible.inactiveMarkers.count) == 1 } it("won't replace inactive marker") { let marker = PASTAMarker(center: CGPoint(x: 4, y: 2.5), radius: 5) marker.isActive = true let success = tangible.replaceInactiveMarker(with: marker) expect(success) == false expect(tangible.markers.contains(marker)) == false expect(tangible.inactiveMarkers.count) == 2 } context("all marker active") { var activePattern: PASTAPattern! beforeEach { m1.isActive = true m3.isActive = true activePattern = tangible.pattern } it("has no inactive marker") { expect(tangible.inactiveMarkers.isEmpty) == true } context("m3 is inactive") { var inactivePattern: PASTAPattern! beforeEach { var touches = Set<MockTouch>() touches.insert(MockTouch(location: m3.center, radius: m3.radius)) m3.touchesEnded(touches, with: nil) inactivePattern = tangible.pattern } it("has an inactive marker") { expect(tangible.inactiveMarkers.count) == 1 } it("current and previous pattern are similar") { expect(activePattern.isSimilar(to: tangible.pattern)) == true } it("m3 marker did not moved") { expect(m3.center) == m3.previousCenter } context("m3 active again") { var secondActivePattern: PASTAPattern! beforeEach { var touches = Set<MockTouch>() touches.insert(MockTouch(location: m3.center, radius: m3.radius)) m3.touchesBegan(touches, with: nil) secondActivePattern = tangible.pattern } it("has no inactive markers") { expect(tangible.inactiveMarkers.isEmpty) == true } it("pattern similar to previous") { expect(tangible.pattern.isSimilar(to: inactivePattern)) == true } it("m3 marker did not moved") { expect(m3.center) == m3.previousCenter } context("m3 inactive again") { beforeEach { var touches = Set<MockTouch>() touches.insert(MockTouch(location: m3.center, radius: m3.radius)) m3.touchesEnded(touches, with: nil) } it("has an inactive marker") { expect(tangible.inactiveMarkers.count) == 1 } it("m3 marker did not moved") { expect(m3.center) == m3.previousCenter } it("pattern similar to previous") { expect(tangible.pattern.isSimilar(to: secondActivePattern)) == true } } } } } } context("received a marker-moved event") { var translation: CGPoint! var prevTangibleRadius: CGFloat! beforeEach { prevTangibleRadius = tangible.radius var touches = Set<MockTouch>() let angle = Angle(45, unit: .degrees) let newMarkerPosition = LineSegment(a: m2.center, b: m1.center).rotatedAroundA(angle).b translation = (newMarkerPosition - m1.center).point touches.insert(MockTouch(location: newMarkerPosition, radius: 11)) m1.touchesBegan(touches, with: nil) } it("has one active marker") { expect(tangible.inactiveMarkers.count).to(equal(2)) } it("is active") { expect(tangible.isActive).to(beTrue()) } it("active marker moved") { expect(m1.center.x).to(beCloseTo(m1.previousCenter.x + translation.x)) expect(m1.center.y).to(beCloseTo(m1.previousCenter.y + translation.y)) } it("inactive markers moved") { expect(m2.center.x).to(beCloseTo(m2.previousCenter.x + translation.x)) expect(m2.center.y).to(beCloseTo(m2.previousCenter.y + translation.y)) expect(m3.center.x).to(beCloseTo(m3.previousCenter.x + translation.x)) expect(m3.center.y).to(beCloseTo(m3.previousCenter.y + translation.y)) } it("center moved") { expect(tangible.center.x).to(beCloseTo(tangible.previousCenter.x + translation.x)) expect(tangible.center.y).to(beCloseTo(tangible.previousCenter.y + translation.y)) } it("frame updates") { expect(tangible.frame.origin).to(equal(tangible.center.applying( .init(translationX: -tangible.radius, y: -tangible.radius)))) expect(tangible.frame.width).to(equal(tangible.radius*2)) } it("radius did not changed") { expect(tangible.radius).to(beCloseTo(prevTangibleRadius)) } context("received marker-moved event from different marker") { var prevTangibleRadius2: CGFloat! beforeEach { prevTangibleRadius2 = tangible.radius var touches2 = Set<MockTouch>() let angle = Angle(45, unit: .degrees) let newMarkerPosition2 = LineSegment(a: m1.center, b: m2.center).rotatedAroundA(angle).b touches2.insert(MockTouch(location: newMarkerPosition2, radius: 11)) m2.touchesBegan(touches2, with: nil) } it("has two active markers") { expect(tangible.inactiveMarkers.count).to(equal(1)) } it("radius did not changed") { expect(tangible.radius).to(beCloseTo(prevTangibleRadius2)) } it("is active") { expect(tangible.isActive).to(beTrue()) } it("center moved") { let prevCenter = Triangle(a: m1.center, b: m2.previousCenter, c: tangible.inactiveMarkers.first!.previousCenter).cicrumcenter expect(prevCenter.x).toNot(beCloseTo(tangible.center.x, within: 0.1)) expect(prevCenter.y).toNot(beCloseTo(tangible.center.y, within: 0.1)) expect(tangible.previousCenter.x).to(beCloseTo(prevCenter.x)) expect(tangible.previousCenter.y).to(beCloseTo(prevCenter.y)) } xit("inactive marker moved") { // FIXME: update let v1 = CGVector(from: m1.center, to: m3.previousCenter) var angle = CGVector(from: m1.center, to: m3.center).angle(between: v1) angle = angle.degrees < 0 ? angle.inversed : angle expect(angle.degrees).to(beCloseTo(45)) let rotationAngle = Angle(45, unit: .degrees) let newPos = LineSegment(a: m1.center, b: m3.previousCenter).rotatedAroundA(rotationAngle).b expect(m3.center.x).to(beCloseTo(newPos.x)) expect(m3.center.y).to(beCloseTo(newPos.y)) } it("other active marker did not moved") { expect(m1.center.x).to(beCloseTo(m1.previousCenter.x + translation.x)) expect(m1.center.y).to(beCloseTo(m1.previousCenter.y + translation.y)) } it("active marker moved") { let cv = CGVector(from: m1.center, to: m2.center) let ov = CGVector(from: m1.center, to: m2.previousCenter) var angle = cv.angle(between: ov) angle = angle < Angle(0) ? angle.inversed : angle expect(angle.degrees).to(beCloseTo(45)) let rotationAngle = Angle(45, unit: .degrees) let newPos = LineSegment(a: m1.center, b: m2.previousCenter).rotatedAroundA(rotationAngle).b expect(m2.center.x).to(beCloseTo(newPos.x)) expect(m2.center.y).to(beCloseTo(newPos.x)) } } } } describe("a Tangible init with coder") { expect(PASTATangible(coder: NSCoder())).to(beNil()) } describe("a mocked Tangible") { var t: MockTangibleMarkerMovedCalled? beforeEach { t = MockTangibleMarkerMovedCalled(markers: [m1, m2, m3]) } it("is not nil") { expect(t).toNot(beNil()) } it("calls marker moved") { var touches = Set<MockTouch>() touches.insert(MockTouch(location: CGPoint(x: 5, y: -5), radius: 11)) m1.touchesMoved(touches, with: nil) guard let tangible = t else { return } expect(tangible.called).to(beTrue()) } } } } class MockTangibleMarkerMovedCalled: PASTATangible { var called = false override func markerMoved(_ marker: PASTAMarker) { called = true } }
mit
brentdax/swift
test/Sema/substring_to_string_conversion_swift4.swift
15
3765
// RUN: %target-swift-frontend -typecheck -verify -swift-version 4 %s let s = "Hello" let ss = s[s.startIndex..<s.endIndex] // CTP_Initialization do { let s1: String = { return ss }() // expected-error {{cannot convert value of type 'Substring' to specified type 'String'}} {{20-20=String(}} {{35-35=)}} _ = s1 } // CTP_ReturnStmt do { func returnsAString() -> String { return ss // expected-error {{cannot convert return expression of type 'Substring' to return type 'String'}} {{12-12=String(}} {{14-14=)}} } } // CTP_ThrowStmt // Doesn't really make sense for this fix-it - see case in diagnoseContextualConversionError: // The conversion destination of throw is always ErrorType (at the moment) // if this ever expands, this should be a specific form like () is for // return. // CTP_EnumCaseRawValue // Substrings can't be raw values because they aren't literals. // CTP_DefaultParameter do { func foo(x: String = ss) {} // expected-error {{default argument value of type 'Substring' cannot be converted to type 'String'}} {{24-24=String(}} {{26-26=)}} } // CTP_CalleeResult do { func getSubstring() -> Substring { return ss } let gottenString : String = getSubstring() // expected-error {{cannot convert value of type 'Substring' to specified type 'String'}} {{31-31=String(}} {{45-45=)}} _ = gottenString } // CTP_CallArgument do { func takesAString(_ s: String) {} takesAString(ss) // expected-error {{cannot convert value of type 'Substring' to expected argument type 'String'}} {{16-16=String(}} {{18-18=)}} } // CTP_ClosureResult do { [ss].map { (x: Substring) -> String in x } // expected-error {{cannot convert value of type 'Substring' to closure result type 'String'}} {{42-42=String(}} {{43-43=)}} } // CTP_ArrayElement do { let a: [String] = [ ss ] // expected-error {{cannot convert value of type 'Substring' to expected element type 'String'}} {{23-23=String(}} {{25-25=)}} _ = a } // CTP_DictionaryKey do { let d: [ String : String ] = [ ss : s ] // expected-error {{cannot convert value of type 'Substring' to expected dictionary key type 'String'}} {{34-34=String(}} {{36-36=)}} _ = d } // CTP_DictionaryValue do { let d: [ String : String ] = [ s : ss ] // expected-error {{cannot convert value of type 'Substring' to expected dictionary value type 'String'}} {{38-38=String(}} {{40-40=)}} _ = d } // CTP_CoerceOperand do { let s1: String = ss as String // expected-error {{cannot convert value of type 'Substring' to type 'String' in coercion}} {{20-20=String(}} {{22-22=)}} _ = s1 } // CTP_AssignSource do { let s1: String = ss // expected-error {{cannot convert value of type 'Substring' to specified type 'String'}} {{20-20=String(}} {{22-22=)}} _ = s1 } // Substring-to-String via subscripting in a context expecting String func takesString(_ s: String) {} func apply(_ fn: (String) -> (), _ s: String) { fn(s[s.startIndex..<s.endIndex]) // expected-error{{subscripts returning String were obsoleted in Swift 4; explicitly construct a String from subscripted result}} {{6-6=String(}} {{34-34=)}} let _: String = s[s.startIndex..<s.endIndex] // expected-error{{subscripts returning String were obsoleted in Swift 4; explicitly construct a String from subscripted result}} {{19-19=String(}} {{47-47=)}} _ = s[s.startIndex..<s.endIndex] as String // expected-error{{subscripts returning String were obsoleted in Swift 4; explicitly construct a String from subscripted result}} {{7-7=String(}} {{35-35=)}} } // rdar://33474838 protocol Derivable { func derive() -> Substring } func foo<T: Derivable>(t: T) -> String { return t.derive() // expected-error {{cannot convert return expression of type 'Substring' to return type 'String'}} {{10-10=String(}} {{20-20=)}} }
apache-2.0
tardieu/swift
benchmark/single-source/AnyHashableWithAClass.swift
21
1371
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 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 // //===----------------------------------------------------------------------===// // This benchmark tests AnyHashable's initializer that needs to dynamically // upcast the instance to the type that introduces the Hashable // conformance. class TestHashableBase : Hashable { var value: Int init(_ value: Int) { self.value = value } var hashValue: Int { return value } static func == ( lhs: TestHashableBase, rhs: TestHashableBase ) -> Bool { return lhs.value == rhs.value } } class TestHashableDerived1 : TestHashableBase {} class TestHashableDerived2 : TestHashableDerived1 {} class TestHashableDerived3 : TestHashableDerived2 {} class TestHashableDerived4 : TestHashableDerived3 {} class TestHashableDerived5 : TestHashableDerived4 {} @inline(never) public func run_AnyHashableWithAClass(_ N: Int) { let c = TestHashableDerived5(10) for _ in 0...(N*500000) { _ = AnyHashable(c) } }
apache-2.0
kmikiy/SpotMenu
MusicPlayer/Manager/MusicPlayerManager.swift
1
5358
// // MusicPlayerManager.swift // MusicPlayer // // Created by Michael Row on 2017/9/3. // import Foundation public class MusicPlayerManager { public weak var delegate: MusicPlayerManagerDelegate? public fileprivate(set) var musicPlayers = [MusicPlayer]() public weak var currentPlayer: MusicPlayer? public init() {} } // MARK: - Public Manager Methods public extension MusicPlayerManager { /// The player names that added to the manager. public var allPlayerNames: [MusicPlayerName] { var playerNames = [MusicPlayerName]() for player in musicPlayers { playerNames.append(player.name) } return playerNames } /// Return the player with selected name if exists. public func existMusicPlayer(with name: MusicPlayerName) -> MusicPlayer? { for player in musicPlayers { if player.name == name { return player } } return nil } /// Add a music player to the manager. /// /// - Parameter name: The name of the music player you wanna add. public func add(musicPlayer name: MusicPlayerName) { for player in musicPlayers { guard player.name != name else { return } } guard let player = MusicPlayerFactory.musicPlayer(name: name) else { return } player.delegate = self player.startPlayerTracking() musicPlayers.append(player) selectMusicPlayer(with: player) } /// Add music players to the manager. /// /// - Parameter names: The names of the music player you wanna add. public func add(musicPlayers names: [MusicPlayerName]) { for name in names { add(musicPlayer: name) } } /// Remove a music player from the manager. /// /// - Parameter name: The name of the music player you wanna remove. public func remove(musicPlayer name: MusicPlayerName) { for index in 0 ..< musicPlayers.count { let player = musicPlayers[index] guard player.name == name else { continue } player.stopPlayerTracking() musicPlayers.remove(at: index) // if the removal is the current player, we should select a new one. if currentPlayer?.name == player.name { currentPlayer = nil selectMusicPlayerFromList() } return } } /// Remove music players from the manager. /// /// - Parameter names: The names of the music player you wanna remove. public func remove(musicPlayers names: [MusicPlayerName]) { for name in names { remove(musicPlayer: name) } } /// Remove all music players from the manager. public func removeAllMusicPlayers() { for player in musicPlayers { player.stopPlayerTracking() } musicPlayers.removeAll() currentPlayer = nil } } // MARK: - MusicPlayerDelegate extension MusicPlayerManager: MusicPlayerDelegate { public func player(_ player: MusicPlayer, didChangeTrack track: MusicTrack, atPosition position: TimeInterval) { selectMusicPlayer(with: player) guard currentPlayer?.name == player.name else { return } delegate?.manager(self, trackingPlayer: player, didChangeTrack: track, atPosition: position) } public func player(_ player: MusicPlayer, playbackStateChanged playbackState: MusicPlaybackState, atPosition postion: TimeInterval) { selectMusicPlayer(with: player) guard currentPlayer?.name == player.name else { return } delegate?.manager(self, trackingPlayer: player, playbackStateChanged: playbackState, atPosition: postion) if !playbackState.isActiveState { selectMusicPlayerFromList() } } public func playerDidQuit(_ player: MusicPlayer) { guard currentPlayer != nil, currentPlayer!.name == player.name else { return } currentPlayer = nil delegate?.manager(self, trackingPlayerDidQuit: player) selectMusicPlayerFromList() } fileprivate func selectMusicPlayerFromList() { for player in musicPlayers { selectMusicPlayer(with: player) if let playerState = currentPlayer?.playbackState, playerState.isActiveState { return } } } fileprivate func selectMusicPlayer(with player: MusicPlayer) { guard shouldChangePlayer(with: player) else { return } currentPlayer = player delegate?.manager(self, trackingPlayerDidChange: player) } fileprivate func shouldChangePlayer(with player: MusicPlayer) -> Bool { // check wheter the new player and current one are the same player. guard currentPlayer !== player else { return false } // check the new player's playback state guard player.playbackState.isActiveState else { return false } // check current player's playback state guard let playbackState = currentPlayer?.playbackState else { return true } if playbackState.isActiveState { return false } else { return true } } }
mit
kunsy/DYZB
DYZB/DYZB/Classes/Home/ViewModel/AmuseViewModel.swift
1
451
// // AmuseViewModel.swift // DYZB // // Created by Anyuting on 2017/9/3. // Copyright © 2017年 Anyuting. All rights reserved. // import UIKit class AmuseViewModel : BaseViewModel { } //请求数据 extension AmuseViewModel { func loadAmuseData(finishedCallback : @escaping () -> ()) { loadAnchorData(isGroupData: true, URLString: "http://capi.douyucdn.cn/api/v1/getHotRoom/2", finishedCallback: finishedCallback) } }
mit
xmartlabs/Bender
Sources/Graph/Graph.swift
1
745
// // Graph.swift // Bender // // Created by Mathias Claassen on 5/17/17. // // /// Protocol implemented by any Graph public protocol GraphProtocol { associatedtype T: Node var nodes: [T] { get set } } public extension GraphProtocol { /// Removes nodes that have no adjacencies mutating func removeLonely() { nodes = nodes.filter { !$0.isLonely } } /// Sort nodes by dependencies mutating func sortNodes() { let inputs: [T] = nodes.filter { $0.incomingNodes().isEmpty } let sorted = DependencyListBuilder().list(from: inputs) assert(nodes.count == sorted.count, "Seems you might have a cyclic dependency in your graph. That is not supported!") nodes = sorted } }
mit
twtstudio/WePeiYang-iOS
WePeiYang/PartyService/View/ScoreTableViewCell.swift
1
1971
// // ScoreTableViewCell.swift // WePeiYang // // Created by JinHongxu on 16/8/15. // Copyright © 2016年 Qin Yubo. All rights reserved. // import Foundation import UIKit //import SnapKit class ScoreTableViewCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } convenience init(title: String, score: String, completeTime: String) { self.init() let titleLabel = UILabel(text: title) let timeLabel = UILabel(text: completeTime) let scoreLabel = UILabel(text: score) titleLabel.font = UIFont.boldSystemFontOfSize(12.0) titleLabel.textColor = UIColor.lightGrayColor() scoreLabel.font = UIFont.boldSystemFontOfSize(12.0) scoreLabel.textColor = UIColor.redColor() timeLabel.font = UIFont.boldSystemFontOfSize(10.0) timeLabel.textColor = UIColor.lightGrayColor() contentView.addSubview(titleLabel) contentView.addSubview(timeLabel) contentView.addSubview(scoreLabel) timeLabel.snp_makeConstraints { make in make.right.equalTo(contentView).offset(-8) make.centerY.equalTo(contentView) } scoreLabel.snp_makeConstraints { make in make.right.equalTo(timeLabel.snp_left).offset(-8) make.centerY.equalTo(contentView) } titleLabel.snp_makeConstraints { make in make.left.equalTo(contentView).offset(8) make.centerY.equalTo(contentView) make.right.lessThanOrEqualTo(scoreLabel.snp_left).offset(-8) } } }
mit
migueloruiz/la-gas-app-swift
lasgasmx/UINavigationItem+Helper.swift
1
1845
// // UINavigationItem+Helper.swift // lasgasmx // // Created by Desarrollo on 4/6/17. // Copyright © 2017 migueloruiz. All rights reserved. // import UIKit extension UINavigationItem { func set(title:String, subtitle:String) { let titleLabel = UILabel() titleLabel.backgroundColor = .clear titleLabel.textColor = .white titleLabel.font = UIFont.boldSystemFont(ofSize: 14) titleLabel.text = title titleLabel.textAlignment = .center titleLabel.sizeToFit() let subtitleLabel = UILabel() subtitleLabel.backgroundColor = .clear subtitleLabel.textColor = .white subtitleLabel.font = UIFont.systemFont(ofSize: 12) subtitleLabel.text = subtitle subtitleLabel.textAlignment = .center subtitleLabel.sizeToFit() let titleView = UIView(frame: CGRect(x: 0, y: 0, width: max(titleLabel.frame.size.width, subtitleLabel.frame.size.width), height: 30)) titleView.addSubview(titleLabel) titleView.addSubview(subtitleLabel) titleLabel.anchor(top: titleView.topAnchor, left: titleView.leftAnchor, bottom: subtitleLabel.topAnchor, right: titleView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0 ) subtitleLabel.anchor(top: titleLabel.bottomAnchor, left: titleView.leftAnchor, bottom: titleView.bottomAnchor, right: titleView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0 ) self.titleView = titleView } } extension UINavigationBar { func hiddeShadow() { self.setBackgroundImage(UIImage(), for: .default) self.shadowImage = UIImage() } }
mit
OscarSwanros/swift
test/stdlib/StringDescribing.swift
3
674
// RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest private class Foo {} class Bar {} var StringDescribingTestSuite = TestSuite("StringDescribing") StringDescribingTestSuite.test("String(describing:) shouldn't include extra stuff if the class is private") { expectEqual(String(describing: Foo.self), "Foo") expectEqual(String(describing: Bar.self), "Bar") } StringDescribingTestSuite.test("String(reflecting:) should include extra stuff if the class is private") { expectEqual(String(reflecting: Bar.self), "main.Bar") expectEqual(String(reflecting: Foo.self), "main.(Foo in _AE29BC3E71CF180B9604AA0071CCE6E8)") } runAllTests()
apache-2.0
vadymmarkov/Faker
Sources/Fakery/Generators/Zelda.swift
3
141
extension Faker { public final class Zelda: Generator { public func game() -> String { return generate("zelda.game") } } }
mit
byu-oit/ios-byuSuite
byuSuite/Apps/Printers/controller/PrintersTabBarViewController.swift
1
1919
// // PrintersTabBarViewController.swift // byuSuite // // Created by Alex Boswell on 8/24/18. // Copyright © 2018 Brigham Young University. All rights reserved. // import UIKit class PrintersTabBarViewController: ByuTabBarViewController { var printerBuildings: [PrintersBuilding]? var printers: [Printer]? override func viewDidLoad() { super.viewDidLoad() loadData() } private func loadData() { if let vcs = self.viewControllers, let buildingsVC = vcs[0] as? PrintersBuildingsViewController, let mapVC = vcs[1] as? PrintersMapViewController { buildingsVC.spinner?.startAnimating() PrintersClient.getAllBuildingsWithCurrentFilter { (printerBuildings, error) in buildingsVC.spinner?.stopAnimating() if let printerBuildings = printerBuildings { self.printerBuildings = printerBuildings buildingsVC.updatePrinterBuildings(printerBuildings) } else { super.displayAlert(error: error) } } mapVC.spinner?.startAnimating() PrintersClient.getAllPrintersWithCurrentFilter(buildingCode: nil) { (printers, error) in mapVC.spinner?.stopAnimating() if let printers = printers { self.printers = printers mapVC.updatePrinters(printers) } else { super.displayAlert(error: error) } } } else { super.displayAlert() } } @IBAction func unwindFromFilterVC(_ sender: UIStoryboardSegue) { if let filterVC = sender.source as? PrintersFilterViewController { if filterVC.filtersChanged { loadData() } } } }
apache-2.0
lorentey/swift
validation-test/stdlib/Collection/DefaultedMutableRangeReplaceableCollection.swift
32
2177
// -*- swift -*- //===----------------------------------------------------------------------===// // Automatically Generated From validation-test/stdlib/Collection/Inputs/Template.swift.gyb // Do Not Edit Directly! //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // FIXME: the test is too slow when the standard library is not optimized. // rdar://problem/46878013 // REQUIRES: optimized_stdlib import StdlibUnittest import StdlibCollectionUnittest var CollectionTests = TestSuite("Collection") // Test collections using value types as elements. do { var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap CollectionTests.addRangeReplaceableCollectionTests( makeCollection: { (elements: [OpaqueValue<Int>]) in return DefaultedMutableRangeReplaceableCollection(elements: elements) }, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in return DefaultedMutableRangeReplaceableCollection(elements: elements) }, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, resiliencyChecks: resiliencyChecks ) CollectionTests.addMutableCollectionTests( makeCollection: { (elements: [OpaqueValue<Int>]) in return DefaultedMutableRangeReplaceableCollection(elements: elements) }, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in return DefaultedMutableRangeReplaceableCollection(elements: elements) }, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, makeCollectionOfComparable: { (elements: [MinimalComparableValue]) in return DefaultedMutableRangeReplaceableCollection(elements: elements) }, wrapValueIntoComparable: identityComp, extractValueFromComparable: identityComp, resiliencyChecks: resiliencyChecks , withUnsafeMutableBufferPointerIsSupported: false, isFixedLengthCollection: true ) } runAllTests()
apache-2.0
TellMeAMovieTeam/TellMeAMovie_iOSApp
TellMeAMovie/Pods/TMDBSwift/Sources/Models/MovieReleaseDatesMDB.swift
1
1021
// // MovieReleaseDatesMDB.swift // MDBSwiftWrapper // // Created by George Kye on 2016-03-08. // Copyright © 2016 George KyeKye. All rights reserved. // import Foundation open class MovieReleaseDatesMDB: ArrayObject{ open var iso_3166_1: String? open var release_dates = [Release_Dates]() required public init(results: JSON){ iso_3166_1 = results["iso_3166_1"].string release_dates = Release_Dates.initialize(json: results["release_dates"]) } } //move inside class? public struct Release_Dates: ArrayObject{ public var certification: String? public var iso_639_1: String? public var note: String? public var release_date: String? //change to formatted NSDate later?? public var type: Int? public init(results release_date: JSON){ certification = release_date["certification"].string iso_639_1 = release_date["iso_639_1"].string note = release_date["note"].string self.release_date = release_date["release_date"].string type = release_date["type"].int } }
apache-2.0
apple/swift-nio
Tests/NIOCoreTests/IntegerTypesTest.swift
1
4345
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import XCTest @testable import NIOCore public final class IntegerTypesTest: XCTestCase { func testNextPowerOfOfTwoZero() { XCTAssertEqual(1, (0 as UInt).nextPowerOf2()) XCTAssertEqual(1, (0 as UInt16).nextPowerOf2()) XCTAssertEqual(1, (0 as UInt32).nextPowerOf2()) XCTAssertEqual(1, (0 as UInt64).nextPowerOf2()) XCTAssertEqual(1, (0 as Int).nextPowerOf2()) XCTAssertEqual(1, (0 as Int16).nextPowerOf2()) XCTAssertEqual(1, (0 as Int32).nextPowerOf2()) XCTAssertEqual(1, (0 as Int64).nextPowerOf2()) } func testNextPowerOfTwoOfOne() { XCTAssertEqual(1, (1 as UInt).nextPowerOf2()) XCTAssertEqual(1, (1 as UInt16).nextPowerOf2()) XCTAssertEqual(1, (1 as UInt32).nextPowerOf2()) XCTAssertEqual(1, (1 as UInt64).nextPowerOf2()) XCTAssertEqual(1, (1 as Int).nextPowerOf2()) XCTAssertEqual(1, (1 as Int16).nextPowerOf2()) XCTAssertEqual(1, (1 as Int32).nextPowerOf2()) XCTAssertEqual(1, (1 as Int64).nextPowerOf2()) } func testNextPowerOfTwoOfTwo() { XCTAssertEqual(2, (2 as UInt).nextPowerOf2()) XCTAssertEqual(2, (2 as UInt16).nextPowerOf2()) XCTAssertEqual(2, (2 as UInt32).nextPowerOf2()) XCTAssertEqual(2, (2 as UInt64).nextPowerOf2()) XCTAssertEqual(2, (2 as Int).nextPowerOf2()) XCTAssertEqual(2, (2 as Int16).nextPowerOf2()) XCTAssertEqual(2, (2 as Int32).nextPowerOf2()) XCTAssertEqual(2, (2 as Int64).nextPowerOf2()) } func testNextPowerOfTwoOfThree() { XCTAssertEqual(4, (3 as UInt).nextPowerOf2()) XCTAssertEqual(4, (3 as UInt16).nextPowerOf2()) XCTAssertEqual(4, (3 as UInt32).nextPowerOf2()) XCTAssertEqual(4, (3 as UInt64).nextPowerOf2()) XCTAssertEqual(4, (3 as Int).nextPowerOf2()) XCTAssertEqual(4, (3 as Int16).nextPowerOf2()) XCTAssertEqual(4, (3 as Int32).nextPowerOf2()) XCTAssertEqual(4, (3 as Int64).nextPowerOf2()) } func testNextPowerOfTwoOfFour() { XCTAssertEqual(4, (4 as UInt).nextPowerOf2()) XCTAssertEqual(4, (4 as UInt16).nextPowerOf2()) XCTAssertEqual(4, (4 as UInt32).nextPowerOf2()) XCTAssertEqual(4, (4 as UInt64).nextPowerOf2()) XCTAssertEqual(4, (4 as Int).nextPowerOf2()) XCTAssertEqual(4, (4 as Int16).nextPowerOf2()) XCTAssertEqual(4, (4 as Int32).nextPowerOf2()) XCTAssertEqual(4, (4 as Int64).nextPowerOf2()) } func testNextPowerOfTwoOfFive() { XCTAssertEqual(8, (5 as UInt).nextPowerOf2()) XCTAssertEqual(8, (5 as UInt16).nextPowerOf2()) XCTAssertEqual(8, (5 as UInt32).nextPowerOf2()) XCTAssertEqual(8, (5 as UInt64).nextPowerOf2()) XCTAssertEqual(8, (5 as Int).nextPowerOf2()) XCTAssertEqual(8, (5 as Int16).nextPowerOf2()) XCTAssertEqual(8, (5 as Int32).nextPowerOf2()) XCTAssertEqual(8, (5 as Int64).nextPowerOf2()) } func testDescriptionUInt24() { XCTAssertEqual("0", _UInt24.min.description) XCTAssertEqual("16777215", _UInt24.max.description) XCTAssertEqual("12345678", _UInt24(12345678 as UInt32).description) XCTAssertEqual("1", _UInt24(1).description) XCTAssertEqual("8388608", _UInt24(1 << 23).description) XCTAssertEqual("66", _UInt24(66).description) } func testDescriptionUInt56() { XCTAssertEqual("0", _UInt56.min.description) XCTAssertEqual("72057594037927935", _UInt56.max.description) XCTAssertEqual("12345678901234567", _UInt56(12345678901234567 as UInt64).description) XCTAssertEqual("1", _UInt56(1).description) XCTAssertEqual("66", _UInt56(66).description) XCTAssertEqual("36028797018963968", _UInt56(UInt64(1) << 55).description) } }
apache-2.0
rene-dohan/CS-IOS
Renetik/Renetik/Classes/Core/Task/CSDoLaterOnce.swift
1
500
// // Created by Rene Dohan on 1/1/21. // import Foundation public class CSDoLaterOnce { let delay: TimeInterval, function: Func var willInvoke = false public init(delay: TimeInterval = 0, _ function: @escaping Func) { self.delay = delay; self.function = function } public func start() { if willInvoke { return } willInvoke = true later(seconds: delay) { [unowned self] in function() willInvoke = false } } }
mit
zakkhoyt/ColorPicKit
ColorPicKitExample/HSBWheelBrightnessViewController.swift
1
1873
// // HSBWheelBrightnessViewController.swift // ColorPicKitExample // // Created by Zakk Hoyt on 10/8/16. // Copyright © 2016 Zakk Hoyt. All rights reserved. // import UIKit class HSBWheelBrightnessViewController: BaseViewController { @IBOutlet weak var hsbWheel: HSBWheel! @IBOutlet weak var brightnessSlider: GradientSlider! // MARK: colorWheel actions @IBAction func colorWheelValueChanged(_ sender: HSBWheel) { updateBackgroundColor() updateBrightnessSlider() } @IBAction func colorWheelTouchDown(_ sender: HSBWheel) { updateBackgroundColor() updateBrightnessSlider() } @IBAction func colorWheelTouchUpInside(_ sender: HSBWheel) { updateBackgroundColor() updateBrightnessSlider() } // MARK: brightnessSlider actions @IBAction func brightnessSliderTouchDown(_ sender: GradientSlider) { updateBackgroundColor() } @IBAction func brightnessSliderTouchUpInside(_ sender: GradientSlider) { updateBackgroundColor() } @IBAction func brightnessSliderValueChanged(_ sender: GradientSlider) { updateBackgroundColor() } private func updateBrightnessSlider() { let hsba = hsbWheel.color.hsba() let color = UIColor(hue: hsba.hue, saturation: 1.0, brightness: 1.0, alpha: 1.0) brightnessSlider.color2 = color } private func updateBackgroundColor() { let brightness = brightnessSlider.value hsbWheel.brightness = brightness colorView.backgroundColor = hsbWheel.color } override func reset() { hsbWheel.position = CGPoint(x: hsbWheel.bounds.midX, y: hsbWheel.bounds.midY) brightnessSlider.value = resetValue updateBackgroundColor() updateBrightnessSlider() } }
mit
editfmah/AeonAPI
Sources/Mutex.swift
1
572
// // Mutex.swift // scale // // Created by Adrian Herridge on 06/02/2017. // // import Foundation import Dispatch import SWSQLite class Mutex { private var thread: Thread? = nil; private var lock: DispatchQueue init() { lock = DispatchQueue(label: uuid()) } func mutex(_ closure: ()->()) { if thread != Thread.current { lock.sync { thread = Thread.current closure() thread = nil } } else { closure() } } }
mit
skonb/YapDatabaseExtensions
framework/Pods/PromiseKit/Sources/Promise.swift
4
15079
import Foundation.NSError public let PMKOperationQueue = NSOperationQueue() public enum CatchPolicy { case AllErrors case AllErrorsExceptCancellation } /** A promise represents the future value of a task. To obtain the value of a promise we call `then`. Promises are chainable: `then` returns a promise, you can call `then` on that promise, which returns a promise, you can call `then` on that promise, et cetera. 0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2 Promises start in a pending state and *resolve* with a value to become *fulfilled* or with an `NSError` to become rejected. @see [PromiseKit `then` Guide](http://promisekit.org/then/) @see [PromiseKit Chaining Guide](http://promisekit.org/chaining/) */ public class Promise<T> { let state: State /** Create a new pending promise. Use this method when wrapping asynchronous systems that do *not* use promises so that they can be involved in promise chains. Don’t use this method if you already have promises! Instead, just return your promise! The closure you pass is executed immediately on the calling thread. func fetchKitten() -> Promise<UIImage> { return Promise { fulfill, reject in KittenFetcher.fetchWithCompletionBlock({ img, err in if err == nil { fulfill(img) } else { reject(err) } }) } } @param resolvers The provided closure is called immediately. Inside, execute your asynchronous system, calling fulfill if it suceeds and reject for any errors. @return A new promise. @warning *Note* If you are wrapping a delegate-based system, we recommend to use instead: defer @see http://promisekit.org/sealing-your-own-promises/ @see http://promisekit.org/wrapping-delegation/ */ public convenience init(@noescape resolvers: (fulfill: (T) -> Void, reject: (NSError) -> Void) -> Void) { self.init(sealant: { sealant in resolvers(fulfill: sealant.resolve, reject: sealant.resolve) }) } /** Create a new pending promise. This initializer is convenient when wrapping asynchronous systems that use common patterns. For example: func fetchKitten() -> Promise<UIImage> { return Promise { sealant in KittenFetcher.fetchWithCompletionBlock(sealant.resolve) } } @see Sealant @see init(resolvers:) */ public init(@noescape sealant: (Sealant<T>) -> Void) { var resolve: ((Resolution) -> Void)! state = UnsealedState(resolver: &resolve) sealant(Sealant(body: resolve)) } /** Create a new fulfilled promise. */ public init(_ value: T) { state = SealedState(resolution: .Fulfilled(value)) } /** Create a new rejected promise. */ public init(_ error: NSError) { unconsume(error) state = SealedState(resolution: .Rejected(error)) } /** I’d prefer this to be the designated initializer, but then there would be no public designated unsealed initializer! Making this convenience would be inefficient. Not very inefficient, but still it seems distasteful to me. */ init(passthru: ((Resolution) -> Void) -> Void) { var resolve: ((Resolution) -> Void)! state = UnsealedState(resolver: &resolve) passthru(resolve) } /** defer is convenient for wrapping delegates or larger asynchronous systems. class Foo: BarDelegate { let (promise, fulfill, reject) = Promise<Int>.defer() func barDidFinishWithResult(result: Int) { fulfill(result) } func barDidError(error: NSError) { reject(error) } } @return A tuple consisting of: 1) A promise 2) A function that fulfills that promise 3) A function that rejects that promise */ public class func defer() -> (promise: Promise, fulfill: (T) -> Void, reject: (NSError) -> Void) { var sealant: Sealant<T>! let promise = Promise { sealant = $0 } return (promise, sealant.resolve, sealant.resolve) } func pipe(body: (Resolution) -> Void) { state.get { seal in switch seal { case .Pending(let handlers): handlers.append(body) case .Resolved(let resolution): body(resolution) } } } private convenience init<U>(when: Promise<U>, body: (Resolution, (Resolution) -> Void) -> Void) { self.init(passthru: { resolve in when.pipe{ body($0, resolve) } }) } /** The provided block is executed when this Promise is resolved. If you provide a block that takes a parameter, the value of the receiver will be passed as that parameter. @param on The queue on which body should be executed. @param body The closure that is executed when this Promise is fulfilled. [NSURLConnection GET:url].then(^(NSData *data){ // do something with data }); @return A new promise that is resolved with the value returned from the provided closure. For example: [NSURLConnection GET:url].then(^(NSData *data){ return data.length; }).then(^(NSNumber *number){ //… }); @see thenInBackground */ public func then<U>(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) -> U) -> Promise<U> { return Promise<U>(when: self) { resolution, resolve in switch resolution { case .Rejected: resolve(resolution) case .Fulfilled(let value): contain_zalgo(q) { resolve(.Fulfilled(body(value as! T))) } } } } public func then<U>(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) -> Promise<U>) -> Promise<U> { return Promise<U>(when: self) { resolution, resolve in switch resolution { case .Rejected: resolve(resolution) case .Fulfilled(let value): contain_zalgo(q) { body(value as! T).pipe(resolve) } } } } public func then(on q: dispatch_queue_t = dispatch_get_main_queue(), body: (T) -> AnyPromise) -> Promise<AnyObject?> { return Promise<AnyObject?>(when: self) { resolution, resolve in switch resolution { case .Rejected: resolve(resolution) case .Fulfilled(let value): contain_zalgo(q) { let anypromise = body(value as! T) anypromise.pipe { obj in if let error = obj as? NSError { resolve(.Rejected(error)) } else { // possibly the value of this promise is a PMKManifold, if so // calling the objc `value` method will return the first item. let obj: AnyObject? = anypromise.valueForKey("value") resolve(.Fulfilled(obj)) } } } } } } /** The provided closure is executed on the default background queue when this Promise is fulfilled. This method is provided as a convenience for `then`. @see then */ public func thenInBackground<U>(body: (T) -> U) -> Promise<U> { return then(on: dispatch_get_global_queue(0, 0), body) } public func thenInBackground<U>(body: (T) -> Promise<U>) -> Promise<U> { return then(on: dispatch_get_global_queue(0, 0), body) } /** The provided closure is executed when this Promise is rejected. Rejecting a promise cascades: rejecting all subsequent promises (unless recover is invoked) thus you will typically place your catch at the end of a chain. Often utility promises will not have a catch, instead delegating the error handling to the caller. The provided closure always runs on the main queue. @param policy The default policy does not execute your handler for cancellation errors. See registerCancellationError for more documentation. @param body The handler to execute when this Promise is rejected. @see registerCancellationError */ public func catch(policy: CatchPolicy = .AllErrorsExceptCancellation, _ body: (NSError) -> Void) { pipe { resolution in switch resolution { case .Fulfilled: break case .Rejected(let error): if policy == .AllErrors || !error.cancelled { dispatch_async(dispatch_get_main_queue()) { consume(error) body(error) } } } } } /** The provided closure is executed when this Promise is rejected giving you an opportunity to recover from the error and continue the promise chain. */ public func recover(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (NSError) -> Promise<T>) -> Promise<T> { return Promise(when: self) { resolution, resolve in switch resolution { case .Rejected(let error): contain_zalgo(q) { consume(error) body(error).pipe(resolve) } case .Fulfilled: resolve(resolution) } } } /** The provided closure is executed when this Promise is resolved. @param on The queue on which body should be executed. @param body The closure that is executed when this Promise is resolved. UIApplication.sharedApplication().networkActivityIndicatorVisible = true somePromise().then { //… }.finally { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } */ public func finally(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: () -> Void) -> Promise<T> { return Promise(when: self) { resolution, resolve in contain_zalgo(q) { body() resolve(resolution) } } } /** @return The value with which this promise was fulfilled or nil if this promise is not fulfilled. */ public var value: T? { switch state.get() { case .None: return nil case .Some(.Fulfilled(let value)): return (value as! T) case .Some(.Rejected): return nil } } } /** Zalgo is dangerous. Pass as the `on` parameter for a `then`. Causes the handler to be executed as soon as it is resolved. That means it will be executed on the queue it is resolved. This means you cannot predict the queue. In the case that the promise is already resolved the handler will be executed immediately. zalgo is provided for libraries providing promises that have good tests that prove unleashing zalgo is safe. You can also use it in your application code in situations where performance is critical, but be careful: read the essay at the provided link to understand the risks. @see http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony */ public let zalgo: dispatch_queue_t = dispatch_queue_create("Zalgo", nil) /** Waldo is dangerous. Waldo is zalgo, unless the current queue is the main thread, in which case we dispatch to the default background queue. If your block is likely to take more than a few milliseconds to execute, then you should use waldo: 60fps means the main thread cannot hang longer than 17 milliseconds. Don’t contribute to UI lag. Conversely if your then block is trivial, use zalgo: GCD is not free and for whatever reason you may already be on the main thread so just do what you are doing quickly and pass on execution. It is considered good practice for asynchronous APIs to complete onto the main thread. Apple do not always honor this, nor do other developers. However, they *should*. In that respect waldo is a good choice if your then is going to take a while and doesn’t interact with the UI. Please note (again) that generally you should not use zalgo or waldo. The performance gains are neglible and we provide these functions only out of a misguided sense that library code should be as optimized as possible. If you use zalgo or waldo without tests proving their correctness you may unwillingly introduce horrendous, near-impossible-to-trace bugs. @see zalgo */ public let waldo: dispatch_queue_t = dispatch_queue_create("Waldo", nil) func contain_zalgo(q: dispatch_queue_t, block: () -> Void) { if q === zalgo { block() } else if q === waldo { if NSThread.isMainThread() { dispatch_async(dispatch_get_global_queue(0, 0), block) } else { block() } } else { dispatch_async(q, block) } } extension Promise { /** Creates a rejected Promise with `PMKErrorDomain` and a specified localizedDescription and error code. */ public convenience init(error: String, code: Int = PMKUnexpectedError) { let error = NSError(domain: "PMKErrorDomain", code: code, userInfo: [NSLocalizedDescriptionKey: error]) self.init(error) } /** Promise<Any> is more flexible, and often needed. However Swift won't cast <T> to <Any> directly. Once that is possible we will deprecate this function. */ public func asAny() -> Promise<Any> { return Promise<Any>(passthru: pipe) } /** Promise<AnyObject> is more flexible, and often needed. However Swift won't cast <T> to <AnyObject> directly. Once that is possible we will deprecate this function. */ public func asAnyObject() -> Promise<AnyObject> { return Promise<AnyObject>(passthru: pipe) } /** Swift (1.2) seems to be much less fussy about Void promises. */ public func asVoid() -> Promise<Void> { return then(on: zalgo) { _ in return } } } extension Promise: DebugPrintable { public var debugDescription: String { return "Promise: \(state)" } } /** Firstly can make chains more readable. Compare: NSURLConnection.GET(url1).then { NSURLConnection.GET(url2) }.then { NSURLConnection.GET(url3) } With: firstly { NSURLConnection.GET(url1) }.then { NSURLConnection.GET(url2) }.then { NSURLConnection.GET(url3) } */ public func firstly<T>(promise: () -> Promise<T>) -> Promise<T> { return promise() }
mit
gspd-mobi/rage-ios
RageExample/GithubEntities.swift
1
937
import Foundation struct GithubOrganization: Codable { var id: Int64? var name: String? var location: String? var blog: String? } struct GithubRepository: Codable { var id: Int64? var name: String? var fullName: String? var url: String? var stars: Int? enum CodingKeys: String, CodingKey { case id case name case fullName = "full_name" case url case stars = "stargazers_count" } } struct GithubUser: Codable { var id: Int64? var login: String? var avatarUrl: String? var htmlUrl: String? var name: String? var email: String? var location: String? enum CodingKeys: String, CodingKey { case id case login case avatarUrl = "avatar_url" case htmlUrl = "html_url" case name case email case location } } struct GithubError: Codable { var message: String? }
mit
nathan-hekman/Stupefy
Stupefy/MainViewController.swift
1
5378
// // MainViewController.swift // Stupefy // // Created by Nathan Hekman on 10/22/16. // Copyright © 2016 NTH. All rights reserved. // import UIKit class MainViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var launchScreenView: UIView! var isEditingPhoto = false var originalImage: UIImage? var zoomedImage: UIImage? override var prefersStatusBarHidden: Bool { return true } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !isEditingPhoto { self.showCamera() } } func showCamera() { let croppingEnabled = false let cameraViewController = CameraViewController(croppingEnabled: croppingEnabled) { [weak self] zoomedImage,originalImage, asset in // Do something with your image here. // If cropping is enabled this image will be the cropped version self?.imageView.image = zoomedImage self?.originalImage = originalImage //self?.zoomedImage = zoomedImage self?.zoomedImage = self?.cropToBounds(image: zoomedImage!, width: Double(self!.view.frame.width), height: Double(self!.view.frame.height)) //compute stupefy zoom with originalImage self?.isEditingPhoto = true self?.dismiss(animated: false, completion: nil) } cameraViewController.closeButton.isHidden = true present(cameraViewController, animated: false, completion: {_ in self.launchScreenView.isHidden = true }) } func cropToBounds(image: UIImage, width: Double, height: Double) -> UIImage { let contextImage: UIImage = UIImage(cgImage: image.cgImage!) let contextSize: CGSize = contextImage.size var posX: CGFloat = 0.0 var posY: CGFloat = 0.0 var cgwidth: CGFloat = CGFloat(width) var cgheight: CGFloat = CGFloat(height) // // See what size is longer and create the center off of that // if contextSize.width > contextSize.height { // posX = ((contextSize.width - contextSize.height) / 2) // posY = 0 // cgwidth = contextSize.height // cgheight = contextSize.height // } else { // posX = 0 // posY = ((contextSize.height - contextSize.width) / 2) // cgwidth = contextSize.width // cgheight = contextSize.width // } let rect: CGRect = CGRect(x:posX, y:posY, width:cgwidth, height:cgheight) // Create bitmap image from context using the rect let imageRef: CGImage = contextImage.cgImage!.cropping(to: rect)! // Create a new image based on the imageRef and rotate back to the original orientation let image: UIImage = UIImage(cgImage: imageRef, scale: 20, orientation: image.imageOrientation) return image } @IBAction func saveTapped(_ sender: Any) { // image to share guard let zoomImage = self.zoomedImage, let original = self.originalImage else { return } // set up activity view controller let imageToShare = [zoomImage, original] let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash // exclude some activity types from the list (optional) activityViewController.excludedActivityTypes = [] // present the view controller self.present(activityViewController, animated: true, completion: nil) //UIImageWriteToSavedPhotosAlbum(zoomImage, nil, nil, nil) } // @IBAction func messageTapped(_ sender: Any) { // // image to share // guard let zoomImage = self.zoomedImage, let original = self.originalImage else { // return // } // // // set up activity view controller // let imageToShare = [zoomImage, original] // let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil) // activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash // // // exclude some activity types from the list (optional) // activityViewController.excludedActivityTypes = [] // // // present the view controller // self.present(activityViewController, animated: true, completion: nil) // } @IBAction func doneTapped(_ sender: Any) { self.isEditingPhoto = false if !isEditingPhoto { self.showCamera() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
tomtclai/swift-algorithm-club
My Work/Binary Search/BinarySearch.playground/Contents.swift
1
141
let numbers = [1,2,3,4] let sortedNums = numbers.sorted() binarySearch(sortedNums, target: 3) iteartiveBinarySearch(sortedNums, target: 4)
mit
nsagora/validation-toolkit
Sources/Constraints/Constraint.swift
1
2421
import Foundation /** The `Constraint` protocol is used to define the structure that must be implemented by concrete constraints. */ public protocol Constraint: AsyncConstraint { /// A type that provides information about what kind of values the constraint can be evaluated with. associatedtype InputType /// An error type that provides information about why the evaluation failed. associatedtype ErrorType /** Evaluates the input against the receiver. - parameter input: The input to be validated. - returns: `.success` if the input is valid,`.failure` containing the `Summary` of the failing `Constraint`s otherwise. */ func evaluate(with input: InputType) -> Result<Void, Summary<ErrorType>> } public extension Constraint { /** Evaluates the input against the receiver. When the evaluation is successful, it return the `input`, otherwise it throws the `Summary` of the failing `Constraint`. - parameter input: The input to be validated. - Returns:The `input` when the validation is successful. - Throws: The `Summary` of the failing `Constraint`s when the validation fails. */ func check(_ input: InputType) throws -> InputType { let result = evaluate(with: input) switch result { case .success: return input case .failure(let summary): throw summary } } } public extension Constraint { private var workQueue: DispatchQueue { return DispatchQueue(label: "com.nsagora.peppermint.constraint", attributes: .concurrent) } /** Asynchronous evaluates the input against the receiver. - parameter input: The input to be validated. - parameter queue: The queue on which the completion handler is executed. - parameter completionHandler: The completion handler to call when the evaluation is complete. It takes a `Bool` parameter: - parameter result: `.success` if the input is valid, `.failure` containing the `Summary` of the failing `Constraint`s otherwise. */ func evaluate(with input: InputType, queue: DispatchQueue, completionHandler: @escaping (_ result: Result<Void, Summary<ErrorType>>) -> Void) { workQueue.async { let result = self.evaluate(with: input) queue.async { completionHandler(result) } } } }
mit
br1sk/Sonar
Sources/Sonar/APIs/Result.swift
2
85
public enum Result<Value, Error> { case success(Value) case failure(Error) }
mit
andela-jejezie/FlutterwavePaymentManager
Rave/Rave/FWPresentation/FWPresentationController.swift
1
3480
// // FWPresentationController.swift // flutterwave // // Created by Johnson Ejezie on 10/12/2016. // Copyright © 2016 johnsonejezie. All rights reserved. // import UIKit class FWPresentationController: UIPresentationController { // MARK: - Properties fileprivate var dimmingView: UIView! override var frameOfPresentedViewInContainerView: CGRect { var frame: CGRect = .zero frame.size = size(forChildContentContainer: presentedViewController, withParentContainerSize: containerView!.bounds.size) frame.origin.y = (containerView!.frame.height - frame.size.height)/2.0 frame.origin.x = (containerView!.frame.width - frame.size.width)/2.0 return frame } // MARK: - Initializers override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { super.init(presentedViewController: presentedViewController, presenting: presentingViewController) setupDimmingView() } override func presentationTransitionWillBegin() { containerView?.insertSubview(dimmingView, at: 0) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|[dimmingView]|", options: [], metrics: nil, views: ["dimmingView": dimmingView])) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[dimmingView]|", options: [], metrics: nil, views: ["dimmingView": dimmingView])) guard let coordinator = presentedViewController.transitionCoordinator else { dimmingView.alpha = 1.0 return } coordinator.animate(alongsideTransition: { _ in self.dimmingView.alpha = 1.0 }) } override func dismissalTransitionWillBegin() { guard let coordinator = presentedViewController.transitionCoordinator else { dimmingView.alpha = 0.0 return } coordinator.animate(alongsideTransition: { _ in self.dimmingView.alpha = 0.0 }) } override func containerViewWillLayoutSubviews() { presentedView?.frame = frameOfPresentedViewInContainerView } override func size(forChildContentContainer container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize { var width = parentSize.width*0.9 let height = parentSize.height*0.8 if UIDevice.current.userInterfaceIdiom == .pad { width = 380 } if UIDevice.current.orientation.isLandscape { return CGSize(width:width, height: height) } if width > 414 { width = 380 } return CGSize(width: width, height: height) } } // MARK: - Private private extension FWPresentationController { func setupDimmingView() { dimmingView = UIView() dimmingView.translatesAutoresizingMaskIntoConstraints = false dimmingView.backgroundColor = UIColor(white: 0.0, alpha: 0.5) dimmingView.alpha = 0.0 let recognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:))) dimmingView.addGestureRecognizer(recognizer) } dynamic func handleTap(recognizer: UITapGestureRecognizer) { presentingViewController.dismiss(animated: true) } }
mit
swilliams/Lattice
Lattice/Behaviors/Validation/EmailTextValidator.swift
3
720
// // EmailTextValidator.swift // Lattice // // Created by Scott Williams on 8/5/15. // Copyright (c) 2015 Tallwave. All rights reserved. // import UIKit /** Checks if a string is a valid email. The pattern it matches against is intentionally naive. The [official email regex](http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html) is nearly as long as freaking Beowulf, and since emails are squirrelly little things, has a lot of false negatives. If you really want to do that knock yourself out. */ public class EmailTextValidator: BaseRegularExpressionValidator { private let _pattern = "^\\S+@\\S+\\.\\S+$" override var pattern: String { get { return _pattern } set {} } }
mit
Huralnyk/rxswift
Networking/Networking/ViewModel.swift
1
1743
// // ViewModel.swift // Networking // // Created by Scott Gardner on 6/6/16. // Copyright © 2016 Scott Gardner. All rights reserved. // import Foundation import RxSwift import RxCocoa class ViewModel { let searchText = Variable("") let disposeBag = DisposeBag() lazy var data: Driver<[Repository]> = { return self.searchText.asObservable() .throttle(0.3, scheduler: MainScheduler.instance) .distinctUntilChanged() .flatMapLatest { self.getRepositories(gitHubID: $0) }.asDriver(onErrorJustReturn: []) }() func getRepositories(gitHubID: String) -> Observable<[Repository]> { guard !gitHubID.isEmpty, let url = URL(string: "https://api.github.com/users/\(gitHubID)/repos") else { return Observable.just([]) } let request = URLRequest(url: url) return URLSession.shared.rx.json(request: request) .retry(3) // .catchErrorJustReturn([]) // .observeOn(ConcurrentDispatchQueueScheduler(qos: .background)) .map { var repositories: [Repository] = [] if let items = $0 as? [[String: AnyObject]] { items.forEach { guard let name = $0["name"] as? String, let url = $0["html_url"] as? String else { return } let repository = Repository(name: name, url: url) repositories.append(repository) } } return repositories } } }
mit
chinesemanbobo/PPDemo
Pods/Down/Source/Extensions/NSAttributedString+HTML.swift
3
980
// // NSAttributedString+HTML.swift // Down // // Created by Rob Phillips on 6/1/16. // Copyright © 2016-2019 Down. All rights reserved. // #if !os(Linux) #if os(macOS) import AppKit #else import UIKit #endif extension NSAttributedString { /// Instantiates an attributed string with the given HTML string /// /// - Parameter htmlString: An HTML string /// - Throws: `HTMLDataConversionError` or an instantiation error convenience init(htmlString: String) throws { guard let data = htmlString.data(using: String.Encoding.utf8) else { throw DownErrors.htmlDataConversionError } let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue) ] try self.init(data: data, options: options, documentAttributes: nil) } } #endif // !os(Linux)
mit
robertzhang/Gank.RZ
Gank.RZ/General/UIColor+Extension.swift
1
800
// // UIColor+Extension.swift // Gank.RZ // // Created by Robert Zhang on 16/5/5. // Copyright © 2016年 robertzhang. All rights reserved. // import UIKit extension UIColor { static func color(red: Int, green: Int, blue: Int, alpha: Float) -> UIColor { return UIColor( colorLiteralRed: Float(1.0) / Float(255.0) * Float(red), green: Float(1.0) / Float(255.0) * Float(green), blue: Float(1.0) / Float(255.0) * Float(blue), alpha: alpha) } static func randomColor()->UIColor{ let red = CGFloat(arc4random_uniform(255)) let green = CGFloat(arc4random_uniform(255)) let blue = CGFloat(arc4random_uniform(255)) return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 0.8) } }
mit
huangboju/Moots
Examples/边缘侧滑/MagicMove-master/MagicMove/Transition/MagicMoveTransion.swift
1
2663
// // MagicMoveTransion.swift // MagicMove // // Created by BourneWeng on 15/7/13. // Copyright (c) 2015年 Bourne. All rights reserved. // import UIKit class MagicMoveTransion: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { //1.获取动画的源控制器和目标控制器 let fromVC = transitionContext.viewController(forKey: .from) as! ViewController let toVC = transitionContext.viewController(forKey: .to) as! DetailViewController let container = transitionContext.containerView //2.创建一个 Cell 中 imageView 的截图,并把 imageView 隐藏,造成使用户以为移动的就是 imageView 的假象 let snapshotView = fromVC.selectedCell.imageView.snapshotView(afterScreenUpdates: false) snapshotView?.frame = container.convert(fromVC.selectedCell.imageView.frame, from: fromVC.selectedCell) fromVC.selectedCell.imageView.isHidden = true //3.设置目标控制器的位置,并把透明度设为0,在后面的动画中慢慢显示出来变为1 toVC.view.frame = transitionContext.finalFrame(for: toVC) toVC.view.alpha = 0 //4.都添加到 container 中。注意顺序不能错了 container.addSubview(toVC.view) container.addSubview(snapshotView!) //5.执行动画 /* 这时avatarImageView.frame的值只是跟在IB中一样的, 如果换成屏幕尺寸不同的模拟器运行时avatarImageView会先移动到IB中的frame,动画结束后才会突然变成正确的frame。 所以需要在动画执行前执行一次toVC.avatarImageView.layoutIfNeeded() update一次frame */ toVC.avatarImageView.layoutIfNeeded() UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveEaseInOut, animations: { () -> Void in snapshotView?.frame = toVC.avatarImageView.frame toVC.view.alpha = 1 }) { (finish: Bool) -> Void in fromVC.selectedCell.imageView.isHidden = false toVC.avatarImageView.image = toVC.image snapshotView?.removeFromSuperview() //一定要记得动画完成后执行此方法,让系统管理 navigation transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } }
mit
optimizely/swift-sdk
Tests/OptimizelyTests-Others/ThrowableConditionListTest.swift
1
4169
// // Copyright 2019, 2021, Optimizely, Inc. and 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. // import XCTest class ThrowableConditionListTest: XCTestCase { // MARK: - AND func testAndTrue() { let conditions = [true, true, true] let result = try! evalsListFromBools(conditions).and() XCTAssertTrue(result) } func testAndFalse() { var conditions = [false, true, true] var result = try! evalsListFromBools(conditions).and() XCTAssertFalse(result) conditions = [true, false, true] result = try! evalsListFromBools(conditions).and() XCTAssertFalse(result) conditions = [true, true, false] result = try! evalsListFromBools(conditions).and() XCTAssertFalse(result) } func testAndThrows() { var conditions = [nil, true, true] var result = try? evalsListFromBools(conditions).and() XCTAssertNil(result) conditions = [true, nil, true] result = try? evalsListFromBools(conditions).and() XCTAssertNil(result) conditions = [true, true, nil] result = try? evalsListFromBools(conditions).and() XCTAssertNil(result) } // MARK: - OR func testOrTrue() { var conditions = [true, true, true] var result = try! evalsListFromBools(conditions).or() XCTAssertTrue(result) conditions = [false, true, false] result = try! evalsListFromBools(conditions).or() XCTAssertTrue(result) conditions = [false, false, true] result = try! evalsListFromBools(conditions).or() XCTAssertTrue(result) } func testOrFalse() { let conditions = [false, false, false] let result = try! evalsListFromBools(conditions).or() XCTAssertFalse(result) } func testOrThrows() { var conditions: [Bool?] = [nil, true, true] var result = try! evalsListFromBools(conditions).or() XCTAssertTrue(result) conditions = [nil, nil, true] result = try! evalsListFromBools(conditions).or() XCTAssertTrue(result) let c2: [Bool?] = [nil, nil, nil] let r2: Bool? = try? evalsListFromBools(c2).or() XCTAssertNil(r2) } // MARK: - NOT func testNotTrue() { let conditions = [false, true, true] let result = try! evalsListFromBools(conditions).not() XCTAssertTrue(result) } func testNotFalse() { var conditions = [true] var result = try! evalsListFromBools(conditions).not() XCTAssertFalse(result) conditions = [true, false] result = try! evalsListFromBools(conditions).not() XCTAssertFalse(result) } func testNotThrows() { var conditions: [Bool?] = [nil] var result = try? evalsListFromBools(conditions).not() XCTAssertNil(result) conditions = [nil, true] result = try? evalsListFromBools(conditions).not() XCTAssertNil(result) conditions = [Bool]() result = try? evalsListFromBools(conditions).not() XCTAssertNil(result) } // MARK: - Utils func evalsListFromBools(_ conditions: [Bool?]) -> [ThrowableCondition] { return conditions.map { value -> ThrowableCondition in return { () throws -> Bool in guard let value = value else { throw OptimizelyError.conditionInvalidFormat("nil") } return value } } } }
apache-2.0
HongxiangShe/STV
Server/Server/Server/Immessage.proto.swift
2
51383
/// Generated by the Protocol Buffers 3.3.0 compiler. DO NOT EDIT! /// Protobuf-swift version: 3.0.16 /// Source file "IMMessage.proto" /// Syntax "Proto2" import Foundation import ProtocolBuffers public struct ImmessageRoot { public static let `default` = ImmessageRoot() public var extensionRegistry:ExtensionRegistry init() { extensionRegistry = ExtensionRegistry() registerAllExtensions(registry: extensionRegistry) } public func registerAllExtensions(registry: ExtensionRegistry) { } } final public class UserInfo : GeneratedMessage { public static func == (lhs: UserInfo, rhs: UserInfo) -> Bool { if lhs === rhs { return true } var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) fieldCheck = fieldCheck && (lhs.hasName == rhs.hasName) && (!lhs.hasName || lhs.name == rhs.name) fieldCheck = fieldCheck && (lhs.hasLevel == rhs.hasLevel) && (!lhs.hasLevel || lhs.level == rhs.level) fieldCheck = fieldCheck && (lhs.hasIconUrl == rhs.hasIconUrl) && (!lhs.hasIconUrl || lhs.iconUrl == rhs.iconUrl) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } public fileprivate(set) var name:String! = nil public fileprivate(set) var hasName:Bool = false public fileprivate(set) var level:Int64! = nil public fileprivate(set) var hasLevel:Bool = false public fileprivate(set) var iconUrl:String! = nil public fileprivate(set) var hasIconUrl:Bool = false required public init() { super.init() } override public func isInitialized() -> Bool { if !hasName { return false } if !hasLevel { return false } if !hasIconUrl { return false } return true } override public func writeTo(codedOutputStream: CodedOutputStream) throws { if hasName { try codedOutputStream.writeString(fieldNumber: 1, value:name) } if hasLevel { try codedOutputStream.writeInt64(fieldNumber: 2, value:level) } if hasIconUrl { try codedOutputStream.writeString(fieldNumber: 3, value:iconUrl) } try unknownFields.writeTo(codedOutputStream: codedOutputStream) } override public func serializedSize() -> Int32 { var serialize_size:Int32 = memoizedSerializedSize if serialize_size != -1 { return serialize_size } serialize_size = 0 if hasName { serialize_size += name.computeStringSize(fieldNumber: 1) } if hasLevel { serialize_size += level.computeInt64Size(fieldNumber: 2) } if hasIconUrl { serialize_size += iconUrl.computeStringSize(fieldNumber: 3) } serialize_size += unknownFields.serializedSize() memoizedSerializedSize = serialize_size return serialize_size } public class func getBuilder() -> UserInfo.Builder { return UserInfo.classBuilder() as! UserInfo.Builder } public func getBuilder() -> UserInfo.Builder { return classBuilder() as! UserInfo.Builder } override public class func classBuilder() -> ProtocolBuffersMessageBuilder { return UserInfo.Builder() } override public func classBuilder() -> ProtocolBuffersMessageBuilder { return UserInfo.Builder() } public func toBuilder() throws -> UserInfo.Builder { return try UserInfo.builderWithPrototype(prototype:self) } public class func builderWithPrototype(prototype:UserInfo) throws -> UserInfo.Builder { return try UserInfo.Builder().mergeFrom(other:prototype) } override public func encode() throws -> Dictionary<String,Any> { guard isInitialized() else { throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") } var jsonMap:Dictionary<String,Any> = Dictionary<String,Any>() if hasName { jsonMap["name"] = name } if hasLevel { jsonMap["level"] = "\(level)" } if hasIconUrl { jsonMap["iconURL"] = iconUrl } return jsonMap } override class public func decode(jsonMap:Dictionary<String,Any>) throws -> UserInfo { return try UserInfo.Builder.decodeToBuilder(jsonMap:jsonMap).build() } override class public func fromJSON(data:Data) throws -> UserInfo { return try UserInfo.Builder.fromJSONToBuilder(data:data).build() } override public func getDescription(indent:String) throws -> String { var output = "" if hasName { output += "\(indent) name: \(name) \n" } if hasLevel { output += "\(indent) level: \(level) \n" } if hasIconUrl { output += "\(indent) iconUrl: \(iconUrl) \n" } output += unknownFields.getDescription(indent: indent) return output } override public var hashValue:Int { get { var hashCode:Int = 7 if hasName { hashCode = (hashCode &* 31) &+ name.hashValue } if hasLevel { hashCode = (hashCode &* 31) &+ level.hashValue } if hasIconUrl { hashCode = (hashCode &* 31) &+ iconUrl.hashValue } hashCode = (hashCode &* 31) &+ unknownFields.hashValue return hashCode } } //Meta information declaration start override public class func className() -> String { return "UserInfo" } override public func className() -> String { return "UserInfo" } //Meta information declaration end final public class Builder : GeneratedMessageBuilder { fileprivate var builderResult:UserInfo = UserInfo() public func getMessage() -> UserInfo { return builderResult } required override public init () { super.init() } public var name:String { get { return builderResult.name } set (value) { builderResult.hasName = true builderResult.name = value } } public var hasName:Bool { get { return builderResult.hasName } } @discardableResult public func setName(_ value:String) -> UserInfo.Builder { self.name = value return self } @discardableResult public func clearName() -> UserInfo.Builder{ builderResult.hasName = false builderResult.name = nil return self } public var level:Int64 { get { return builderResult.level } set (value) { builderResult.hasLevel = true builderResult.level = value } } public var hasLevel:Bool { get { return builderResult.hasLevel } } @discardableResult public func setLevel(_ value:Int64) -> UserInfo.Builder { self.level = value return self } @discardableResult public func clearLevel() -> UserInfo.Builder{ builderResult.hasLevel = false builderResult.level = nil return self } public var iconUrl:String { get { return builderResult.iconUrl } set (value) { builderResult.hasIconUrl = true builderResult.iconUrl = value } } public var hasIconUrl:Bool { get { return builderResult.hasIconUrl } } @discardableResult public func setIconUrl(_ value:String) -> UserInfo.Builder { self.iconUrl = value return self } @discardableResult public func clearIconUrl() -> UserInfo.Builder{ builderResult.hasIconUrl = false builderResult.iconUrl = nil return self } override public var internalGetResult:GeneratedMessage { get { return builderResult } } @discardableResult override public func clear() -> UserInfo.Builder { builderResult = UserInfo() return self } override public func clone() throws -> UserInfo.Builder { return try UserInfo.builderWithPrototype(prototype:builderResult) } override public func build() throws -> UserInfo { try checkInitialized() return buildPartial() } public func buildPartial() -> UserInfo { let returnMe:UserInfo = builderResult return returnMe } @discardableResult public func mergeFrom(other:UserInfo) throws -> UserInfo.Builder { if other == UserInfo() { return self } if other.hasName { name = other.name } if other.hasLevel { level = other.level } if other.hasIconUrl { iconUrl = other.iconUrl } try merge(unknownField: other.unknownFields) return self } @discardableResult override public func mergeFrom(codedInputStream: CodedInputStream) throws -> UserInfo.Builder { return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) } @discardableResult override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> UserInfo.Builder { let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) while (true) { let protobufTag = try codedInputStream.readTag() switch protobufTag { case 0: self.unknownFields = try unknownFieldsBuilder.build() return self case 10: name = try codedInputStream.readString() case 16: level = try codedInputStream.readInt64() case 26: iconUrl = try codedInputStream.readString() default: if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { unknownFields = try unknownFieldsBuilder.build() return self } } } } class override public func decodeToBuilder(jsonMap:Dictionary<String,Any>) throws -> UserInfo.Builder { let resultDecodedBuilder = UserInfo.Builder() if let jsonValueName = jsonMap["name"] as? String { resultDecodedBuilder.name = jsonValueName } if let jsonValueLevel = jsonMap["level"] as? String { resultDecodedBuilder.level = Int64(jsonValueLevel)! } else if let jsonValueLevel = jsonMap["level"] as? Int { resultDecodedBuilder.level = Int64(jsonValueLevel) } if let jsonValueIconUrl = jsonMap["iconURL"] as? String { resultDecodedBuilder.iconUrl = jsonValueIconUrl } return resultDecodedBuilder } override class public func fromJSONToBuilder(data:Data) throws -> UserInfo.Builder { let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) guard let jsDataCast = jsonData as? Dictionary<String,Any> else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") } return try UserInfo.Builder.decodeToBuilder(jsonMap:jsDataCast) } } } final public class TextMessage : GeneratedMessage { public static func == (lhs: TextMessage, rhs: TextMessage) -> Bool { if lhs === rhs { return true } var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) fieldCheck = fieldCheck && (lhs.hasUser == rhs.hasUser) && (!lhs.hasUser || lhs.user == rhs.user) fieldCheck = fieldCheck && (lhs.hasText == rhs.hasText) && (!lhs.hasText || lhs.text == rhs.text) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } public fileprivate(set) var user:UserInfo! public fileprivate(set) var hasUser:Bool = false public fileprivate(set) var text:String! = nil public fileprivate(set) var hasText:Bool = false required public init() { super.init() } override public func isInitialized() -> Bool { if !hasUser { return false } if !hasText { return false } if !user.isInitialized() { return false } return true } override public func writeTo(codedOutputStream: CodedOutputStream) throws { if hasUser { try codedOutputStream.writeMessage(fieldNumber: 1, value:user) } if hasText { try codedOutputStream.writeString(fieldNumber: 2, value:text) } try unknownFields.writeTo(codedOutputStream: codedOutputStream) } override public func serializedSize() -> Int32 { var serialize_size:Int32 = memoizedSerializedSize if serialize_size != -1 { return serialize_size } serialize_size = 0 if hasUser { if let varSizeuser = user?.computeMessageSize(fieldNumber: 1) { serialize_size += varSizeuser } } if hasText { serialize_size += text.computeStringSize(fieldNumber: 2) } serialize_size += unknownFields.serializedSize() memoizedSerializedSize = serialize_size return serialize_size } public class func getBuilder() -> TextMessage.Builder { return TextMessage.classBuilder() as! TextMessage.Builder } public func getBuilder() -> TextMessage.Builder { return classBuilder() as! TextMessage.Builder } override public class func classBuilder() -> ProtocolBuffersMessageBuilder { return TextMessage.Builder() } override public func classBuilder() -> ProtocolBuffersMessageBuilder { return TextMessage.Builder() } public func toBuilder() throws -> TextMessage.Builder { return try TextMessage.builderWithPrototype(prototype:self) } public class func builderWithPrototype(prototype:TextMessage) throws -> TextMessage.Builder { return try TextMessage.Builder().mergeFrom(other:prototype) } override public func encode() throws -> Dictionary<String,Any> { guard isInitialized() else { throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") } var jsonMap:Dictionary<String,Any> = Dictionary<String,Any>() if hasUser { jsonMap["user"] = try user.encode() } if hasText { jsonMap["text"] = text } return jsonMap } override class public func decode(jsonMap:Dictionary<String,Any>) throws -> TextMessage { return try TextMessage.Builder.decodeToBuilder(jsonMap:jsonMap).build() } override class public func fromJSON(data:Data) throws -> TextMessage { return try TextMessage.Builder.fromJSONToBuilder(data:data).build() } override public func getDescription(indent:String) throws -> String { var output = "" if hasUser { output += "\(indent) user {\n" if let outDescUser = user { output += try outDescUser.getDescription(indent: "\(indent) ") } output += "\(indent) }\n" } if hasText { output += "\(indent) text: \(text) \n" } output += unknownFields.getDescription(indent: indent) return output } override public var hashValue:Int { get { var hashCode:Int = 7 if hasUser { if let hashValueuser = user?.hashValue { hashCode = (hashCode &* 31) &+ hashValueuser } } if hasText { hashCode = (hashCode &* 31) &+ text.hashValue } hashCode = (hashCode &* 31) &+ unknownFields.hashValue return hashCode } } //Meta information declaration start override public class func className() -> String { return "TextMessage" } override public func className() -> String { return "TextMessage" } //Meta information declaration end final public class Builder : GeneratedMessageBuilder { fileprivate var builderResult:TextMessage = TextMessage() public func getMessage() -> TextMessage { return builderResult } required override public init () { super.init() } public var user:UserInfo! { get { if userBuilder_ != nil { builderResult.user = userBuilder_.getMessage() } return builderResult.user } set (value) { builderResult.hasUser = true builderResult.user = value } } public var hasUser:Bool { get { return builderResult.hasUser } } fileprivate var userBuilder_:UserInfo.Builder! { didSet { builderResult.hasUser = true } } public func getUserBuilder() -> UserInfo.Builder { if userBuilder_ == nil { userBuilder_ = UserInfo.Builder() builderResult.user = userBuilder_.getMessage() if user != nil { try! userBuilder_.mergeFrom(other: user) } } return userBuilder_ } @discardableResult public func setUser(_ value:UserInfo!) -> TextMessage.Builder { self.user = value return self } @discardableResult public func mergeUser(value:UserInfo) throws -> TextMessage.Builder { if builderResult.hasUser { builderResult.user = try UserInfo.builderWithPrototype(prototype:builderResult.user).mergeFrom(other: value).buildPartial() } else { builderResult.user = value } builderResult.hasUser = true return self } @discardableResult public func clearUser() -> TextMessage.Builder { userBuilder_ = nil builderResult.hasUser = false builderResult.user = nil return self } public var text:String { get { return builderResult.text } set (value) { builderResult.hasText = true builderResult.text = value } } public var hasText:Bool { get { return builderResult.hasText } } @discardableResult public func setText(_ value:String) -> TextMessage.Builder { self.text = value return self } @discardableResult public func clearText() -> TextMessage.Builder{ builderResult.hasText = false builderResult.text = nil return self } override public var internalGetResult:GeneratedMessage { get { return builderResult } } @discardableResult override public func clear() -> TextMessage.Builder { builderResult = TextMessage() return self } override public func clone() throws -> TextMessage.Builder { return try TextMessage.builderWithPrototype(prototype:builderResult) } override public func build() throws -> TextMessage { try checkInitialized() return buildPartial() } public func buildPartial() -> TextMessage { let returnMe:TextMessage = builderResult return returnMe } @discardableResult public func mergeFrom(other:TextMessage) throws -> TextMessage.Builder { if other == TextMessage() { return self } if (other.hasUser) { try mergeUser(value: other.user) } if other.hasText { text = other.text } try merge(unknownField: other.unknownFields) return self } @discardableResult override public func mergeFrom(codedInputStream: CodedInputStream) throws -> TextMessage.Builder { return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) } @discardableResult override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> TextMessage.Builder { let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) while (true) { let protobufTag = try codedInputStream.readTag() switch protobufTag { case 0: self.unknownFields = try unknownFieldsBuilder.build() return self case 10: let subBuilder:UserInfo.Builder = UserInfo.Builder() if hasUser { try subBuilder.mergeFrom(other: user) } try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) user = subBuilder.buildPartial() case 18: text = try codedInputStream.readString() default: if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { unknownFields = try unknownFieldsBuilder.build() return self } } } } class override public func decodeToBuilder(jsonMap:Dictionary<String,Any>) throws -> TextMessage.Builder { let resultDecodedBuilder = TextMessage.Builder() if let jsonValueUser = jsonMap["user"] as? Dictionary<String,Any> { resultDecodedBuilder.user = try UserInfo.Builder.decodeToBuilder(jsonMap:jsonValueUser).build() } if let jsonValueText = jsonMap["text"] as? String { resultDecodedBuilder.text = jsonValueText } return resultDecodedBuilder } override class public func fromJSONToBuilder(data:Data) throws -> TextMessage.Builder { let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) guard let jsDataCast = jsonData as? Dictionary<String,Any> else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") } return try TextMessage.Builder.decodeToBuilder(jsonMap:jsDataCast) } } } final public class GiftMessage : GeneratedMessage { public static func == (lhs: GiftMessage, rhs: GiftMessage) -> Bool { if lhs === rhs { return true } var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) fieldCheck = fieldCheck && (lhs.hasUser == rhs.hasUser) && (!lhs.hasUser || lhs.user == rhs.user) fieldCheck = fieldCheck && (lhs.hasGiftname == rhs.hasGiftname) && (!lhs.hasGiftname || lhs.giftname == rhs.giftname) fieldCheck = fieldCheck && (lhs.hasGiftUrl == rhs.hasGiftUrl) && (!lhs.hasGiftUrl || lhs.giftUrl == rhs.giftUrl) fieldCheck = fieldCheck && (lhs.hasGiftCount == rhs.hasGiftCount) && (!lhs.hasGiftCount || lhs.giftCount == rhs.giftCount) fieldCheck = fieldCheck && (lhs.hasGiftGifUrl == rhs.hasGiftGifUrl) && (!lhs.hasGiftGifUrl || lhs.giftGifUrl == rhs.giftGifUrl) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } public fileprivate(set) var user:UserInfo! public fileprivate(set) var hasUser:Bool = false public fileprivate(set) var giftname:String! = nil public fileprivate(set) var hasGiftname:Bool = false public fileprivate(set) var giftUrl:String! = nil public fileprivate(set) var hasGiftUrl:Bool = false public fileprivate(set) var giftCount:String! = nil public fileprivate(set) var hasGiftCount:Bool = false public fileprivate(set) var giftGifUrl:String! = nil public fileprivate(set) var hasGiftGifUrl:Bool = false required public init() { super.init() } override public func isInitialized() -> Bool { if !hasUser { return false } if !hasGiftname { return false } if !hasGiftUrl { return false } if !hasGiftCount { return false } if !hasGiftGifUrl { return false } if !user.isInitialized() { return false } return true } override public func writeTo(codedOutputStream: CodedOutputStream) throws { if hasUser { try codedOutputStream.writeMessage(fieldNumber: 1, value:user) } if hasGiftname { try codedOutputStream.writeString(fieldNumber: 2, value:giftname) } if hasGiftUrl { try codedOutputStream.writeString(fieldNumber: 3, value:giftUrl) } if hasGiftCount { try codedOutputStream.writeString(fieldNumber: 4, value:giftCount) } if hasGiftGifUrl { try codedOutputStream.writeString(fieldNumber: 5, value:giftGifUrl) } try unknownFields.writeTo(codedOutputStream: codedOutputStream) } override public func serializedSize() -> Int32 { var serialize_size:Int32 = memoizedSerializedSize if serialize_size != -1 { return serialize_size } serialize_size = 0 if hasUser { if let varSizeuser = user?.computeMessageSize(fieldNumber: 1) { serialize_size += varSizeuser } } if hasGiftname { serialize_size += giftname.computeStringSize(fieldNumber: 2) } if hasGiftUrl { serialize_size += giftUrl.computeStringSize(fieldNumber: 3) } if hasGiftCount { serialize_size += giftCount.computeStringSize(fieldNumber: 4) } if hasGiftGifUrl { serialize_size += giftGifUrl.computeStringSize(fieldNumber: 5) } serialize_size += unknownFields.serializedSize() memoizedSerializedSize = serialize_size return serialize_size } public class func getBuilder() -> GiftMessage.Builder { return GiftMessage.classBuilder() as! GiftMessage.Builder } public func getBuilder() -> GiftMessage.Builder { return classBuilder() as! GiftMessage.Builder } override public class func classBuilder() -> ProtocolBuffersMessageBuilder { return GiftMessage.Builder() } override public func classBuilder() -> ProtocolBuffersMessageBuilder { return GiftMessage.Builder() } public func toBuilder() throws -> GiftMessage.Builder { return try GiftMessage.builderWithPrototype(prototype:self) } public class func builderWithPrototype(prototype:GiftMessage) throws -> GiftMessage.Builder { return try GiftMessage.Builder().mergeFrom(other:prototype) } override public func encode() throws -> Dictionary<String,Any> { guard isInitialized() else { throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") } var jsonMap:Dictionary<String,Any> = Dictionary<String,Any>() if hasUser { jsonMap["user"] = try user.encode() } if hasGiftname { jsonMap["giftname"] = giftname } if hasGiftUrl { jsonMap["giftURL"] = giftUrl } if hasGiftCount { jsonMap["giftCount"] = giftCount } if hasGiftGifUrl { jsonMap["giftGifURL"] = giftGifUrl } return jsonMap } override class public func decode(jsonMap:Dictionary<String,Any>) throws -> GiftMessage { return try GiftMessage.Builder.decodeToBuilder(jsonMap:jsonMap).build() } override class public func fromJSON(data:Data) throws -> GiftMessage { return try GiftMessage.Builder.fromJSONToBuilder(data:data).build() } override public func getDescription(indent:String) throws -> String { var output = "" if hasUser { output += "\(indent) user {\n" if let outDescUser = user { output += try outDescUser.getDescription(indent: "\(indent) ") } output += "\(indent) }\n" } if hasGiftname { output += "\(indent) giftname: \(giftname) \n" } if hasGiftUrl { output += "\(indent) giftUrl: \(giftUrl) \n" } if hasGiftCount { output += "\(indent) giftCount: \(giftCount) \n" } if hasGiftGifUrl { output += "\(indent) giftGifUrl: \(giftGifUrl) \n" } output += unknownFields.getDescription(indent: indent) return output } override public var hashValue:Int { get { var hashCode:Int = 7 if hasUser { if let hashValueuser = user?.hashValue { hashCode = (hashCode &* 31) &+ hashValueuser } } if hasGiftname { hashCode = (hashCode &* 31) &+ giftname.hashValue } if hasGiftUrl { hashCode = (hashCode &* 31) &+ giftUrl.hashValue } if hasGiftCount { hashCode = (hashCode &* 31) &+ giftCount.hashValue } if hasGiftGifUrl { hashCode = (hashCode &* 31) &+ giftGifUrl.hashValue } hashCode = (hashCode &* 31) &+ unknownFields.hashValue return hashCode } } //Meta information declaration start override public class func className() -> String { return "GiftMessage" } override public func className() -> String { return "GiftMessage" } //Meta information declaration end final public class Builder : GeneratedMessageBuilder { fileprivate var builderResult:GiftMessage = GiftMessage() public func getMessage() -> GiftMessage { return builderResult } required override public init () { super.init() } public var user:UserInfo! { get { if userBuilder_ != nil { builderResult.user = userBuilder_.getMessage() } return builderResult.user } set (value) { builderResult.hasUser = true builderResult.user = value } } public var hasUser:Bool { get { return builderResult.hasUser } } fileprivate var userBuilder_:UserInfo.Builder! { didSet { builderResult.hasUser = true } } public func getUserBuilder() -> UserInfo.Builder { if userBuilder_ == nil { userBuilder_ = UserInfo.Builder() builderResult.user = userBuilder_.getMessage() if user != nil { try! userBuilder_.mergeFrom(other: user) } } return userBuilder_ } @discardableResult public func setUser(_ value:UserInfo!) -> GiftMessage.Builder { self.user = value return self } @discardableResult public func mergeUser(value:UserInfo) throws -> GiftMessage.Builder { if builderResult.hasUser { builderResult.user = try UserInfo.builderWithPrototype(prototype:builderResult.user).mergeFrom(other: value).buildPartial() } else { builderResult.user = value } builderResult.hasUser = true return self } @discardableResult public func clearUser() -> GiftMessage.Builder { userBuilder_ = nil builderResult.hasUser = false builderResult.user = nil return self } public var giftname:String { get { return builderResult.giftname } set (value) { builderResult.hasGiftname = true builderResult.giftname = value } } public var hasGiftname:Bool { get { return builderResult.hasGiftname } } @discardableResult public func setGiftname(_ value:String) -> GiftMessage.Builder { self.giftname = value return self } @discardableResult public func clearGiftname() -> GiftMessage.Builder{ builderResult.hasGiftname = false builderResult.giftname = nil return self } public var giftUrl:String { get { return builderResult.giftUrl } set (value) { builderResult.hasGiftUrl = true builderResult.giftUrl = value } } public var hasGiftUrl:Bool { get { return builderResult.hasGiftUrl } } @discardableResult public func setGiftUrl(_ value:String) -> GiftMessage.Builder { self.giftUrl = value return self } @discardableResult public func clearGiftUrl() -> GiftMessage.Builder{ builderResult.hasGiftUrl = false builderResult.giftUrl = nil return self } public var giftCount:String { get { return builderResult.giftCount } set (value) { builderResult.hasGiftCount = true builderResult.giftCount = value } } public var hasGiftCount:Bool { get { return builderResult.hasGiftCount } } @discardableResult public func setGiftCount(_ value:String) -> GiftMessage.Builder { self.giftCount = value return self } @discardableResult public func clearGiftCount() -> GiftMessage.Builder{ builderResult.hasGiftCount = false builderResult.giftCount = nil return self } public var giftGifUrl:String { get { return builderResult.giftGifUrl } set (value) { builderResult.hasGiftGifUrl = true builderResult.giftGifUrl = value } } public var hasGiftGifUrl:Bool { get { return builderResult.hasGiftGifUrl } } @discardableResult public func setGiftGifUrl(_ value:String) -> GiftMessage.Builder { self.giftGifUrl = value return self } @discardableResult public func clearGiftGifUrl() -> GiftMessage.Builder{ builderResult.hasGiftGifUrl = false builderResult.giftGifUrl = nil return self } override public var internalGetResult:GeneratedMessage { get { return builderResult } } @discardableResult override public func clear() -> GiftMessage.Builder { builderResult = GiftMessage() return self } override public func clone() throws -> GiftMessage.Builder { return try GiftMessage.builderWithPrototype(prototype:builderResult) } override public func build() throws -> GiftMessage { try checkInitialized() return buildPartial() } public func buildPartial() -> GiftMessage { let returnMe:GiftMessage = builderResult return returnMe } @discardableResult public func mergeFrom(other:GiftMessage) throws -> GiftMessage.Builder { if other == GiftMessage() { return self } if (other.hasUser) { try mergeUser(value: other.user) } if other.hasGiftname { giftname = other.giftname } if other.hasGiftUrl { giftUrl = other.giftUrl } if other.hasGiftCount { giftCount = other.giftCount } if other.hasGiftGifUrl { giftGifUrl = other.giftGifUrl } try merge(unknownField: other.unknownFields) return self } @discardableResult override public func mergeFrom(codedInputStream: CodedInputStream) throws -> GiftMessage.Builder { return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) } @discardableResult override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> GiftMessage.Builder { let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) while (true) { let protobufTag = try codedInputStream.readTag() switch protobufTag { case 0: self.unknownFields = try unknownFieldsBuilder.build() return self case 10: let subBuilder:UserInfo.Builder = UserInfo.Builder() if hasUser { try subBuilder.mergeFrom(other: user) } try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) user = subBuilder.buildPartial() case 18: giftname = try codedInputStream.readString() case 26: giftUrl = try codedInputStream.readString() case 34: giftCount = try codedInputStream.readString() case 42: giftGifUrl = try codedInputStream.readString() default: if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { unknownFields = try unknownFieldsBuilder.build() return self } } } } class override public func decodeToBuilder(jsonMap:Dictionary<String,Any>) throws -> GiftMessage.Builder { let resultDecodedBuilder = GiftMessage.Builder() if let jsonValueUser = jsonMap["user"] as? Dictionary<String,Any> { resultDecodedBuilder.user = try UserInfo.Builder.decodeToBuilder(jsonMap:jsonValueUser).build() } if let jsonValueGiftname = jsonMap["giftname"] as? String { resultDecodedBuilder.giftname = jsonValueGiftname } if let jsonValueGiftUrl = jsonMap["giftURL"] as? String { resultDecodedBuilder.giftUrl = jsonValueGiftUrl } if let jsonValueGiftCount = jsonMap["giftCount"] as? String { resultDecodedBuilder.giftCount = jsonValueGiftCount } if let jsonValueGiftGifUrl = jsonMap["giftGifURL"] as? String { resultDecodedBuilder.giftGifUrl = jsonValueGiftGifUrl } return resultDecodedBuilder } override class public func fromJSONToBuilder(data:Data) throws -> GiftMessage.Builder { let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) guard let jsDataCast = jsonData as? Dictionary<String,Any> else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") } return try GiftMessage.Builder.decodeToBuilder(jsonMap:jsDataCast) } } } extension UserInfo: GeneratedMessageProtocol { public class func parseArrayDelimitedFrom(inputStream: InputStream) throws -> Array<UserInfo> { var mergedArray = Array<UserInfo>() while let value = try parseDelimitedFrom(inputStream: inputStream) { mergedArray.append(value) } return mergedArray } public class func parseDelimitedFrom(inputStream: InputStream) throws -> UserInfo? { return try UserInfo.Builder().mergeDelimitedFrom(inputStream: inputStream)?.build() } public class func parseFrom(data: Data) throws -> UserInfo { return try UserInfo.Builder().mergeFrom(data: data, extensionRegistry:ImmessageRoot.default.extensionRegistry).build() } public class func parseFrom(data: Data, extensionRegistry:ExtensionRegistry) throws -> UserInfo { return try UserInfo.Builder().mergeFrom(data: data, extensionRegistry:extensionRegistry).build() } public class func parseFrom(inputStream: InputStream) throws -> UserInfo { return try UserInfo.Builder().mergeFrom(inputStream: inputStream).build() } public class func parseFrom(inputStream: InputStream, extensionRegistry:ExtensionRegistry) throws -> UserInfo { return try UserInfo.Builder().mergeFrom(inputStream: inputStream, extensionRegistry:extensionRegistry).build() } public class func parseFrom(codedInputStream: CodedInputStream) throws -> UserInfo { return try UserInfo.Builder().mergeFrom(codedInputStream: codedInputStream).build() } public class func parseFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> UserInfo { return try UserInfo.Builder().mergeFrom(codedInputStream: codedInputStream, extensionRegistry:extensionRegistry).build() } public subscript(key: String) -> Any? { switch key { case "name": return self.name case "level": return self.level case "iconUrl": return self.iconUrl default: return nil } } } extension UserInfo.Builder: GeneratedMessageBuilderProtocol { public subscript(key: String) -> Any? { get { switch key { case "name": return self.name case "level": return self.level case "iconUrl": return self.iconUrl default: return nil } } set (newSubscriptValue) { switch key { case "name": guard let newSubscriptValue = newSubscriptValue as? String else { return } self.name = newSubscriptValue case "level": guard let newSubscriptValue = newSubscriptValue as? Int64 else { return } self.level = newSubscriptValue case "iconUrl": guard let newSubscriptValue = newSubscriptValue as? String else { return } self.iconUrl = newSubscriptValue default: return } } } } extension TextMessage: GeneratedMessageProtocol { public class func parseArrayDelimitedFrom(inputStream: InputStream) throws -> Array<TextMessage> { var mergedArray = Array<TextMessage>() while let value = try parseDelimitedFrom(inputStream: inputStream) { mergedArray.append(value) } return mergedArray } public class func parseDelimitedFrom(inputStream: InputStream) throws -> TextMessage? { return try TextMessage.Builder().mergeDelimitedFrom(inputStream: inputStream)?.build() } public class func parseFrom(data: Data) throws -> TextMessage { return try TextMessage.Builder().mergeFrom(data: data, extensionRegistry:ImmessageRoot.default.extensionRegistry).build() } public class func parseFrom(data: Data, extensionRegistry:ExtensionRegistry) throws -> TextMessage { return try TextMessage.Builder().mergeFrom(data: data, extensionRegistry:extensionRegistry).build() } public class func parseFrom(inputStream: InputStream) throws -> TextMessage { return try TextMessage.Builder().mergeFrom(inputStream: inputStream).build() } public class func parseFrom(inputStream: InputStream, extensionRegistry:ExtensionRegistry) throws -> TextMessage { return try TextMessage.Builder().mergeFrom(inputStream: inputStream, extensionRegistry:extensionRegistry).build() } public class func parseFrom(codedInputStream: CodedInputStream) throws -> TextMessage { return try TextMessage.Builder().mergeFrom(codedInputStream: codedInputStream).build() } public class func parseFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> TextMessage { return try TextMessage.Builder().mergeFrom(codedInputStream: codedInputStream, extensionRegistry:extensionRegistry).build() } public subscript(key: String) -> Any? { switch key { case "user": return self.user case "text": return self.text default: return nil } } } extension TextMessage.Builder: GeneratedMessageBuilderProtocol { public subscript(key: String) -> Any? { get { switch key { case "user": return self.user case "text": return self.text default: return nil } } set (newSubscriptValue) { switch key { case "user": guard let newSubscriptValue = newSubscriptValue as? UserInfo else { return } self.user = newSubscriptValue case "text": guard let newSubscriptValue = newSubscriptValue as? String else { return } self.text = newSubscriptValue default: return } } } } extension GiftMessage: GeneratedMessageProtocol { public class func parseArrayDelimitedFrom(inputStream: InputStream) throws -> Array<GiftMessage> { var mergedArray = Array<GiftMessage>() while let value = try parseDelimitedFrom(inputStream: inputStream) { mergedArray.append(value) } return mergedArray } public class func parseDelimitedFrom(inputStream: InputStream) throws -> GiftMessage? { return try GiftMessage.Builder().mergeDelimitedFrom(inputStream: inputStream)?.build() } public class func parseFrom(data: Data) throws -> GiftMessage { return try GiftMessage.Builder().mergeFrom(data: data, extensionRegistry:ImmessageRoot.default.extensionRegistry).build() } public class func parseFrom(data: Data, extensionRegistry:ExtensionRegistry) throws -> GiftMessage { return try GiftMessage.Builder().mergeFrom(data: data, extensionRegistry:extensionRegistry).build() } public class func parseFrom(inputStream: InputStream) throws -> GiftMessage { return try GiftMessage.Builder().mergeFrom(inputStream: inputStream).build() } public class func parseFrom(inputStream: InputStream, extensionRegistry:ExtensionRegistry) throws -> GiftMessage { return try GiftMessage.Builder().mergeFrom(inputStream: inputStream, extensionRegistry:extensionRegistry).build() } public class func parseFrom(codedInputStream: CodedInputStream) throws -> GiftMessage { return try GiftMessage.Builder().mergeFrom(codedInputStream: codedInputStream).build() } public class func parseFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> GiftMessage { return try GiftMessage.Builder().mergeFrom(codedInputStream: codedInputStream, extensionRegistry:extensionRegistry).build() } public subscript(key: String) -> Any? { switch key { case "user": return self.user case "giftname": return self.giftname case "giftUrl": return self.giftUrl case "giftCount": return self.giftCount case "giftGifUrl": return self.giftGifUrl default: return nil } } } extension GiftMessage.Builder: GeneratedMessageBuilderProtocol { public subscript(key: String) -> Any? { get { switch key { case "user": return self.user case "giftname": return self.giftname case "giftUrl": return self.giftUrl case "giftCount": return self.giftCount case "giftGifUrl": return self.giftGifUrl default: return nil } } set (newSubscriptValue) { switch key { case "user": guard let newSubscriptValue = newSubscriptValue as? UserInfo else { return } self.user = newSubscriptValue case "giftname": guard let newSubscriptValue = newSubscriptValue as? String else { return } self.giftname = newSubscriptValue case "giftUrl": guard let newSubscriptValue = newSubscriptValue as? String else { return } self.giftUrl = newSubscriptValue case "giftCount": guard let newSubscriptValue = newSubscriptValue as? String else { return } self.giftCount = newSubscriptValue case "giftGifUrl": guard let newSubscriptValue = newSubscriptValue as? String else { return } self.giftGifUrl = newSubscriptValue default: return } } } } // @@protoc_insertion_point(global_scope)
apache-2.0
iossocket/BabyMoment
BabyMomentTests/BabyProfileTests.swift
1
2582
import XCTest import RealmSwift @testable import BabyMoment class BabyProfileTests: XCTestCase { override func setUp() { NSUserDefaults.resetStandardUserDefaults() let realm = try! Realm() try! realm.write { realm.deleteAll() } } func test_saveName_should_save_to_default_setting() { BabyProfile.saveName("xuebao") let babyName:String = NSUserDefaults.standardUserDefaults().stringForKey("kBabyName")! XCTAssertEqual(babyName, "xuebao") } func test_saveGender_should_save_to_default_setting() { BabyProfile.saveGender(Gender.Boy) let babyGender:NSInteger = NSUserDefaults.standardUserDefaults().integerForKey("kBabyGender") XCTAssertEqual(Gender(rawValue: babyGender), Gender.Boy) } func test_saveBirthday_should_save_to_default_setting() { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" BabyProfile.saveBirthday(formatter.dateFromString("2015-09-11")!) let brithday:String = NSUserDefaults.standardUserDefaults().stringForKey("kBabyBirthday")! XCTAssertEqual(brithday, "2015-09-11") } func test_initWithUserDefault_should_return_a_baby_profile() { BabyProfile.saveName("xuebao") BabyProfile.saveGender(Gender.Boy) let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" let birthdayDate: NSDate = formatter.dateFromString("2015-09-11")! BabyProfile.saveBirthday(birthdayDate) let baby: BabyProfile = BabyProfile.initWithUserDefault() XCTAssertEqual(baby.name, "xuebao") XCTAssertEqual(baby.gender, Gender.Boy.rawValue) XCTAssertEqual(baby.birthday, birthdayDate) } func test_currentProfile_should_return_nil() { XCTAssertNil(BabyProfile.currentProfile()) } func test_currentProfile_should_return_current_profile() { let baby: BabyProfile = BabyProfile(value: ["name": "xuebao", "gender": Gender.Boy.rawValue, "birthday": NSDate()]) baby.save() XCTAssertEqual(BabyProfile.currentProfile()!, baby) } func test_save_should_save_baby_profile() { let baby: BabyProfile = BabyProfile(value: ["name": "xuebao", "gender": Gender.Boy.rawValue, "birthday": NSDate()]) baby.save() let realm = try! Realm() let ret = realm.objects(BabyProfile.self).first! XCTAssertEqual(ret, baby) } }
mit
jakubgert/JGSwiftUI
JGUISampleApp/JGUISampleApp/Model/SimpleNews.swift
1
282
// // SimpleNews.swift // JGUISampleApp // // Created by Jakub Gert on 02/01/15. // Copyright (c) 2015 Planktovision. All rights reserved. // import UIKit class SimpleNews: NSObject { var title: String? init( title: String? ) { self.title = title } }
mit
ArtSabintsev/Freedom
Sources/DolphinFreedomActivity.swift
1
3467
// // DolphinFreedomActivity.swift // Freedom // // Created by Arthur Sabintsev on 7/8/17. // Copyright © 2017 Arthur Ariel Sabintsev. All rights reserved. // import UIKit final class DolphinFreedomActivity: UIActivity, FreedomActivating { override class var activityCategory: UIActivity.Category { return .action } override var activityImage: UIImage? { return UIImage(named: "dolphin", in: Freedom.bundle, compatibleWith: nil) } override var activityTitle: String? { return "Open in Dolphin" } override var activityType: UIActivity.ActivityType? { guard let bundleID = Bundle.main.bundleIdentifier else { Freedom.printDebugMessage("Failed to fetch the bundleID.") return nil } let type = bundleID + "." + String(describing: DolphinFreedomActivity.self) return UIActivity.ActivityType(rawValue: type) } var activityDeepLink: String? = "dolphin://" var activityURL: URL? override func canPerform(withActivityItems activityItems: [Any]) -> Bool { for item in activityItems { guard let deepLinkURLString = activityDeepLink, let deepLinkURL = URL(string: deepLinkURLString), UIApplication.shared.canOpenURL(deepLinkURL) else { return false } guard let url = item as? URL else { continue } guard url.conformToHypertextProtocol() else { Freedom.printDebugMessage("The URL scheme is missing. This happens if a URL does not contain `http://` or `https://`.") return false } Freedom.printDebugMessage("The user has the Dolphin Web Browser installed.") return true } return false } override func prepare(withActivityItems activityItems: [Any]) { activityItems.forEach { item in guard let url = item as? URL, url.conformToHypertextProtocol() else { return Freedom.printDebugMessage("The URL scheme is missing. This happens if a URL does not contain `http://` or `https://`.") } activityURL = url return } } override func perform() { guard let activityURL = activityURL else { Freedom.printDebugMessage("activityURL is missing.") return activityDidFinish(false) } guard let deepLink = activityDeepLink, let formattedURL = activityURL.withoutScheme(), let url = URL(string: deepLink + formattedURL.absoluteString) else { return activityDidFinish(false) } if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:]) { [weak self] opened in guard let strongSelf = self else { return } guard opened else { return strongSelf.activityDidFinish(false) } Freedom.printDebugMessage("The user successfully opened the url, \(activityURL.absoluteString), in the Dolphin Browser.") strongSelf.activityDidFinish(true) } } else { UIApplication.shared.openURL(url) Freedom.printDebugMessage("The user successfully opened the url, \(activityURL.absoluteString), in the Dolphin Browser.") activityDidFinish(true) } } }
mit