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
nalexn/ViewInspector
Tests/ViewInspectorTests/SwiftUI/MapTests.swift
1
8387
#if canImport(MapKit) import MapKit import SwiftUI import XCTest @testable import ViewInspector class MapTests: XCTestCase { private let testRegion = MKCoordinateRegion( center: CLLocationCoordinate2D(latitude: 123, longitude: 321), latitudinalMeters: 987, longitudinalMeters: 6) func testExtractionFromSingleViewContainer() throws { guard #available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.0, *) else { throw XCTSkip() } let sut = AnyView(Map(coordinateRegion: .constant(MKCoordinateRegion()))) XCTAssertNoThrow(try sut.inspect().anyView().map()) } func testExtractionFromMultipleViewContainer() throws { guard #available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.0, *) else { throw XCTSkip() } let view = HStack { Map(coordinateRegion: .constant(MKCoordinateRegion())) Map(coordinateRegion: .constant(MKCoordinateRegion())) } XCTAssertNoThrow(try view.inspect().hStack().map(0)) XCTAssertNoThrow(try view.inspect().hStack().map(1)) } func testSearch() throws { guard #available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.0, *) else { throw XCTSkip() } let view = AnyView(Map(coordinateRegion: .constant(MKCoordinateRegion()))) XCTAssertEqual(try view.inspect().find(ViewType.Map.self).pathToRoot, "anyView().map()") } func testExtractingCoordinateRegionValue() throws { guard #available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.0, *) else { throw XCTSkip() } let sut = Map(coordinateRegion: .constant(testRegion)) XCTAssertEqual(try sut.inspect().map().coordinateRegion(), testRegion) } func testSettingCoordinateRegionValue() throws { guard #available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.0, *) else { throw XCTSkip() } let binding = Binding(wrappedValue: MKCoordinateRegion()) let sut = Map(coordinateRegion: binding) XCTAssertEqual(try sut.inspect().map().coordinateRegion(), MKCoordinateRegion()) try sut.inspect().map().setCoordinateRegion(testRegion) XCTAssertEqual(try sut.inspect().map().coordinateRegion(), testRegion) XCTAssertEqual(binding.wrappedValue, testRegion) } func testErrorOnSettingCoordinateRegionWhenNonResponsive() throws { guard #available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.0, *) else { throw XCTSkip() } let binding = Binding(wrappedValue: MKCoordinateRegion()) let sut = Map(coordinateRegion: binding).hidden() XCTAssertEqual(try sut.inspect().map().coordinateRegion(), MKCoordinateRegion()) XCTAssertFalse(try sut.inspect().map().isResponsive()) XCTAssertThrows(try sut.inspect().map().setCoordinateRegion(testRegion), "Map is unresponsive: it is hidden") } func testExtractingMapRectValue() throws { guard #available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.0, *) else { throw XCTSkip() } let rect = MKMapRect(x: 3, y: 5, width: 1, height: 8) let sut = Map(mapRect: .constant(rect), interactionModes: .all, showsUserLocation: false, userTrackingMode: .constant(.none)) XCTAssertEqual(try sut.inspect().map().mapRect(), rect) } func testSettingMapRectValue() throws { guard #available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.0, *) else { throw XCTSkip() } let binding = Binding(wrappedValue: MKMapRect()) let sut = Map(mapRect: binding, interactionModes: .all, showsUserLocation: false, userTrackingMode: .constant(.none)) XCTAssertEqual(try sut.inspect().map().mapRect(), MKMapRect()) let rect = MKMapRect(x: 3, y: 5, width: 1, height: 8) try sut.inspect().map().setMapRect(rect) XCTAssertEqual(try sut.inspect().map().mapRect(), rect) XCTAssertEqual(binding.wrappedValue, rect) } func testErrorOnSettingMapRectWhenNonResponsive() throws { guard #available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.0, *) else { throw XCTSkip() } let binding = Binding(wrappedValue: MKMapRect()) let sut = Map(mapRect: binding, interactionModes: .all, showsUserLocation: false, userTrackingMode: .constant(.none)) .hidden() XCTAssertEqual(try sut.inspect().map().mapRect(), MKMapRect()) XCTAssertFalse(try sut.inspect().map().isResponsive()) let rect = MKMapRect(x: 3, y: 5, width: 1, height: 8) XCTAssertThrows(try sut.inspect().map().setMapRect(rect), "Map is unresponsive: it is hidden") } func testExtractingInteractionModes() throws { guard #available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.0, *) else { throw XCTSkip() } let region = MKCoordinateRegion() let sut = Map(coordinateRegion: .constant(region), interactionModes: .pan, showsUserLocation: false, userTrackingMode: .constant(.none)) let value = try sut.inspect().map().interactionModes() XCTAssertEqual(value, .pan) } func testExtractingShowsUserLocation() throws { guard #available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.0, *) else { throw XCTSkip() } let region = MKCoordinateRegion() let sut = Map(coordinateRegion: .constant(region), interactionModes: .all, showsUserLocation: true, userTrackingMode: .constant(.none)) let value = try sut.inspect().map().showsUserLocation() XCTAssertEqual(value, true) } func testExtractingUserTrackingMode() throws { guard #available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.0, *) else { throw XCTSkip() } let region = MKCoordinateRegion() let sut = Map(coordinateRegion: .constant(region), interactionModes: .all, showsUserLocation: true, userTrackingMode: .constant(.follow)) let value = try sut.inspect().map().userTrackingMode() XCTAssertEqual(value, .follow) } func testSettingUserTrackingMode() throws { guard #available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.0, *) else { throw XCTSkip() } let binding = Binding(wrappedValue: MapUserTrackingMode.follow) let sut = Map(coordinateRegion: .constant(MKCoordinateRegion()), interactionModes: .all, showsUserLocation: true, userTrackingMode: binding) XCTAssertEqual(try sut.inspect().map().userTrackingMode(), .follow) try sut.inspect().map().setUserTrackingMode(.none) XCTAssertEqual(try sut.inspect().map().userTrackingMode(), .none) XCTAssertEqual(binding.wrappedValue, .none) } } // MARK: - Equatable extension CLLocationCoordinate2D: Equatable { public static func == (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool { return lhs.latitude == rhs.latitude && rhs.longitude == rhs.longitude } } extension MKCoordinateSpan: Equatable { public static func == (lhs: MKCoordinateSpan, rhs: MKCoordinateSpan) -> Bool { return lhs.latitudeDelta == rhs.latitudeDelta && lhs.longitudeDelta == rhs.longitudeDelta } } extension MKCoordinateRegion: Equatable { public static func == (lhs: MKCoordinateRegion, rhs: MKCoordinateRegion) -> Bool { return lhs.center == rhs.center && lhs.span == rhs.span } } extension MKMapPoint: Equatable { public static func == (lhs: MKMapPoint, rhs: MKMapPoint) -> Bool { return lhs.coordinate == rhs.coordinate } } extension MKMapSize: Equatable { public static func == (lhs: MKMapSize, rhs: MKMapSize) -> Bool { return lhs.width == lhs.width && lhs.height == rhs.height } } extension MKMapRect: Equatable { public static func == (lhs: MKMapRect, rhs: MKMapRect) -> Bool { return lhs.origin == rhs.origin && lhs.size == rhs.size } } #endif
mit
a1exb1/ABToolKit-pod
Pod/Classes/FormView/FormViewCell.swift
1
523
// // FormViewCell.swift // Pods // // Created by Alex Bechmann on 08/06/2015. // // import UIKit public class FormViewCell: UITableViewCell { public var config = FormViewConfiguration() public var formViewDelegate: FormViewDelegate? public var editable: Bool { get { if let editable = formViewDelegate?.formViewElementIsEditable?(config.identifier) { return editable } return true } } }
mit
baquiax/SimpleTwitterClient
SimpleTwitterClient/Pods/OAuthSwift/OAuthSwift/String+OAuthSwift.swift
5
3960
// // String+OAuthSwift.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation extension String { internal func indexOf(sub: String) -> Int? { var pos: Int? if let range = self.rangeOfString(sub) { if !range.isEmpty { pos = self.startIndex.distanceTo(range.startIndex) } } return pos } internal subscript (r: Range<Int>) -> String { get { let startIndex = self.startIndex.advancedBy(r.startIndex) let endIndex = startIndex.advancedBy(r.endIndex - r.startIndex) return self[startIndex..<endIndex] } } func urlEncodedStringWithEncoding(encoding: NSStringEncoding) -> String { let originalString: NSString = self let customAllowedSet = NSCharacterSet(charactersInString:"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") let escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet) return escapedString! as String } func parametersFromQueryString() -> Dictionary<String, String> { return dictionaryBySplitting("&", keyValueSeparator: "=") } var urlQueryEncoded: String? { return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) } func dictionaryBySplitting(elementSeparator: String, keyValueSeparator: String) -> Dictionary<String, String> { var string = self if(hasPrefix(elementSeparator)) { string = String(characters.dropFirst(1)) } var parameters = Dictionary<String, String>() let scanner = NSScanner(string: string) var key: NSString? var value: NSString? while !scanner.atEnd { key = nil scanner.scanUpToString(keyValueSeparator, intoString: &key) scanner.scanString(keyValueSeparator, intoString: nil) value = nil scanner.scanUpToString(elementSeparator, intoString: &value) scanner.scanString(elementSeparator, intoString: nil) if (key != nil && value != nil) { parameters.updateValue(value! as String, forKey: key! as String) } } return parameters } public var headerDictionary: Dictionary<String, String> { return dictionaryBySplitting(",", keyValueSeparator: "=") } var safeStringByRemovingPercentEncoding: String { return self.stringByRemovingPercentEncoding ?? self } func split(s:String)->[String]{ if s.isEmpty{ var x=[String]() for y in self.characters{ x.append(String(y)) } return x } return self.componentsSeparatedByString(s) } func trim()->String{ return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } func has(s:String)->Bool{ if (self.rangeOfString(s) != nil) { return true }else{ return false } } func hasBegin(s:String)->Bool{ if self.hasPrefix(s) { return true }else{ return false } } func hasEnd(s:String)->Bool{ if self.hasSuffix(s) { return true }else{ return false } } func length()->Int{ return self.utf16.count } func size()->Int{ return self.utf16.count } func `repeat`(times: Int) -> String{ var result = "" for _ in 0..<times { result += self } return result } func reverse()-> String{ let s=Array(self.split("").reverse()) var x="" for y in s{ x+=y } return x } }
mit
edragoev1/pdfjet
Sources/PDFjet/Segment.swift
1
1367
/** * Segment.swift * Copyright 2020 Innovatics Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /// /// Used to specify the segment of Ellipse or Circle to draw. /// See Example_18 /// public class Segment { public static let CLOCKWISE_00_03 = 0 public static let CLOCKWISE_03_06 = 1 public static let CLOCKWISE_06_09 = 2 public static let CLOCKWISE_09_12 = 3 }
mit
osrufung/TouchVisualizer
Example/Example/ConfigViewController.swift
2
4074
// // ConfigViewController.swift // Example // // Created by MORITA NAOKI on 2015/01/25. // Copyright (c) 2015年 molabo. All rights reserved. // import UIKit import TouchVisualizer final class ConfigViewController: UITableViewController { @IBOutlet weak var timerCell: UITableViewCell! @IBOutlet weak var touchRadiusCell: UITableViewCell! @IBOutlet weak var logCell: UITableViewCell! @IBOutlet weak var blueColorCell: UITableViewCell! @IBOutlet weak var redColorCell: UITableViewCell! @IBOutlet weak var greenColorCell: UITableViewCell! var config = Configuration() let colors = [ "blue": UIColor(red: 52/255.0, green: 152/255.0, blue: 219/255.0, alpha: 0.8), "green": UIColor(red: 22/255.0, green: 160/255.0, blue: 133/255.0, alpha: 0.8), "red": UIColor(red: 192/255.0, green: 57/255.0, blue: 43/255.0, alpha: 0.8) ] // MARK: - Life Cycle override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) Visualizer.start() updateCells() } // MARK: - TableView Delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let cell = tableView.cellForRowAtIndexPath(indexPath) if cell == timerCell { config.showsTimer = !config.showsTimer } if cell == touchRadiusCell { if isSimulator() { let controller = UIAlertController( title: "Warning", message: "This property doesn't work on the simulator because it is not possible to read touch radius on it. Please test it on device.", preferredStyle: .Alert ) controller.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) self.presentViewController(controller, animated: true, completion: nil) return } config.showsTouchRadius = !config.showsTouchRadius } if cell == logCell { config.showsLog = !config.showsLog } if cell == blueColorCell { config.color = colors["blue"]! } if cell == redColorCell { config.color = colors["red"]! } if cell == greenColorCell { config.color = colors["green"]! } updateCells() Visualizer.start(config) } func updateCells() { let boolCells = [timerCell, touchRadiusCell, logCell] for cell in boolCells { cell.detailTextLabel?.text = "false" } let checkmarkCells = [blueColorCell, redColorCell, greenColorCell] for cell in checkmarkCells { cell.accessoryType = .None } if config.showsTimer { timerCell.detailTextLabel?.text = "true" } if config.showsTouchRadius { touchRadiusCell.detailTextLabel?.text = "true" } if config.showsLog { logCell.detailTextLabel?.text = "true" } if config.color == colors["blue"] { blueColorCell.accessoryType = .Checkmark } else if config.color == colors["red"] { redColorCell.accessoryType = .Checkmark } else if config.color == colors["green"] { greenColorCell.accessoryType = .Checkmark } } // MARK: - Actions @IBAction func cancelButtonTapped(sender: UIBarButtonItem) { dismissViewControllerAnimated(true, completion: nil) Visualizer.start() } @IBAction func doneButtonTapped(sender: UIBarButtonItem) { self.dismissViewControllerAnimated(true, completion: nil) } func isSimulator() -> Bool { var simulator = false #if (arch(i386) || arch(x86_64)) && os(iOS) simulator = true #endif return simulator } }
mit
crazypoo/PTools
Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift
2
1155
// // CryptoSwift // // Copyright (C) 2014-2022 Marcin Krzyżanowski <marcin@krzyzanowskim.com> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // import Foundation extension Rabbit { public convenience init(key: String) throws { try self.init(key: key.bytes) } public convenience init(key: String, iv: String) throws { try self.init(key: key.bytes, iv: iv.bytes) } }
mit
shridharmalimca/iOSDev
iOS/Components/MusicTransition/MusicTransition/MiniPlayerViewController.swift
2
887
// // MiniPlayerViewController.swift // MusicTransition // // Created by Shridhar Mali on 1/24/17. // Copyright © 2017 Shridhar Mali. All rights reserved. // import UIKit class MiniPlayerViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
muyexi/Mogoroom-Demo
Mogoroom Demo/ViewModel/CellViewModelProtocol.swift
1
242
import UIKit enum LoadingState: String { case loading = "加载中..." case success = "加载完成" case failure = "加载失败" } protocol CellViewModelProtocol { var api: APIProtocol { get } func loadData() }
mit
OpenKitten/MongoKitten
Sources/MongoClient/InternalCommands/IsMaster.swift
2
2039
import MongoCore public struct MongoClientDetails: Encodable { public struct ApplicationDetails: Encodable { public var name: String } public struct DriverDetails: Encodable { public let name = "SwiftMongoClient" public let version = "1" } public struct OSDetails: Encodable { #if os(Linux) public let type = "Linux" public let name: String? = nil // TODO: see if we can fill this in #elseif os(macOS) public let type = "Darwin" public let name: String? = "macOS" #elseif os(iOS) public let type = "Darwin" public let name: String? = "iOS" #elseif os(Windows) public let type = "Windows" public let name: String? = nil #else public let type = "unknown" public let name: String? = nil #endif #if arch(x86_64) public let architecture: String? = "x86_64" #else public let architecture: String? = nil #endif public let version: String? = nil } public var application: ApplicationDetails? public var driver = DriverDetails() public var os = OSDetails() #if swift(>=5.2) public let platform: String? = "Swift 5.2" #elseif swift(>=5.1) public let platform: String? = "Swift 5.1" #elseif swift(>=5.0) public let platform: String? = "Swift 5.0" #elseif swift(>=4.2) public let platform: String? = "Swift 4.2" #elseif swift(>=4.1) public let platform: String? = "Swift 4.1" #else public let platform: String? #endif public init(application: ApplicationDetails?) { self.application = application } } internal struct IsMaster: Encodable { private let isMaster: Int32 = 1 internal var saslSupportedMechs: String? internal var client: MongoClientDetails? internal init(clientDetails: MongoClientDetails?, userNamespace: String?) { self.client = clientDetails self.saslSupportedMechs = userNamespace } }
mit
Bouke/Swift-Security
README.playground/section-6.swift
2
58
certificates[0].commonName certificates[0].subjectCountry
mit
Arthraim/ARTagger
ARTagger/ViewController.swift
1
8075
// // ViewController.swift // ARTagger // // Created by Arthur Wang on 7/7/17. // Copyright © 2017 YANGAPP. All rights reserved. // import UIKit import SceneKit import ARKit import CoreML import Vision class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate { // var session: ARSession! var text: String? private var requests = [VNRequest]() var screenCenter: CGPoint? @IBOutlet var sceneView: ARSCNView! override func viewDidLoad() { super.viewDidLoad() // Set the view's delegate sceneView.delegate = self // Show statistics such as fps and timing information sceneView.showsStatistics = true sceneView.preferredFramesPerSecond = 60 DispatchQueue.main.async { self.screenCenter = self.sceneView.bounds.mid } // Create a new scene let scene = SCNScene(named: "art.scnassets/empty.scn")! // Set the scene to the view sceneView.scene = scene sceneView.session.delegate = self // coreML vision setupVision() sceneView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleTag(gestureRecognizer:)))) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Create a session configuration let configuration = ARWorldTrackingSessionConfiguration() // configuration.planeDetection = .horizontal // Run the view's session sceneView.session.run(configuration) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Pause the view's session sceneView.session.pause() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } // func addText(text: String) { @objc func handleTag(gestureRecognizer: UITapGestureRecognizer) { guard let currentFrame = sceneView.session.currentFrame else { return } let scnText = SCNText(string: String(text ?? "ERROR"), extrusionDepth: 1) scnText.firstMaterial?.lightingModel = .constant let textScale = 0.02 / Float(scnText.font.pointSize) let textNode = SCNNode(geometry: scnText) textNode.scale = SCNVector3Make(textScale, textScale, textScale) sceneView.scene.rootNode.addChildNode(textNode) // Set transform of node to be 10cm in front of camera var translation = textNode.simdTransform translation.columns.3.z = -0.2 textNode.simdTransform = matrix_multiply(currentFrame.camera.transform, translation) addHomeTags(currentFrame: currentFrame) } func addHomeTags(currentFrame: ARFrame) { if (text == "mouse") { addHomeTag(imageName: "razer", currentFrame: currentFrame) } else if (text == "iPod") { addHomeTag(imageName: "nokia", currentFrame: currentFrame) } } func addHomeTag(imageName: String, currentFrame: ARFrame) { let image = UIImage(named: imageName) // Create an image plane using a snapshot of the view let imagePlain = SCNPlane(width: sceneView.bounds.width / 6000, height: sceneView.bounds.height / 6000) imagePlain.firstMaterial?.diffuse.contents = image imagePlain.firstMaterial?.lightingModel = .constant let plainNode = SCNNode(geometry: imagePlain) sceneView.scene.rootNode.addChildNode(plainNode) // Set transform of node to be 10cm in front of camera var translation = matrix_identity_float4x4 translation.columns.3.z = -0.22 translation.columns.3.y = 0.05 plainNode.simdTransform = matrix_multiply(currentFrame.camera.transform, translation) } // MARK: - coreML vision logic func setupVision() { //guard let visionModel = try? VNCoreMLModel(for: Inceptionv3().model) guard let visionModel = try? VNCoreMLModel(for: Resnet50().model) else { fatalError("Can't load VisionML model") } let classificationRequest = VNCoreMLRequest(model: visionModel, completionHandler: handleClassifications) classificationRequest.imageCropAndScaleOption = VNImageCropAndScaleOptionCenterCrop self.requests = [classificationRequest] } func handleClassifications(request: VNRequest, error: Error?) { guard let observations = request.results else { print("no results: \(error!)"); return } let classifications = observations[0...4] .flatMap({ $0 as? VNClassificationObservation }) // .filter({ $0.confidence > 0.3 }) .sorted(by: { $0.confidence > $1.confidence }) DispatchQueue.main.async { let text = classifications.map { (prediction: VNClassificationObservation) -> String in return "\(round(prediction.confidence * 100 * 100)/100)%: \(prediction.identifier)" } print(text.joined(separator: " | ")) // add 3d text if let firstPrediction = classifications.first { if firstPrediction.confidence > 0.1 { // self.addText(text: firstPrediction.identifier) if let t = firstPrediction.identifier.split(separator: ",").first { self.text = String(t) } } } } } // MARK: - ARSCNViewDelegate // Override to create and configure nodes for anchors added to the view's session. // func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? { // if let textNote = textNode { // updateText() // return textNode // } // let node = SCNNode() // return node // } // func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { // // This visualization covers only detected planes. // guard let planeAnchor = anchor as? ARPlaneAnchor else { return } // // // Create a SceneKit plane to visualize the node using its position and extent. // let plane = SCNPlane(width: CGFloat(planeAnchor.extent.x), height: CGFloat(planeAnchor.extent.z)) // let planeNode = SCNNode(geometry: plane) // planeNode.position = SCNVector3Make(planeAnchor.center.x, 0, planeAnchor.center.z) // // // SCNPlanes are vertically oriented in their local coordinate space. // // Rotate it to match the horizontal orientation of the ARPlaneAnchor. // planeNode.transform = SCNMatrix4MakeRotation(-Float.pi / 2, 1, 0, 0) // // // ARKit owns the node corresponding to the anchor, so make the plane a child node. // node.addChildNode(planeNode) // } func session(_ session: ARSession, didFailWithError error: Error) { // Present an error message to the user } func sessionWasInterrupted(_ session: ARSession) { // Inform the user that the session has been interrupted, for example, by presenting an overlay } func sessionInterruptionEnded(_ session: ARSession) { // Reset tracking and/or remove existing anchors if consistent tracking is required } var i = 0 func session(_ session: ARSession, didUpdate frame: ARFrame) { i = i + 1 if (i % 10 == 0) { // if (i <= 10) { DispatchQueue.global(qos: .background).async { var requestOptions:[VNImageOption : Any] = [:] let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: frame.capturedImage, orientation: 1, options: requestOptions) do { try imageRequestHandler.perform(self.requests) } catch { print(error) } } } } }
mit
russbishop/swift
test/Generics/invalid.swift
1
2479
// RUN: %target-parse-verify-swift -enable-experimental-nested-generic-types func bet() where A : B {} // expected-error {{'where' clause cannot be attached to a non-generic declaration}} typealias gimel where A : B // expected-error {{'where' clause cannot be attached to a non-generic declaration}} // expected-error@-1 {{expected '=' in typealias declaration}} class dalet where A : B {} // expected-error {{'where' clause cannot be attached to a non-generic declaration}} protocol he where A : B { // expected-error {{'where' clause cannot be attached to a protocol declaration}} associatedtype vav where A : B // expected-error {{'where' clause cannot be attached to an associated type declaration}} } struct Lunch<T> { struct Dinner<U> { var leftovers: T var transformation: (T) -> U } } class Deli<Spices> { class Pepperoni {} struct Sausage {} } struct Pizzas<Spices> { class NewYork { } class DeepDish { } } class HotDog { } struct Pepper {} struct ChiliFlakes {} func eatDinnerConcrete(d: Pizzas<ChiliFlakes>.NewYork, t: Deli<ChiliFlakes>.Pepperoni) { } func eatDinnerConcrete(d: Pizzas<Pepper>.DeepDish, t: Deli<Pepper>.Pepperoni) { } func badDiagnostic1() { _ = Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDog>( // expected-error {{expression type 'Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDog>' is ambiguous without more context}} leftovers: Pizzas<ChiliFlakes>.NewYork(), transformation: { _ in HotDog() }) } func badDiagnostic2() { let firstCourse = Pizzas<ChiliFlakes>.NewYork() var dinner = Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDog>( leftovers: firstCourse, transformation: { _ in HotDog() }) let topping = Deli<Pepper>.Pepperoni() eatDinnerConcrete(d: firstCourse, t: topping) // expected-error@-1 {{cannot invoke 'eatDinnerConcrete' with an argument list of type '(d: Pizzas<ChiliFlakes>.NewYork, t: Deli<Pepper>.Pepperoni)'}} // expected-note@-2 {{overloads for 'eatDinnerConcrete' exist with these partially matching parameter lists: (d: Pizzas<ChiliFlakes>.NewYork, t: Deli<ChiliFlakes>.Pepperoni), (d: Pizzas<Pepper>.DeepDish, t: Deli<Pepper>.Pepperoni)}} } // Real error is that we cannot infer the generic parameter from context func takesAny(_ a: Any) {} func badDiagnostic3() { takesAny(Deli.self) // expected-error {{argument type 'Deli<_>.Type' does not conform to expected type 'Any' (aka 'protocol<>')}} }
apache-2.0
TongCui/LearningCrptography
CryptographyDemo/ViewControllers/CryptographyViewController.swift
1
3238
// // CryptographyViewController.swift // CryptographyDemo // // Created by tcui on 14/8/2017. // Copyright © 2017 LuckyTR. All rights reserved. // import UIKit import RxSwift import RxCocoa class CryptographyViewController: BaseViewController { var cryptography: Cryptography? @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var topLabel: UILabel! @IBOutlet weak var topTextField: UITextField! @IBOutlet weak var bottomLabel: UILabel! @IBOutlet weak var bottomTextField: UITextField! @IBOutlet weak var keyTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() setupUI() // Do any additional setup after loading the view. } private func setupUI() { // Default Key keyTextField.text = cryptography?.defaultKey // Upper Case topTextField.rx.text .map { $0?.uppercased() } .bind(to: topTextField.rx.text) .disposed(by: disposeBag) bottomTextField.rx.text .map { $0?.uppercased() } .bind(to: bottomTextField.rx.text) .disposed(by: disposeBag) // Bind Top and Bottom Textfields let topTextObservable = topTextField.rx.text.orEmpty.throttle(0.5, scheduler: MainScheduler.instance) let keyTextObservable = keyTextField.rx.text.orEmpty.throttle(0.5, scheduler: MainScheduler.instance) let segmentedControlObservable = segmentedControl.rx.value Observable.combineLatest(topTextObservable, keyTextObservable, segmentedControlObservable) { [weak self] topText, keyText, segmentedIndex in let bottomText: String? switch segmentedIndex { case 0: bottomText = self?.cryptography?.encrypt(from: topText, key: keyText) case 1: bottomText = self?.cryptography?.decrypt(from: topText, key: keyText) default: bottomText = "Error" } return bottomText ?? "" } .bind(to: bottomTextField.rx.text) .disposed(by: disposeBag) // Segmented Control segmentedControl.rx.value .map { $0 == 0 ? "Plaintext" : "Chipertext" } .bind(to: topLabel.rx.text) .disposed(by: disposeBag) segmentedControl.rx.value .map { $0 == 1 ? "Plaintext" : "Chipertext" } .bind(to: bottomLabel.rx.text) .disposed(by: disposeBag) // Tap View to hide keyboard let tapBackground = UITapGestureRecognizer() tapBackground.rx.event .subscribe(onNext: { [weak self] _ in self?.view.endEditing(true) }) .disposed(by: disposeBag) view.addGestureRecognizer(tapBackground) } private func getPlaintext(from chiperText: String) -> String { return "plaintext \(chiperText)" } private func getChipertext(from plainText: String) -> String { return "chipertext \(plainText)" } private func changeKey() { print("TODO: Change Key") } }
mit
JakeLin/IBAnimatable
Sources/Views/AnimatableTableView.swift
2
4867
// // Created by Jake Lin on 12/15/15. // Copyright © 2015 IBAnimatable. All rights reserved. // import UIKit @IBDesignable open class AnimatableTableView: UITableView, FillDesignable, BorderDesignable, GradientDesignable, BackgroundImageDesignable, BlurDesignable, RefreshControlDesignable, Animatable { // MARK: - FillDesignable @IBInspectable open var fillColor: UIColor? { didSet { configureFillColor() } } open var predefinedColor: ColorType? { didSet { configureFillColor() } } @IBInspectable var _predefinedColor: String? { didSet { predefinedColor = ColorType(string: _predefinedColor) } } @IBInspectable open var opacity: CGFloat = CGFloat.nan { didSet { configureOpacity() } } // MARK: - BorderDesignable open var borderType: BorderType = .solid { didSet { configureBorder() } } @IBInspectable var _borderType: String? { didSet { borderType = BorderType(string: _borderType) } } @IBInspectable open var borderColor: UIColor? { didSet { configureBorder() } } @IBInspectable open var borderWidth: CGFloat = CGFloat.nan { didSet { configureBorder() } } open var borderSides: BorderSides = .AllSides { didSet { configureBorder() } } @IBInspectable var _borderSides: String? { didSet { borderSides = BorderSides(rawValue: _borderSides) } } // MARK: - GradientDesignable open var gradientMode: GradientMode = .linear @IBInspectable var _gradientMode: String? { didSet { gradientMode = GradientMode(string: _gradientMode) ?? .linear } } @IBInspectable open var startColor: UIColor? @IBInspectable open var endColor: UIColor? open var predefinedGradient: GradientType? @IBInspectable var _predefinedGradient: String? { didSet { predefinedGradient = GradientType(string: _predefinedGradient) } } open var startPoint: GradientStartPoint = .top @IBInspectable var _startPoint: String? { didSet { startPoint = GradientStartPoint(string: _startPoint, default: .top) } } // MARK: - BackgroundImageDesignable @IBInspectable open var backgroundImage: UIImage? { didSet { configureBackgroundImage() configureBackgroundBlurEffectStyle() } } // MARK: - BlurDesignable open var blurEffectStyle: UIBlurEffect.Style? { didSet { configureBackgroundBlurEffectStyle() } } @IBInspectable var _blurEffectStyle: String? { didSet { blurEffectStyle = UIBlurEffect.Style(string: _blurEffectStyle) } } open var vibrancyEffectStyle: UIBlurEffect.Style? { didSet { configureBackgroundBlurEffectStyle() } } @IBInspectable var _vibrancyEffectStyle: String? { didSet { vibrancyEffectStyle = UIBlurEffect.Style(string: _vibrancyEffectStyle) } } @IBInspectable open var blurOpacity: CGFloat = CGFloat.nan { didSet { configureBackgroundBlurEffectStyle() } } // MARK: - RefreshControlDesignable @IBInspectable open var hasRefreshControl: Bool = false { didSet { configureRefreshController() } } @IBInspectable open var refreshControlTintColor: UIColor? { didSet { configureRefreshController() } } @IBInspectable open var refreshControlBackgroundColor: UIColor? { didSet { configureRefreshController() } } // MARK: - Animatable open var animationType: AnimationType = .none @IBInspectable var _animationType: String? { didSet { animationType = AnimationType(string: _animationType) } } @IBInspectable open var autoRun: Bool = true @IBInspectable open var duration: Double = Double.nan @IBInspectable open var delay: Double = Double.nan @IBInspectable open var damping: CGFloat = CGFloat.nan @IBInspectable open var velocity: CGFloat = CGFloat.nan @IBInspectable open var force: CGFloat = CGFloat.nan @IBInspectable var _timingFunction: String = "" { didSet { timingFunction = TimingFunctionType(string: _timingFunction) } } open var timingFunction: TimingFunctionType = .none // MARK: - Lifecycle open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() configureInspectableProperties() } open override func awakeFromNib() { super.awakeFromNib() configureInspectableProperties() } open override func layoutSubviews() { super.layoutSubviews() autoRunAnimation() configureAfterLayoutSubviews() } // MARK: - Private fileprivate func configureInspectableProperties() { configureAnimatableProperties() configureOpacity() } fileprivate func configureAfterLayoutSubviews() { configureBorder() configureGradient() } }
mit
wuhduhren/Mr-Ride-iOS
Mr-Ride-iOS/Model/Resources/UIFont+YBKAdditions.swift
1
1691
// // UIFont+YBKAdditions.swift // YouBike // // Generated on Zeplin. (by wuduhren on 2016/5/23). // Copyright (c) 2016 __MyCompanyName__. All rights reserved. // import UIKit extension UIFont { class func mrTextStyleFont() -> UIFont? { return UIFont(name: "Helvetica-Bold", size: 80.0) } class func mrTextStyle8Font() -> UIFont { return UIFont.systemFontOfSize(80.0, weight: UIFontWeightBold) } class func mrTextStyle5Font() -> UIFont? { return UIFont(name: "Helvetica", size: 50.0) } class func mrTextStyle9Font() -> UIFont { return UIFont.systemFontOfSize(30.0, weight: UIFontWeightRegular) } class func mrTextStyle3Font() -> UIFont { return UIFont.systemFontOfSize(24.0, weight: UIFontWeightBold) } class func mrTextStyle7Font() -> UIFont { return UIFont.systemFontOfSize(24.0, weight: UIFontWeightMedium) } class func mrTextStyle11Font() -> UIFont { return UIFont.systemFontOfSize(24.0, weight: UIFontWeightMedium) } class func mrTextStyle2Font() -> UIFont? { return UIFont(name: "PingFangTC-Medium", size: 20.0) } class func mrTextStyle10Font() -> UIFont { return UIFont.systemFontOfSize(20.0, weight: UIFontWeightMedium) } class func mrTextStyle6Font() -> UIFont? { return UIFont(name: "Helvetica", size: 20.0) } class func mrTextStyle12Font() -> UIFont { return UIFont.systemFontOfSize(12.0, weight: UIFontWeightRegular) } class func mrTextStyle4Font() -> UIFont { return UIFont.systemFontOfSize(10.0, weight: UIFontWeightRegular) } class func mrTextStyle13Font() -> UIFont { return UIFont.systemFontOfSize(17.0, weight: UIFontWeightBold) } }
mit
aulas-lab/ads-ios
Optional/Optional/main.swift
1
413
// // main.swift // Optional // // Created by Mobitec on 24/08/16. // Copyright (c) 2016 Unopar. All rights reserved. // import Foundation class Pessoa { var nome = "" var endereco = "" } func imprime(p: Pessoa) { println("Nome: \(p.nome), Endereco: \(p.endereco)") } func imprime(numero: Int) { println("\(numero)") } var x: Int = 0 var p1: Pessoa = Pessoa() imprime(x) imprime(p1)
mit
IBM-MIL/IBM-Ready-App-for-Retail
iOS/ReadyAppRetail/ReadyAppRetail/Controllers/ProductDetailViewController.swift
1
16891
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit class ProductDetailViewController: MILWebViewController, MILWebViewDelegate, UIAlertViewDelegate { @IBOutlet weak var addToListContainerView: UIView! @IBOutlet weak var addToListContainerViewBottomSpace: NSLayoutConstraint! @IBOutlet weak var backBarButton: UIBarButtonItem! @IBOutlet weak var addedToListPopupLabel: UILabel! @IBOutlet weak var addedToListPopup: UIView! @IBOutlet weak var dimViewButton: UIButton! var addToListContainerViewDestinationBottomSpace: CGFloat! var containerViewController: AddToListContainerViewController! var productId : NSString = "" var currentProduct : Product! var webViewReady : Bool = false var jsonDataReady : Bool = false var jsonString : NSString! var json : JSON? var addToListVisible : Bool = false override func viewDidLoad() { self.startPage = "index.html/" super.viewDidLoad() self.saveInstanceToAppDelegate() self.setUpAddToListPopup() self.setUpAddToListContainer() self.setupWebView() self.showDimViewButton() //query for product information self.getProductById() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { setUpNavigationBar() } /** When the view disappears it hides the progress hud - parameter animated: */ override func viewWillDisappear(animated: Bool) { Utils.dismissProgressHud() } /** This method is called by viewDidLoad. It calls MILWLHelper's getProductById method and then shows the progressHud */ private func getProductById(){ MILWLHelper.getProductById(self.productId, callBack: self.productRetrievalResult) Utils.showProgressHud() } func productRetrievalResult(success: Bool, jsonResult: JSON?) { if success { if let result = jsonResult { self.receiveProductDetailJSON(result) } } else { self.failureGettingProductById() } } /** This method is called by the GetProductByIdDataManager when the onFailure is called by Worklight. It first dismisses the progress hud and then if the view is visible it shows the error alert */ func failureGettingProductById(){ Utils.dismissProgressHud() if (self.isViewLoaded() == true && self.view.window != nil ) { //check if the view is currently visible Utils.showServerErrorAlertWithCancel(self, tag: 1) //only show error alert if the view is visible } } /** This method is called by ProductIsAvailableDataManager when the onFailure is called by the Worklight. It first dismisses the progress hud and then if the view is visible it shows the error alert */ func failureGettingProductAvailability(){ Utils.dismissProgressHud() if (self.isViewLoaded() == true && self.view.window != nil) { Utils.showServerErrorAlertWithCancel(self, tag: 2) } } /** This method is called when the user clicks a button on the alert view. If the user clicks a button with index 1 then it shows the progress hud and then retries either the getProductById method or the queryProductIsAvailable method. If the butten clicked is index 0 then it pops the view controller to go back to the browseViewController. - parameter alertView: - parameter buttonIndex: */ func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if(alertView.tag == 1){ if(buttonIndex == 1){ Utils.showProgressHud() self.getProductById() } else{ self.navigationController?.popViewControllerAnimated(true) } } else if(alertView.tag == 2){ if(buttonIndex == 1){ Utils.showProgressHud() self.queryProductIsAvailable() } else{ self.navigationController?.popViewControllerAnimated(true) } } } /** This method saves the current instance of ProductDetailViewController to the app delegate's instance variable "productDetailViewController" */ private func saveInstanceToAppDelegate(){ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.productDetailViewController = self } /** This method sets up the the navigation bar with various properties */ private func setUpNavigationBar(){ //customize back arrow //set the back button to be just an arrow, nothing in right button space (nil) self.navigationItem.leftBarButtonItem = self.backBarButton self.navigationItem.rightBarButtonItem = nil self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Oswald-Regular", size: 22)!, NSForegroundColorAttributeName: UIColor.whiteColor()] } /** This method sets up the webview */ private func setupWebView(){ self.view.bringSubviewToFront(self.webView) self.delegate = self self.setupWebViewConstraints() } /** This method sets up the addToListPopup */ private func setUpAddToListPopup(){ self.addedToListPopup.alpha = 0 self.addedToListPopup.layer.cornerRadius = 10 } /** This method sets ups the AddToListContainer */ private func setUpAddToListContainer(){ self.addToListContainerViewDestinationBottomSpace = self.addToListContainerViewBottomSpace.constant self.addToListContainerViewBottomSpace.constant = -(self.addToListContainerView.frame.size.height + self.tabBarController!.tabBar.bounds.size.height) self.providesPresentationContextTransitionStyle = true; self.definesPresentationContext = true; } /** This method shows the dimViewButton by making it not hidden, changing its alpha and bringing it up to the front */ private func showDimViewButton(){ self.dimViewButton.alpha = 0.0 self.dimViewButton.hidden = false self.dimViewButton.alpha = 0.6 self.view.bringSubviewToFront(self.dimViewButton) } /** This method hides the dimViewbutton by changing it to hidden and making its alpha set to 0.0 */ private func hideDimViewButton(){ if (self.addToListVisible == false) { self.dimViewButton.hidden = true } } /** This method is called if the callback changes. If pathComponents[2] is set to "Ready then it sets the webViewReady instance variable to true and it then calls the tryToInjectData method. If both the webView and data are ready then it will inject the data. - parameter pathComponents: */ func callBackHasChanged(pathComponents: Array<String>) { if (pathComponents[2] == "Ready") { self.webViewReady = true self.tryToInjectData() } } /** This method takes care of if the addToList Button was pressed on the hybrid side. It calls the addToListTapped method to show the modal popup of the addToListContainer - parameter pathComponents: */ func nativeViewHasChanged(pathComponents: Array<String>) { if (pathComponents[2] == "AddToList") { self.addToListTapped() } } /** This method first checks if data can be injected by calling the canInjectData method. If this is true, then it calls the injectData method and then hides the dimViewButton */ private func tryToInjectData(){ if(self.canInjectData() == true){ self.injectData() self.hideDimViewButton() } } /** This method checks if data can be injected. It does this by checking if the jsonDataReady and webViewReady are both set to true. If it is set to true, then it returns true, else false. - returns: A Bool representing if data can be injected */ private func canInjectData() -> Bool{ if(self.jsonDataReady == true && self.webViewReady == true){ return true } else{ return false } } /** This method injects data into the web view by injecting the jsonString instance variable. */ private func injectData(){ let injectData : String = "injectData(\(self.jsonString))"; let inject : String = Utils.prepareCodeInjectionString(injectData); self.webView.stringByEvaluatingJavaScriptFromString(inject); Utils.dismissProgressHud() } /** This method is called by the GetProductByIdDataManager when it has finished massaging the product detail json. It sets the json instance variable to the json parameter. It then calls parseProduct of JSONParseHelper and sets the currentProduct instance variable to the return value of this method. After it calls the queryProductIsAvailable method to query for product availabilty. - parameter json: the massaged product detail json the webview expects */ func receiveProductDetailJSON(json : JSON){ self.json = json self.currentProduct = JSONParseHelper.parseProduct(json) self.updateTitle() self.queryProductIsAvailable() } /** This method updates the title of the navigation bar */ private func updateTitle(){ if let name = self.currentProduct?.name { self.navigationItem.title = name.uppercaseString } } /** This method is called by the receiveProductDetailJSON method. It first calls MILWLHelper's productIsAvailable method. If this method returns false, then this means the user isn't logged in and it will procede to inject data without product availability since getting product availability is a protected call and a user needs to be logged in to make this call. */ func queryProductIsAvailable(){ if(MILWLHelper.productIsAvailable(self.currentProduct.id, callback: self) != true){ self.jsonString = "\(self.json!)" self.jsonDataReady = true self.tryToInjectData() } } /** This method is called by the ProductIsAvailableDataManager when it is ready to send the product availability information to the ProductDetailViewController. It will recieve a 1 for In Stock, 0 for out of stock, or a 2 for no information available. When this method receives this information, it adds it to the json instance variable and then updates to the jsonString instance variable and sets the jsonDataReady instance variable to true. After it trys to inject data by calling the tryToInjectData method. - parameter availability: 1 for In Stock, 0 for out of stock, or a 2 for no information available */ func recieveProductAvailability(availability : Int){ if(availability == 1){ self.json!["availability"] = "In Stock" } else if (availability == 0){ self.json!["availability"] = "Out of Stock" } else if (availability == 2){ self.json!["availability"] = "" } self.jsonString = "\(self.json!)" self.jsonDataReady = true self.tryToInjectData() } /** This method is called by the ReadyAppsChallengeHandler when the user authentication has timed out thus not allowing us to do productIsAvailable procedure call to Worklight since this call is protected. Thus, this method injects data to the webview without the product availability. */ func injectWithoutProductAvailability(){ self.jsonString = "\(self.json!)" self.jsonDataReady = true self.tryToInjectData() } /** calls the UserAuthHelper's checkIfLoggedIn method, and shows login view if not logged in. If logged in, shows choose list view */ func addToListTapped(){ if (UserAuthHelper.checkIfLoggedIn(self)) { self.addToListVisible = true self.dimViewButton.hidden = false self.view.bringSubviewToFront(self.dimViewButton) self.view.bringSubviewToFront(self.addToListContainerView) UIView.animateWithDuration(0.4, animations: { // self.dimViewButton.alpha = 0.6 self.addToListContainerViewBottomSpace.constant = self.addToListContainerViewDestinationBottomSpace self.view.layoutIfNeeded() }) } } /** dismisses the add to list view from the screen if user touches outside or presses cancel/X button */ func dismissAddToListContainer() { UIView.animateWithDuration(0.4, animations: { // self.dimViewButton.alpha = 0 self.addToListContainerViewBottomSpace.constant = -(self.addToListContainerView.frame.size.height + self.tabBarController!.tabBar.bounds.size.height) self.view.layoutIfNeeded() }, completion: { finished in if (self.containerViewController.currentSegueIdentifier == "createAList") { self.containerViewController.swapViewControllers() } }) self.dimViewButton.hidden = true self.view.endEditing(true) self.addToListVisible = false } /** dismiss add to list container if user taps outside of it - parameter sender: */ @IBAction func tappedOutsideOfListContainer(sender: AnyObject) { if(self.canInjectData() == true){ self.dismissAddToListContainer() } } /** added to list popup fade out */ func fadeOutAddedToListPopup() { UIView.animateWithDuration(1, animations: { // self.addedToListPopup.alpha = 0 }) } /** added to list popup fade in */ func fadeInAddedToListPopup() { UIView.animateWithDuration(1, animations: { // self.addedToListPopup.alpha = 0.95 }, completion: { finished in }) } /** function to show grey popup on bottom of screen saying that the item was added to a particular list after tapping that list. includes fade in/out - parameter listName: - name of the list the item was added to */ func showPopup(listName: String) { // create attributed string let localizedString = NSLocalizedString("Product added to \(listName)!", comment: "") let string = localizedString as NSString let attributedString = NSMutableAttributedString(string: string as String) //Add attributes to two parts of the string attributedString.addAttributes([NSFontAttributeName: UIFont(name: "OpenSans", size: 14)!, NSForegroundColorAttributeName: UIColor.whiteColor()], range: string.rangeOfString("Product added to ")) attributedString.addAttributes([NSFontAttributeName: UIFont(name: "OpenSans-Semibold", size: 14)!, NSForegroundColorAttributeName: UIColor.whiteColor()], range: string.rangeOfString("\(listName)!")) //set label to be attributed string and present popup self.addedToListPopupLabel.attributedText = attributedString self.fadeInAddedToListPopup() _ = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("fadeOutAddedToListPopup"), userInfo: nil, repeats: false) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if (segue.identifier == "addToListContainer") { self.containerViewController = segue.destinationViewController as! AddToListContainerViewController } } /** This method is called when the tappedBackButton is pressed. - parameter sender: */ @IBAction func tappedBackButton(sender: AnyObject) { self.navigationController?.popViewControllerAnimated(true) } }
epl-1.0
Incipia/Elemental
Elemental/Classes/ViewControllers/ElementalPageViewController.swift
1
16981
// // ElementalPageViewController.swift // Pods // // Created by Leif Meyer on 7/3/17. // // import UIKit public protocol ElementalPageViewControllerDelegate: class { func elementalPageTransitionCompleted(index: Int, destinationIndex: Int, in viewController: ElementalPageViewController) } public protocol ElementalPage { func willAppear(inPageViewController pageViewController: ElementalPageViewController) func cancelAppear(inPageViewController pageViewController: ElementalPageViewController) func didAppear(inPageViewController pageViewController: ElementalPageViewController) func willDisappear(fromPageViewController pageViewController: ElementalPageViewController) func cancelDisappear(fromPageViewController pageViewController: ElementalPageViewController) func didDisappear(fromPageViewController pageViewController: ElementalPageViewController) } public extension ElementalPage { func willAppear(inPageViewController pageViewController: ElementalPageViewController) {} func cancelAppear(inPageViewController pageViewController: ElementalPageViewController) {} func didAppear(inPageViewController pageViewController: ElementalPageViewController) {} func willDisappear(fromPageViewController pageViewController: ElementalPageViewController) {} func cancelDisappear(fromPageViewController pageViewController: ElementalPageViewController) {} func didDisappear(fromPageViewController pageViewController: ElementalPageViewController) {} } open class ElementalPageViewController: UIPageViewController { // MARK: - Nested Types private class DataSource: NSObject, UIPageViewControllerDataSource { // MARK: - Private Properties fileprivate unowned let _owner: ElementalPageViewController // MARK: - Init init(owner: ElementalPageViewController) { _owner = owner } // MARK: - UIPageViewControllerDataSource public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let index = _owner.pages.index(of: viewController), index < _owner.pages.count - 1 else { return nil } return _owner.pages[index + 1] } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = _owner.pages.index(of: viewController), index > 0 else { return nil } return _owner.pages[index - 1] } } private class PageIndicatorDataSource: DataSource { // MARK: - UIPageViewControllerDataSource public func presentationCount(for pageViewController: UIPageViewController) -> Int { return _owner.pages.count } public func presentationIndex(for pageViewController: UIPageViewController) -> Int { return _owner.currentIndex } } fileprivate struct TransitionState { var nextViewController: UIViewController? var direction: UIPageViewControllerNavigationDirection = .forward } // MARK: - Private Properties private var _dataSource: DataSource! = nil fileprivate var _transitionState: TransitionState = TransitionState() // MARK: - Public Properties public fileprivate(set) var pages: [UIViewController] = [] { didSet { for (index, vc) in pages.enumerated() { vc.view.tag = index } } } public func setPages(_ pages: [UIViewController], currentIndex: Int, direction: UIPageViewControllerNavigationDirection, animated: Bool, completion: (() -> Void)? = nil) { self.pages = pages setCurrentIndex(currentIndex, direction: direction, animated: animated, completion: completion) } public private(set) var currentIndex: Int = 0 public func setCurrentIndex(_ currentIndex: Int, direction: UIPageViewControllerNavigationDirection, animated: Bool, completion: (() -> Void)? = nil) { self.currentIndex = currentIndex _transition(from: viewControllers?.first, to: pages.count > currentIndex ? pages[currentIndex] : nil, direction: direction, animated: animated, notifyDelegate: true, completion: completion) } public var showsPageIndicator: Bool = false { didSet { guard showsPageIndicator != oldValue else { return } _dataSource = showsPageIndicator ? PageIndicatorDataSource(owner: self) : DataSource(owner: self) dataSource = _dataSource } } public weak var elementalDelegate: ElementalPageViewControllerDelegate? public var pageCount: Int { return pages.count } // Subclass Hooks open func prepareForTransition(from currentPage: UIViewController?, to nextPage: UIViewController?, direction: UIPageViewControllerNavigationDirection, animated: Bool) { (currentPage as? ElementalPage)?.willDisappear(fromPageViewController: self) (nextPage as? ElementalPage)?.willAppear(inPageViewController: self) } open func cancelTransition(from currentPage: UIViewController?, to nextPage: UIViewController?, direction: UIPageViewControllerNavigationDirection, animated: Bool) { (currentPage as? ElementalPage)?.cancelDisappear(fromPageViewController: self) (nextPage as? ElementalPage)?.cancelAppear(inPageViewController: self) } open func recoverAfterTransition(from previousPage: UIViewController?, to currentPage: UIViewController?, direction: UIPageViewControllerNavigationDirection, animated: Bool) { (previousPage as? ElementalPage)?.didDisappear(fromPageViewController: self) (currentPage as? ElementalPage)?.didAppear(inPageViewController: self) } // MARK: - Init public convenience init(viewControllers: [UIViewController]) { self.init(transitionStyle: .scroll, navigationOrientation: .horizontal) // didSet will not be triggered if pages is set directly in an init method _setPages(viewControllers) } public required init?(coder: NSCoder) { super.init(coder: coder) _commonInit() } public override init(transitionStyle style: UIPageViewControllerTransitionStyle, navigationOrientation: UIPageViewControllerNavigationOrientation, options: [String : Any]? = nil) { super.init(transitionStyle: style, navigationOrientation: navigationOrientation, options: options) _commonInit() } private func _commonInit() { showsPageIndicator = true delegate = self dataSource = _dataSource } // MARK: - Life Cycle open override func viewDidLoad() { super.viewDidLoad() view.subviews.forEach { ($0 as? UIScrollView)?.delaysContentTouches = false } _transition(from: nil, to: pages.first, direction: .forward, animated: false, notifyDelegate: false, completion: nil) } // MARK: - Public public func navigate(_ direction: UIPageViewControllerNavigationDirection, completion: (() -> Void)? = nil) { guard let current = viewControllers?.first else { completion?(); return } var next: UIViewController? switch direction { case .forward: next = dataSource?.pageViewController(self, viewControllerAfter: current) case .reverse: next = dataSource?.pageViewController(self, viewControllerBefore: current) } guard let target = next else { completion?(); return } switch direction { case .forward: currentIndex = currentIndex + 1 case .reverse: currentIndex = currentIndex - 1 } _transition(from: current, to: next, direction: direction, animated: true, notifyDelegate: true, completion: completion) } public func navigate(to index: Int) { guard !pages.isEmpty, index != currentIndex else { return } let index = min(index, pages.count - 1) switch index { case 0..<currentIndex: let count = currentIndex - index for _ in 0..<count { navigate(.reverse) } case currentIndex+1..<pages.count: let count = index - currentIndex for _ in 0..<count { navigate(.forward) } default: break } } public func navigateToFirst() { navigate(to: 0) } // MARK: - Private private func _transition(from current: UIViewController?, to next: UIViewController?, direction: UIPageViewControllerNavigationDirection, animated: Bool, notifyDelegate: Bool, completion: (() -> Void)?) { guard current != next else { return } prepareForTransition(from: current, to: next, direction: direction, animated: true) let nextViewControllers = next == nil ? nil : [next!] setViewControllers(nextViewControllers, direction: direction, animated: true) { finished in self.recoverAfterTransition(from: current, to: next, direction: direction, animated: true) if let next = next, let index = self.pages.index(of: next) { // calling setViewControllers(direction:animated:) doesn't trigger the UIPageViewControllerDelegate method // didFinishAnimating, so we have to tell our elementalDelegate that a transition was just completed self.elementalDelegate?.elementalPageTransitionCompleted(index: index, destinationIndex: self.currentIndex, in: self) } completion?() } } fileprivate func _setPages(_ pages: [UIViewController]) { self.pages = pages } fileprivate func _setCurrentIndex(_ index: Int) { currentIndex = index } } extension ElementalPageViewController: UIPageViewControllerDelegate { public func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { let nextViewController = pendingViewControllers.first let direction: UIPageViewControllerNavigationDirection = { guard let nextIndex = nextViewController?.view.tag else { return .forward } return nextIndex < currentIndex ? .reverse : .forward }() if let transitionViewController = _transitionState.nextViewController { cancelTransition(from: pageViewController.viewControllers?.first, to: transitionViewController, direction: _transitionState.direction, animated: true) } _transitionState.nextViewController = nextViewController _transitionState.direction = direction prepareForTransition(from: pageViewController.viewControllers?.first, to: nextViewController, direction: direction, animated: true) } public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { guard let index = pageViewController.viewControllers?.first?.view.tag else { return } _setCurrentIndex(index) let previousViewController = previousViewControllers.first if previousViewController == pageViewController.viewControllers?.first, let transitionViewController = _transitionState.nextViewController { cancelTransition(from: previousViewController, to: transitionViewController, direction: _transitionState.direction, animated: true) } else { let direction: UIPageViewControllerNavigationDirection = { guard let previousIndex = previousViewController?.view.tag else { return .forward } return currentIndex < previousIndex ? .reverse : .forward }() recoverAfterTransition(from: previousViewController, to: pageViewController.viewControllers?.first, direction: direction, animated: true) } _transitionState.nextViewController = nil guard completed else { return } elementalDelegate?.elementalPageTransitionCompleted(index: index, destinationIndex: currentIndex, in: self) } } public protocol ElementalContextual { func enter(context: Any) func leave(context: Any) func changeContext(from oldContext: Any, to context: Any) } public extension ElementalContextual { func enter(context: Any) {} func leave(context: Any) {} func changeContext(from oldContext: Any, to context: Any) {} } open class ElementalContextPage<PageContext>: ElementalViewController, ElementalPage, ElementalContextual { // MARK: - Subclass Hooks open func enterOwn(context: PageContext) {} open func leaveOwn(context: PageContext) {} open func changeOwnContext(from oldContext: PageContext, to context: PageContext) {} // MARK: - ElementalContextual open func enter(context: Any) { guard let pageContext = context as? PageContext else { return } enterOwn(context: pageContext) } open func leave(context: Any) { guard let pageContext = context as? PageContext else { return } leaveOwn(context: pageContext) } open func changeContext(from oldContext: Any, to context: Any) { if let oldPageContext = oldContext as? PageContext, let pageContext = context as? PageContext { changeOwnContext(from: oldPageContext, to: pageContext) } else if let oldPageContext = oldContext as? PageContext { leaveOwn(context: oldPageContext) } else if let pageContext = context as? PageContext { enterOwn(context: pageContext) } } } open class ElementalContextPageViewController<Context>: ElementalPageViewController { // MARK: - Nested Types public typealias Page = ElementalContextPage<Context> // MARK: - Private Properties private var _transitionContexts: [UIViewController : (countDown: Int, context: Context?)] = [:] private var _transitionStateContext: Context? // MARK: - Public Properties public var context: Context? { didSet { if let oldContext = oldValue, let context = context { viewControllers?.forEach { ($0 as? ElementalContextual)?.changeContext(from: oldValue, to: oldContext) } } else if let oldContext = oldValue { viewControllers?.forEach { ($0 as? ElementalContextual)?.leave(context: oldContext) } } else if let context = context { viewControllers?.forEach { ($0 as? ElementalContextual)?.enter(context: context) } } } } // Subclass Hooks override open func prepareForTransition(from currentPage: UIViewController?, to nextPage: UIViewController?, direction: UIPageViewControllerNavigationDirection, animated: Bool) { super.prepareForTransition(from: currentPage, to: nextPage, direction: direction, animated: animated) if let currentPage = currentPage, currentPage is ElementalContextual { var transitionContext = _transitionContexts[currentPage] ?? (countDown: 0, context: context) transitionContext.countDown += 1 _transitionContexts[currentPage] = transitionContext } if let contextualNextPage = nextPage as? ElementalContextual, let nextPage = nextPage { if _transitionState.nextViewController == nextPage { _transitionStateContext = context } if let oldContext = _transitionContexts[nextPage]?.context, let context = context { contextualNextPage.changeContext(from: oldContext, to: context) } else if let oldContext = _transitionContexts[nextPage]?.context { contextualNextPage.leave(context: oldContext) } else if let context = context { contextualNextPage.enter(context: context) } _transitionContexts[nextPage]?.context = nil } } open override func cancelTransition(from currentPage: UIViewController?, to nextPage: UIViewController?, direction: UIPageViewControllerNavigationDirection, animated: Bool) { super.cancelTransition(from: currentPage, to: nextPage, direction: direction, animated: animated) guard let nextPage = nextPage as? ElementalContextual else { return } nextPage.leave(context: _transitionStateContext) _transitionStateContext = nil } override open func recoverAfterTransition(from previousPage: UIViewController?, to currentPage: UIViewController?, direction: UIPageViewControllerNavigationDirection, animated: Bool) { super.recoverAfterTransition(from: previousPage, to: currentPage, direction: direction, animated: animated) guard let previousPage = previousPage, var transitionContext = _transitionContexts[previousPage] else { return } transitionContext.countDown -= 1 if transitionContext.countDown == 0 { if let oldContext = transitionContext.context { (previousPage as? ElementalContextual)?.leave(context: oldContext) } _transitionContexts[previousPage] = nil } else { _transitionContexts[previousPage] = transitionContext } _transitionStateContext = nil } // MARK: - Init public convenience init(context: Context, viewControllers: [UIViewController]) { self.init(viewControllers: viewControllers) self.context = context } }
mit
kickstarter/ios-ksapi
KsApi/models/templates/User.StatsTemplates.swift
1
258
extension User.Stats { internal static let template = User.Stats( backedProjectsCount: nil, createdProjectsCount: nil, memberProjectsCount: nil, starredProjectsCount: nil, unansweredSurveysCount: nil, unreadMessagesCount: nil ) }
apache-2.0
laurentVeliscek/AudioKit
AudioKit/macOS/AudioKit for macOS/User Interface/AKResourceAudioFileLoaderView.swift
2
6411
// // AKResourceAudioFileLoaderView.swift // AudioKit for macOS // // Created by Aurelius Prochazka on 7/30/16. // Copyright © 2016 AudioKit. All rights reserved. // import Cocoa public class AKResourcesAudioFileLoaderView: NSView { var player: AKAudioPlayer? var stopOuterPath = NSBezierPath() var playOuterPath = NSBezierPath() var upOuterPath = NSBezierPath() var downOuterPath = NSBezierPath() var currentIndex = 0 var titles = [String]() override public func mouseDown(theEvent: NSEvent) { var isFileChanged = false let isPlayerPlaying = player!.isPlaying let touchLocation = convertPoint(theEvent.locationInWindow, fromView: nil) if stopOuterPath.containsPoint(touchLocation) { player?.stop() } if playOuterPath.containsPoint(touchLocation) { player?.play() } if upOuterPath.containsPoint(touchLocation) { currentIndex -= 1 isFileChanged = true } if downOuterPath.containsPoint(touchLocation) { currentIndex += 1 isFileChanged = true } if currentIndex < 0 { currentIndex = titles.count - 1 } if currentIndex >= titles.count { currentIndex = 0 } if isFileChanged { player?.stop() let filename = titles[currentIndex] let file = try? AKAudioFile(readFileName: "\(filename)", baseDir: .Resources) do { try player?.replaceFile(file!) } catch { Swift.print("Could not replace file") } if isPlayerPlaying { player?.play() } } needsDisplay = true } public convenience init(player: AKAudioPlayer, filenames: [String], frame: CGRect = CGRect(x: 0, y: 0, width: 440, height: 60)) { self.init(frame: frame) self.player = player self.titles = filenames } func drawAudioFileLoader(sliderColor sliderColor: NSColor = NSColor(calibratedRed: 1, green: 0, blue: 0.062, alpha: 1), fileName: String = "None") { //// General Declarations let _ = unsafeBitCast(NSGraphicsContext.currentContext()!.graphicsPort, CGContext.self) //// Color Declarations let backgroundColor = NSColor(calibratedRed: 0.835, green: 0.842, blue: 0.836, alpha: 0.925) let color = NSColor(calibratedRed: 0.029, green: 1, blue: 0, alpha: 1) let dark = NSColor(calibratedRed: 0, green: 0, blue: 0, alpha: 1) //// background Drawing let backgroundPath = NSBezierPath(rect: NSMakeRect(0, 0, 440, 60)) backgroundColor.setFill() backgroundPath.fill() //// stopButton //// stopOuter Drawing stopOuterPath = NSBezierPath(rect: NSMakeRect(0, 0, 60, 60)) sliderColor.setFill() stopOuterPath.fill() //// stopInner Drawing let stopInnerPath = NSBezierPath(rect: NSMakeRect(15, 15, 30, 30)) dark.setFill() stopInnerPath.fill() //// playButton //// playOuter Drawing playOuterPath = NSBezierPath(rect: NSMakeRect(60, 0, 60, 60)) color.setFill() playOuterPath.fill() //// playInner Drawing let playInnerPath = NSBezierPath() playInnerPath.moveToPoint(NSMakePoint(76.5, 45)) playInnerPath.lineToPoint(NSMakePoint(76.5, 15)) playInnerPath.lineToPoint(NSMakePoint(106.5, 30)) dark.setFill() playInnerPath.fill() //// upButton //// upOuter Drawing upOuterPath = NSBezierPath(rect: NSMakeRect(381, 30, 59, 30)) backgroundColor.setFill() upOuterPath.fill() //// upInner Drawing let upInnerPath = NSBezierPath() upInnerPath.moveToPoint(NSMakePoint(395.75, 37.5)) upInnerPath.lineToPoint(NSMakePoint(425.25, 37.5)) upInnerPath.lineToPoint(NSMakePoint(410.5, 52.5)) upInnerPath.lineToPoint(NSMakePoint(410.5, 52.5)) upInnerPath.lineToPoint(NSMakePoint(395.75, 37.5)) upInnerPath.closePath() dark.setFill() upInnerPath.fill() //// downButton //// downOuter Drawing downOuterPath = NSBezierPath(rect: NSMakeRect(381, 0, 59, 30)) backgroundColor.setFill() downOuterPath.fill() //// downInner Drawing let downInnerPath = NSBezierPath() downInnerPath.moveToPoint(NSMakePoint(410.5, 7.5)) downInnerPath.lineToPoint(NSMakePoint(410.5, 7.5)) downInnerPath.lineToPoint(NSMakePoint(425.25, 22.5)) downInnerPath.lineToPoint(NSMakePoint(395.75, 22.5)) downInnerPath.lineToPoint(NSMakePoint(410.5, 7.5)) downInnerPath.closePath() dark.setFill() downInnerPath.fill() //// nameLabel Drawing let nameLabelRect = NSMakeRect(120, 0, 320, 60) let nameLabelStyle = NSMutableParagraphStyle() nameLabelStyle.alignment = .Left let nameLabelFontAttributes = [NSFontAttributeName: NSFont(name: "HelveticaNeue", size: 24)!, NSForegroundColorAttributeName: NSColor.blackColor(), NSParagraphStyleAttributeName: nameLabelStyle] let nameLabelInset: CGRect = NSInsetRect(nameLabelRect, 10, 0) let nameLabelTextHeight: CGFloat = NSString(string: fileName).boundingRectWithSize(NSMakeSize(nameLabelInset.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: nameLabelFontAttributes).size.height let nameLabelTextRect: NSRect = NSMakeRect(nameLabelInset.minX, nameLabelInset.minY + (nameLabelInset.height - nameLabelTextHeight) / 2, nameLabelInset.width, nameLabelTextHeight) NSGraphicsContext.saveGraphicsState() NSRectClip(nameLabelInset) NSString(string: fileName).drawInRect(NSOffsetRect(nameLabelTextRect, 0, 0), withAttributes: nameLabelFontAttributes) NSGraphicsContext.restoreGraphicsState() } override public func drawRect(rect: CGRect) { drawAudioFileLoader(fileName: titles[currentIndex]) } }
mit
mozilla-mobile/firefox-ios
Tests/SyncTests/InfoTests.swift
2
2367
// 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 SwiftyJSON @testable import Sync import XCTest class InfoTests: XCTestCase { func testSame() { let empty = JSON(parseJSON: "{}") let oneA = JSON(parseJSON: "{\"foo\": 1234.0, \"bar\": 456.12}") let oneB = JSON(parseJSON: "{\"bar\": 456.12, \"foo\": 1234.0}") let twoA = JSON(parseJSON: "{\"bar\": 456.12}") let twoB = JSON(parseJSON: "{\"foo\": 1234.0}") let iEmpty = InfoCollections.fromJSON(empty)! let iOneA = InfoCollections.fromJSON(oneA)! let iOneB = InfoCollections.fromJSON(oneB)! let iTwoA = InfoCollections.fromJSON(twoA)! let iTwoB = InfoCollections.fromJSON(twoB)! XCTAssertTrue(iEmpty.same(iEmpty, collections: nil)) XCTAssertTrue(iEmpty.same(iEmpty, collections: [])) XCTAssertTrue(iEmpty.same(iEmpty, collections: ["anything"])) XCTAssertTrue(iEmpty.same(iOneA, collections: [])) XCTAssertTrue(iEmpty.same(iOneA, collections: ["anything"])) XCTAssertTrue(iOneA.same(iEmpty, collections: [])) XCTAssertTrue(iOneA.same(iEmpty, collections: ["anything"])) XCTAssertFalse(iEmpty.same(iOneA, collections: ["foo"])) XCTAssertFalse(iOneA.same(iEmpty, collections: ["foo"])) XCTAssertFalse(iEmpty.same(iOneA, collections: nil)) XCTAssertFalse(iOneA.same(iEmpty, collections: nil)) XCTAssertTrue(iOneA.same(iOneA, collections: nil)) XCTAssertTrue(iOneA.same(iOneA, collections: ["foo", "bar", "baz"])) XCTAssertTrue(iOneA.same(iOneB, collections: ["foo", "bar", "baz"])) XCTAssertTrue(iOneB.same(iOneA, collections: ["foo", "bar", "baz"])) XCTAssertFalse(iTwoA.same(iOneA, collections: nil)) XCTAssertTrue(iTwoA.same(iOneA, collections: ["bar", "baz"])) XCTAssertTrue(iOneA.same(iTwoA, collections: ["bar", "baz"])) XCTAssertTrue(iTwoB.same(iOneA, collections: ["foo", "baz"])) XCTAssertFalse(iTwoA.same(iTwoB, collections: nil)) XCTAssertFalse(iTwoA.same(iTwoB, collections: ["foo"])) XCTAssertFalse(iTwoA.same(iTwoB, collections: ["bar"])) } }
mpl-2.0
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/Utility/MessageToolboxDataSource.swift
1
12273
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit import WireDataModel import WireCommonComponents /// The different contents that can be displayed inside the message toolbox. enum MessageToolboxContent: Equatable { /// Display buttons to let the user resend the message. case sendFailure(NSAttributedString) /// Display the list of reactions. case reactions(NSAttributedString) /// Display list of calls case callList(NSAttributedString) /// Display the message details (timestamp and/or status and/or countdown). case details(timestamp: NSAttributedString?, status: NSAttributedString?, countdown: NSAttributedString?) } extension MessageToolboxContent: Comparable { /// Returns whether one content is located above or below the other. /// This is used to determine from which direction to slide, so that we can keep /// the animations logical. static func < (lhs: MessageToolboxContent, rhs: MessageToolboxContent) -> Bool { switch (lhs, rhs) { case (.sendFailure, _): return true case (.details, .reactions): return true default: return false } } } // MARK: - Data Source /** * An object that determines what content to display for the given message. */ class MessageToolboxDataSource { /// The displayed message. let message: ZMConversationMessage /// The content to display for the message. private(set) var content: MessageToolboxContent // MARK: - Formatting Properties private let statusTextColor = SemanticColors.Label.textMessageDetails private let statusFont = FontSpec.smallRegularFont.font! private static let ephemeralTimeFormatter = EphemeralTimeoutFormatter() private var attributes: [NSAttributedString.Key: AnyObject] { return [.font: statusFont, .foregroundColor: statusTextColor] } private static let separator = " " + String.MessageToolbox.middleDot + " " // MARK: - Initialization /// Creates a toolbox data source for the given message. init(message: ZMConversationMessage) { self.message = message self.content = .details(timestamp: nil, status: nil, countdown: nil) } // MARK: - Content /** * Updates the contents of the message toolbox. * - parameter forceShowTimestamp: Whether the timestamp should be shown, even if a state * with a higher priority has been calculated (ex: likes). * - parameter widthConstraint: The width available to rend the toolbox contents. */ func updateContent(forceShowTimestamp: Bool, widthConstraint: CGFloat) -> SlideDirection? { // Compute the state let likers = message.likers let isSentBySelfUser = message.senderUser?.isSelfUser == true let failedToSend = message.deliveryState == .failedToSend && isSentBySelfUser let showTimestamp = forceShowTimestamp || likers.isEmpty let previousContent = self.content // Determine the content by priority // 1) Call list if message.systemMessageData?.systemMessageType == .performedCall || message.systemMessageData?.systemMessageType == .missedCall { content = .callList(makeCallList()) } // 2) Failed to send else if failedToSend && isSentBySelfUser { let detailsString = "content.system.failedtosend_message_timestamp".localized && attributes content = .sendFailure(detailsString) } // 3) Likers else if !showTimestamp { let text = makeReactionsLabel(with: message.likers, widthConstraint: widthConstraint) content = .reactions(text) } // 4) Timestamp else { let (timestamp, status, countdown) = makeDetailsString() content = .details(timestamp: timestamp, status: status, countdown: countdown) } // Only perform the changes if the content did change. guard previousContent != content else { return nil } return previousContent < content ? .up : .down } // MARK: - Reactions /// Creates a label that display the likers of the message. private func makeReactionsLabel(with likers: [UserType], widthConstraint: CGFloat) -> NSAttributedString { let likers = message.likers // If there is only one liker, always display the name, even if the width doesn't fit if likers.count == 1 { return (likers[0].name ?? "") && attributes } // Create the list of likers let likersNames = likers.compactMap(\.name).joined(separator: ", ") let likersNamesAttributedString = likersNames && attributes // Check if the list of likers fits on the screen. Otheriwse, show the summary let constrainedSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) let labelSize = likersNamesAttributedString.boundingRect(with: constrainedSize, options: [.usesFontLeading, .usesLineFragmentOrigin], context: nil) if likers.count >= 3 || labelSize.width > widthConstraint { let likersCount = String(format: "participants.people.count".localized, likers.count) return likersCount && attributes } else { return likersNamesAttributedString } } // MARK: - Details Text /// Create a timestamp list for all calls associated with a call system message private func makeCallList() -> NSAttributedString { if let childMessages = message.systemMessageData?.childMessages, !childMessages.isEmpty, let timestamp = timestampString(message) { let childrenTimestamps = childMessages.compactMap { $0 as? ZMConversationMessage }.sorted { left, right in left.serverTimestamp < right.serverTimestamp }.compactMap(timestampString) let finalText = childrenTimestamps.reduce(timestamp) { (text, current) in return "\(text)\n\(current)" } return finalText && attributes } else { return timestampString(message) ?? "-" && attributes } } /// Creates a label that display the status of the message. private func makeDetailsString() -> (NSAttributedString?, NSAttributedString?, NSAttributedString?) { let deliveryStateString: NSAttributedString? = selfStatus(for: message) let countdownStatus = makeEphemeralCountdown() if let timestampString = self.timestampString(message), message.isSent { if let deliveryStateString = deliveryStateString, message.shouldShowDeliveryState { return (timestampString && attributes, deliveryStateString, countdownStatus) } else { return (timestampString && attributes, nil, countdownStatus) } } else { return (nil, deliveryStateString, countdownStatus) } } private func makeEphemeralCountdown() -> NSAttributedString? { let showDestructionTimer = message.isEphemeral && !message.isObfuscated && nil != message.destructionDate && message.deliveryState != .pending if let destructionDate = message.destructionDate, showDestructionTimer { let remaining = destructionDate.timeIntervalSinceNow + 1 // We need to add one second to start with the correct value if remaining > 0 { if let string = MessageToolboxDataSource.ephemeralTimeFormatter.string(from: remaining) { return string && attributes } } else if message.isAudio { // do nothing, audio messages are allowed to extend the timer // past the destruction date. } } return nil } /// Returns the status for the sender of the message. fileprivate func selfStatus(for message: ZMConversationMessage) -> NSAttributedString? { guard let sender = message.senderUser, sender.isSelfUser else { return nil } var deliveryStateString: String switch message.deliveryState { case .pending: deliveryStateString = "content.system.pending_message_timestamp".localized case .read: return selfStatusForReadDeliveryState(for: message) case .delivered: deliveryStateString = "content.system.message_delivered_timestamp".localized case .sent: deliveryStateString = "content.system.message_sent_timestamp".localized case .invalid, .failedToSend: return nil } return NSAttributedString(string: deliveryStateString) && attributes } private func seenTextAttachment() -> NSTextAttachment { let imageIcon = NSTextAttachment.textAttachment(for: .eye, with: statusTextColor, verticalCorrection: -1) imageIcon.accessibilityLabel = "seen" return imageIcon } /// Creates the status for the read receipts. fileprivate func selfStatusForReadDeliveryState(for message: ZMConversationMessage) -> NSAttributedString? { guard let conversationType = message.conversationLike?.conversationType else {return nil} switch conversationType { case .group: let attributes: [NSAttributedString.Key: AnyObject] = [ .font: UIFont.monospacedDigitSystemFont(ofSize: 10, weight: .semibold), .foregroundColor: statusTextColor ] let imageIcon = seenTextAttachment() let attributedString = NSAttributedString(attachment: imageIcon) + " \(message.readReceipts.count)" && attributes attributedString.accessibilityLabel = (imageIcon.accessibilityLabel ?? "") + " \(message.readReceipts.count)" return attributedString case .oneOnOne: guard let timestamp = message.readReceipts.first?.serverTimestamp else { return nil } let imageIcon = seenTextAttachment() let timestampString = message.formattedDate(timestamp) let attributedString = NSAttributedString(attachment: imageIcon) + " " + timestampString && attributes attributedString.accessibilityLabel = (imageIcon.accessibilityLabel ?? "") + " " + timestampString return attributedString default: return nil } } /// Creates the timestamp text. fileprivate func timestampString(_ message: ZMConversationMessage) -> String? { let timestampString: String? if let editedTimeString = message.formattedEditedDate() { timestampString = String(format: "content.system.edited_message_prefix_timestamp".localized, editedTimeString) } else if let dateTimeString = message.formattedReceivedDate() { if let systemMessage = message as? ZMSystemMessage, systemMessage.systemMessageType == .messageDeletedForEveryone { timestampString = String(format: "content.system.deleted_message_prefix_timestamp".localized, dateTimeString) } else if let durationString = message.systemMessageData?.callDurationString() { timestampString = dateTimeString + MessageToolboxDataSource.separator + durationString } else { timestampString = dateTimeString } } else { timestampString = .none } return timestampString } }
gpl-3.0
JadenGeller/Helium
Helium/Helium/AppDelegate.swift
1
1836
// // AppDelegate.swift // Helium // // Created by Jaden Geller on 4/9/15. // Copyright (c) 2015 Jaden Geller. All rights reserved. // import Cocoa class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate { func applicationWillFinishLaunching(_ notification: Notification) { NSAppleEventManager.shared().setEventHandler( self, andSelector: #selector(AppDelegate.handleURLEvent(_:withReply:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL) ) UserDefaults.standard.set(false, forKey: "NSFullScreenMenuItemEverywhere") } let windowControllerManager = WindowControllerManager() @objc func showNewWindow(_ sender: Any?) { windowControllerManager.newWindow().showWindow(self) } //MARK: - handleURLEvent // Called when the App opened via URL. @objc func handleURLEvent(_ event: NSAppleEventDescriptor, withReply reply: NSAppleEventDescriptor) { guard let keyDirectObject = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject)), let urlString = keyDirectObject.stringValue, let urlObject = URL(string: String(urlString[urlString.index(urlString.startIndex, offsetBy: 9)..<urlString.endIndex])) else { return print("No valid URL to handle") } NotificationCenter.default.post(name: NSNotification.Name(rawValue: "HeliumLoadURL"), object: urlObject) } func applicationOpenUntitledFile(_ sender: NSApplication) -> Bool { showNewWindow(self) return true } func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { return sender.windows.isEmpty } }
mit
gregomni/swift
test/AutoDiff/Sema/derivative_attr_type_checking.swift
7
47023
// RUN: %target-swift-frontend-typecheck -verify -disable-availability-checking %s // RUN: %target-swift-frontend-typecheck -enable-testing -verify -disable-availability-checking %s // Swift.AdditiveArithmetic:3:17: note: cannot yet register derivative default implementation for protocol requirements import _Differentiation // Dummy `Differentiable`-conforming type. struct DummyTangentVector: Differentiable & AdditiveArithmetic { static var zero: Self { Self() } static func + (_: Self, _: Self) -> Self { Self() } static func - (_: Self, _: Self) -> Self { Self() } typealias TangentVector = Self } // Test top-level functions. func id(_ x: Float) -> Float { return x } @derivative(of: id) func jvpId(x: Float) -> (value: Float, differential: (Float) -> (Float)) { return (x, { $0 }) } @derivative(of: id, wrt: x) func vjpIdExplicitWrt(x: Float) -> (value: Float, pullback: (Float) -> Float) { return (x, { $0 }) } func generic<T: Differentiable>(_ x: T, _ y: T) -> T { return x } @derivative(of: generic) func jvpGeneric<T: Differentiable>(x: T, y: T) -> ( value: T, differential: (T.TangentVector, T.TangentVector) -> T.TangentVector ) { return (x, { $0 + $1 }) } @derivative(of: generic) func vjpGenericExtraGenericRequirements<T: Differentiable & FloatingPoint>( x: T, y: T ) -> (value: T, pullback: (T) -> (T, T)) where T == T.TangentVector { return (x, { ($0, $0) }) } // Test `wrt` parameter clauses. func add(x: Float, y: Float) -> Float { return x + y } @derivative(of: add, wrt: x) // ok func vjpAddWrtX(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float)) { return (x + y, { $0 }) } @derivative(of: add, wrt: (x, y)) // ok func vjpAddWrtXY(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x + y, { ($0, $0) }) } // Test index-based `wrt` parameters. func subtract(x: Float, y: Float) -> Float { return x - y } @derivative(of: subtract, wrt: (0, y)) // ok func vjpSubtractWrt0Y(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x - y, { ($0, $0) }) } @derivative(of: subtract, wrt: (1)) // ok func vjpSubtractWrt1(x: Float, y: Float) -> (value: Float, pullback: (Float) -> Float) { return (x - y, { $0 }) } // Test invalid original function. // expected-error @+1 {{cannot find 'nonexistentFunction' in scope}} @derivative(of: nonexistentFunction) func vjpOriginalFunctionNotFound(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } struct Q { } @derivative(of: remainder(_:_:)) // expected-error {{cannot find 'remainder' in scope}} // expected-error @+1 {{generic parameter 'T' is not used in function signature}} func _vjpRemainder<T: FloatingPoint>(_ x: Q, _ y: Q) -> ( value: Q, pullback: (Q) -> (Q, Q) ) { fatalError() } // Test `@derivative` attribute where `value:` result does not conform to `Differentiable`. // Invalid original function should be diagnosed first. // expected-error @+1 {{cannot find 'nonexistentFunction' in scope}} @derivative(of: nonexistentFunction) func vjpOriginalFunctionNotFound2(_ x: Float) -> (value: Int, pullback: (Float) -> Float) { fatalError() } // Test incorrect `@derivative` declaration type. // expected-note @+2 {{'incorrectDerivativeType' defined here}} // expected-note @+1 {{candidate global function does not have expected type '(Int) -> Int'}} func incorrectDerivativeType(_ x: Float) -> Float { return x } // expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; first element must have label 'value:' and second element must have label 'pullback:' or 'differential:'}} @derivative(of: incorrectDerivativeType) func jvpResultIncorrect(x: Float) -> Float { return x } // expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; first element must have label 'value:'}} @derivative(of: incorrectDerivativeType) func vjpResultIncorrectFirstLabel(x: Float) -> (Float, (Float) -> Float) { return (x, { $0 }) } // expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; second element must have label 'pullback:' or 'differential:'}} @derivative(of: incorrectDerivativeType) func vjpResultIncorrectSecondLabel(x: Float) -> (value: Float, (Float) -> Float) { return (x, { $0 }) } // expected-error @+1 {{referenced declaration 'incorrectDerivativeType' could not be resolved}} @derivative(of: incorrectDerivativeType) func vjpResultNotDifferentiable(x: Int) -> ( value: Int, pullback: (Int) -> Int ) { return (x, { $0 }) } // expected-error @+2 {{function result's 'pullback' type does not match 'incorrectDerivativeType'}} // expected-note @+3 {{'pullback' does not have expected type '(Float.TangentVector) -> Float.TangentVector' (aka '(Float) -> Float')}} @derivative(of: incorrectDerivativeType) func vjpResultIncorrectPullbackType(x: Float) -> ( value: Float, pullback: (Double) -> Double ) { return (x, { $0 }) } // Test invalid `wrt:` differentiation parameters. func invalidWrtParam(_ x: Float, _ y: Float) -> Float { return x } // expected-error @+1 {{unknown parameter name 'z'}} @derivative(of: add, wrt: z) func vjpUnknownParam(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float)) { return (x + y, { $0 }) } // expected-error @+1 {{parameters must be specified in original order}} @derivative(of: invalidWrtParam, wrt: (y, x)) func vjpParamOrderNotIncreasing(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x + y, { ($0, $0) }) } // expected-error @+1 {{'self' parameter is only applicable to instance methods}} @derivative(of: invalidWrtParam, wrt: self) func vjpInvalidSelfParam(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x + y, { ($0, $0) }) } // expected-error @+1 {{parameter index is larger than total number of parameters}} @derivative(of: invalidWrtParam, wrt: 2) func vjpSubtractWrt2(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x - y, { ($0, $0) }) } // expected-error @+1 {{parameters must be specified in original order}} @derivative(of: invalidWrtParam, wrt: (1, x)) func vjpSubtractWrt1x(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x - y, { ($0, $0) }) } // expected-error @+1 {{parameters must be specified in original order}} @derivative(of: invalidWrtParam, wrt: (1, 0)) func vjpSubtractWrt10(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x - y, { ($0, $0) }) } func noParameters() -> Float { return 1 } // expected-error @+1 {{'vjpNoParameters()' has no parameters to differentiate with respect to}} @derivative(of: noParameters) func vjpNoParameters() -> (value: Float, pullback: (Float) -> Float) { return (1, { $0 }) } func noDifferentiableParameters(x: Int) -> Float { return 1 } // expected-error @+1 {{no differentiation parameters could be inferred; must differentiate with respect to at least one parameter conforming to 'Differentiable'}} @derivative(of: noDifferentiableParameters) func vjpNoDifferentiableParameters(x: Int) -> ( value: Float, pullback: (Float) -> Int ) { return (1, { _ in 0 }) } func functionParameter(_ fn: (Float) -> Float) -> Float { return fn(1) } // expected-error @+1 {{can only differentiate with respect to parameters that conform to 'Differentiable', but '(Float) -> Float' does not conform to 'Differentiable'}} @derivative(of: functionParameter, wrt: fn) func vjpFunctionParameter(_ fn: (Float) -> Float) -> ( value: Float, pullback: (Float) -> Float ) { return (functionParameter(fn), { $0 }) } // Test static methods. protocol StaticMethod: Differentiable { static func foo(_ x: Float) -> Float static func generic<T: Differentiable>(_ x: T) -> T } extension StaticMethod { static func foo(_ x: Float) -> Float { x } static func generic<T: Differentiable>(_ x: T) -> T { x } } extension StaticMethod { @derivative(of: foo) static func jvpFoo(x: Float) -> (value: Float, differential: (Float) -> Float) { return (x, { $0 }) } // Test qualified declaration name. @derivative(of: StaticMethod.foo) static func vjpFoo(x: Float) -> (value: Float, pullback: (Float) -> Float) { return (x, { $0 }) } @derivative(of: generic) static func vjpGeneric<T: Differentiable>(_ x: T) -> ( value: T, pullback: (T.TangentVector) -> (T.TangentVector) ) { return (x, { $0 }) } // expected-error @+1 {{'self' parameter is only applicable to instance methods}} @derivative(of: foo, wrt: (self, x)) static func vjpFooWrtSelf(x: Float) -> (value: Float, pullback: (Float) -> Float) { return (x, { $0 }) } } // Test instance methods. protocol InstanceMethod: Differentiable { func foo(_ x: Self) -> Self func generic<T: Differentiable>(_ x: T) -> Self } extension InstanceMethod { // expected-note @+1 {{'foo' defined here}} func foo(_ x: Self) -> Self { x } // expected-note @+1 {{'generic' defined here}} func generic<T: Differentiable>(_ x: T) -> Self { self } } extension InstanceMethod { @derivative(of: foo) func jvpFoo(x: Self) -> ( value: Self, differential: (TangentVector, TangentVector) -> (TangentVector) ) { return (x, { $0 + $1 }) } // Test qualified declaration name. @derivative(of: InstanceMethod.foo, wrt: x) func jvpFooWrtX(x: Self) -> ( value: Self, differential: (TangentVector) -> (TangentVector) ) { return (x, { $0 }) } @derivative(of: generic) func vjpGeneric<T: Differentiable>(_ x: T) -> ( value: Self, pullback: (TangentVector) -> (TangentVector, T.TangentVector) ) { return (self, { ($0, .zero) }) } @derivative(of: generic, wrt: (self, x)) func jvpGenericWrt<T: Differentiable>(_ x: T) -> (value: Self, differential: (TangentVector, T.TangentVector) -> TangentVector) { return (self, { dself, dx in dself }) } // expected-error @+1 {{'self' parameter must come first in the parameter list}} @derivative(of: generic, wrt: (x, self)) func jvpGenericWrtSelf<T: Differentiable>(_ x: T) -> (value: Self, differential: (TangentVector, T.TangentVector) -> TangentVector) { return (self, { dself, dx in dself }) } } extension InstanceMethod { // If `Self` conforms to `Differentiable`, then `Self` is inferred to be a differentiation parameter. // expected-error @+2 {{function result's 'pullback' type does not match 'foo'}} // expected-note @+3 {{'pullback' does not have expected type '(Self.TangentVector) -> (Self.TangentVector, Self.TangentVector)'}} @derivative(of: foo) func vjpFoo(x: Self) -> ( value: Self, pullback: (TangentVector) -> TangentVector ) { return (x, { $0 }) } // If `Self` conforms to `Differentiable`, then `Self` is inferred to be a differentiation parameter. // expected-error @+2 {{function result's 'pullback' type does not match 'generic'}} // expected-note @+3 {{'pullback' does not have expected type '(Self.TangentVector) -> (Self.TangentVector, T.TangentVector)'}} @derivative(of: generic) func vjpGeneric<T: Differentiable>(_ x: T) -> ( value: Self, pullback: (TangentVector) -> T.TangentVector ) { return (self, { _ in .zero }) } } // Test `@derivative` declaration with more constrained generic signature. func req1<T>(_ x: T) -> T { return x } @derivative(of: req1) func vjpExtraConformanceConstraint<T: Differentiable>(_ x: T) -> ( value: T, pullback: (T.TangentVector) -> T.TangentVector ) { return (x, { $0 }) } func req2<T, U>(_ x: T, _ y: U) -> T { return x } @derivative(of: req2) func vjpExtraConformanceConstraints<T: Differentiable, U: Differentiable>( _ x: T, _ y: U) -> ( value: T, pullback: (T) -> (T, U) ) where T == T.TangentVector, U == U.TangentVector, T: CustomStringConvertible { return (x, { ($0, .zero) }) } // Test `@derivative` declaration with extra same-type requirements. func req3<T>(_ x: T) -> T { return x } @derivative(of: req3) func vjpSameTypeRequirementsGenericParametersAllConcrete<T>(_ x: T) -> ( value: T, pullback: (T.TangentVector) -> T.TangentVector ) where T: Differentiable, T.TangentVector == Float { return (x, { $0 }) } struct Wrapper<T: Equatable>: Equatable { var x: T init(_ x: T) { self.x = x } } extension Wrapper: AdditiveArithmetic where T: AdditiveArithmetic { static var zero: Self { .init(.zero) } static func + (lhs: Self, rhs: Self) -> Self { .init(lhs.x + rhs.x) } static func - (lhs: Self, rhs: Self) -> Self { .init(lhs.x - rhs.x) } } extension Wrapper: Differentiable where T: Differentiable, T == T.TangentVector { typealias TangentVector = Wrapper<T.TangentVector> } extension Wrapper where T: Differentiable, T == T.TangentVector { @derivative(of: init(_:)) static func vjpInit(_ x: T) -> (value: Self, pullback: (Wrapper<T>.TangentVector) -> (T)) { fatalError() } } // Test class methods. class Super { @differentiable(reverse) // expected-note @+1 {{candidate instance method is not defined in the current type context}} func foo(_ x: Float) -> Float { return x } @derivative(of: foo) func vjpFoo(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { return (foo(x), { v in v }) } } class Sub: Super { // TODO(TF-649): Enable `@derivative` to override derivatives for original // declaration defined in superclass. // expected-error @+1 {{referenced declaration 'foo' could not be resolved}} @derivative(of: foo) override func vjpFoo(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { return (foo(x), { v in v }) } } // Test non-`func` original declarations. struct Struct<T> { var x: T } extension Struct: Equatable where T: Equatable {} extension Struct: Differentiable & AdditiveArithmetic where T: Differentiable & AdditiveArithmetic { static var zero: Self { fatalError() } static func + (lhs: Self, rhs: Self) -> Self { fatalError() } static func - (lhs: Self, rhs: Self) -> Self { fatalError() } typealias TangentVector = Struct<T.TangentVector> mutating func move(by offset: TangentVector) { x.move(by: offset.x) } } class Class<T> { var x: T init(_ x: T) { self.x = x } } extension Class: Differentiable where T: Differentiable {} // Test computed properties. extension Struct { var computedProperty: T { get { x } set { x = newValue } _modify { yield &x } } } extension Struct where T: Differentiable & AdditiveArithmetic { @derivative(of: computedProperty) func vjpProperty() -> (value: T, pullback: (T.TangentVector) -> TangentVector) { return (x, { v in .init(x: v) }) } @derivative(of: computedProperty.get) func jvpProperty() -> (value: T, differential: (TangentVector) -> T.TangentVector) { fatalError() } @derivative(of: computedProperty.set) mutating func vjpPropertySetter(_ newValue: T) -> ( value: (), pullback: (inout TangentVector) -> T.TangentVector ) { fatalError() } // expected-error @+1 {{cannot register derivative for _modify accessor}} @derivative(of: computedProperty._modify) mutating func vjpPropertyModify(_ newValue: T) -> ( value: (), pullback: (inout TangentVector) -> T.TangentVector ) { fatalError() } } // Test initializers. extension Struct { init(_ x: Float) {} init(_ x: T, y: Float) {} } extension Struct where T: Differentiable & AdditiveArithmetic { @derivative(of: init) static func vjpInit(_ x: Float) -> ( value: Struct, pullback: (TangentVector) -> Float ) { return (.init(x), { _ in .zero }) } @derivative(of: init(_:y:)) static func vjpInit2(_ x: T, _ y: Float) -> ( value: Struct, pullback: (TangentVector) -> (T.TangentVector, Float) ) { return (.init(x, y: y), { _ in (.zero, .zero) }) } } // Test subscripts. extension Struct { subscript() -> Float { get { 1 } set {} } subscript(float float: Float) -> Float { get { 1 } set {} } // expected-note @+1 {{candidate subscript does not have a setter}} subscript<T: Differentiable>(x: T) -> T { x } } extension Struct where T: Differentiable & AdditiveArithmetic { @derivative(of: subscript.get) func vjpSubscriptGetter() -> (value: Float, pullback: (Float) -> TangentVector) { return (1, { _ in .zero }) } // expected-error @+2 {{a derivative already exists for '_'}} // expected-note @-6 {{other attribute declared here}} @derivative(of: subscript) func vjpSubscript() -> (value: Float, pullback: (Float) -> TangentVector) { return (1, { _ in .zero }) } @derivative(of: subscript().get) func jvpSubscriptGetter() -> (value: Float, differential: (TangentVector) -> Float) { return (1, { _ in .zero }) } @derivative(of: subscript(float:).get, wrt: self) func vjpSubscriptLabeledGetter(float: Float) -> (value: Float, pullback: (Float) -> TangentVector) { return (1, { _ in .zero }) } // expected-error @+2 {{a derivative already exists for '_'}} // expected-note @-6 {{other attribute declared here}} @derivative(of: subscript(float:), wrt: self) func vjpSubscriptLabeled(float: Float) -> (value: Float, pullback: (Float) -> TangentVector) { return (1, { _ in .zero }) } @derivative(of: subscript(float:).get) func jvpSubscriptLabeledGetter(float: Float) -> (value: Float, differential: (TangentVector, Float) -> Float) { return (1, { (_,_) in 1}) } @derivative(of: subscript(_:).get, wrt: self) func vjpSubscriptGenericGetter<T: Differentiable>(x: T) -> (value: T, pullback: (T.TangentVector) -> TangentVector) { return (x, { _ in .zero }) } // expected-error @+2 {{a derivative already exists for '_'}} // expected-note @-6 {{other attribute declared here}} @derivative(of: subscript(_:), wrt: self) func vjpSubscriptGeneric<T: Differentiable>(x: T) -> (value: T, pullback: (T.TangentVector) -> TangentVector) { return (x, { _ in .zero }) } @derivative(of: subscript.set) mutating func vjpSubscriptSetter(_ newValue: Float) -> ( value: (), pullback: (inout TangentVector) -> Float ) { fatalError() } @derivative(of: subscript().set) mutating func jvpSubscriptSetter(_ newValue: Float) -> ( value: (), differential: (inout TangentVector, Float) -> () ) { fatalError() } @derivative(of: subscript(float:).set) mutating func vjpSubscriptLabeledSetter(float: Float, newValue: Float) -> ( value: (), pullback: (inout TangentVector) -> (Float, Float) ) { fatalError() } @derivative(of: subscript(float:).set) mutating func jvpSubscriptLabeledSetter(float: Float, _ newValue: Float) -> ( value: (), differential: (inout TangentVector, Float, Float) -> Void ) { fatalError() } // Error: original subscript has no setter. // expected-error @+1 {{referenced declaration 'subscript(_:)' could not be resolved}} @derivative(of: subscript(_:).set, wrt: self) mutating func vjpSubscriptGeneric_NoSetter<T: Differentiable>(x: T) -> ( value: T, pullback: (T.TangentVector) -> TangentVector ) { return (x, { _ in .zero }) } } struct SR15530_Struct<T> {} extension SR15530_Struct: Differentiable where T: Differentiable {} extension SR15530_Struct { // expected-note @+1 {{candidate instance method does not have type equal to or less constrained than '<T where T : Differentiable> (inout SR15530_Struct<T>) -> (Int, @differentiable(reverse) (inout T) -> Void) -> Void'}} mutating func sr15530_update<D>(at index: Int, byCalling closure: (inout T, D) -> Void, withArgument: D) { fatalError("Stop") } } extension SR15530_Struct where T: Differentiable { // expected-error @+1 {{referenced declaration 'sr15530_update' could not be resolved}} @derivative(of: sr15530_update) mutating func vjp_sr15530_update( at index: Int, byCalling closure: @differentiable(reverse) (inout T) -> Void ) -> (value: Void, pullback: (inout Self.TangentVector) -> Void) { fatalError("Stop") } } extension Class { subscript() -> Float { get { 1 } // expected-note @+1 {{'subscript()' declared here}} set {} } } extension Class where T: Differentiable { @derivative(of: subscript.get) func vjpSubscriptGetter() -> (value: Float, pullback: (Float) -> TangentVector) { return (1, { _ in .zero }) } // expected-error @+2 {{a derivative already exists for '_'}} // expected-note @-6 {{other attribute declared here}} @derivative(of: subscript) func vjpSubscript() -> (value: Float, pullback: (Float) -> TangentVector) { return (1, { _ in .zero }) } // FIXME(SR-13096): Enable derivative registration for class property/subscript setters. // This requires changing derivative type calculation rules for functions with // class-typed parameters. We need to assume that all functions taking // class-typed operands may mutate those operands. // expected-error @+1 {{cannot yet register derivative for class property or subscript setters}} @derivative(of: subscript.set) func vjpSubscriptSetter(_ newValue: Float) -> ( value: (), pullback: (inout TangentVector) -> Float ) { fatalError() } } // Test duplicate `@derivative` attribute. func duplicate(_ x: Float) -> Float { x } // expected-note @+1 {{other attribute declared here}} @derivative(of: duplicate) func jvpDuplicate1(_ x: Float) -> (value: Float, differential: (Float) -> Float) { return (duplicate(x), { $0 }) } // expected-error @+1 {{a derivative already exists for 'duplicate'}} @derivative(of: duplicate) func jvpDuplicate2(_ x: Float) -> (value: Float, differential: (Float) -> Float) { return (duplicate(x), { $0 }) } // Test invalid original declaration kind. // expected-note @+1 {{candidate var does not have a getter}} var globalVariable: Float // expected-error @+1 {{referenced declaration 'globalVariable' could not be resolved}} @derivative(of: globalVariable) func invalidOriginalDeclaration(x: Float) -> ( value: Float, differential: (Float) -> (Float) ) { return (x, { $0 }) } // Test ambiguous original declaration. protocol P1 {} protocol P2 {} // expected-note @+1 {{candidate global function found here}} func ambiguous<T: P1>(_ x: T) -> T { x } // expected-note @+1 {{candidate global function found here}} func ambiguous<T: P2>(_ x: T) -> T { x } // expected-error @+1 {{referenced declaration 'ambiguous' is ambiguous}} @derivative(of: ambiguous) func jvpAmbiguous<T: P1 & P2 & Differentiable>(x: T) -> (value: T, differential: (T.TangentVector) -> (T.TangentVector)) { return (x, { $0 }) } // Test no valid original declaration. // Original declarations are invalid because they have extra generic // requirements unsatisfied by the `@derivative` function. // expected-note @+1 {{candidate global function does not have type equal to or less constrained than '<T where T : Differentiable> (x: T) -> T'}} func invalid<T: BinaryFloatingPoint>(x: T) -> T { x } // expected-note @+1 {{candidate global function does not have type equal to or less constrained than '<T where T : Differentiable> (x: T) -> T'}} func invalid<T: CustomStringConvertible>(x: T) -> T { x } // expected-note @+1 {{candidate global function does not have type equal to or less constrained than '<T where T : Differentiable> (x: T) -> T'}} func invalid<T: FloatingPoint>(x: T) -> T { x } // expected-error @+1 {{referenced declaration 'invalid' could not be resolved}} @derivative(of: invalid) func jvpInvalid<T: Differentiable>(x: T) -> ( value: T, differential: (T.TangentVector) -> T.TangentVector ) { return (x, { $0 }) } // Test stored property original declaration. struct HasStoredProperty { // expected-note @+1 {{'stored' declared here}} var stored: Float } extension HasStoredProperty: Differentiable & AdditiveArithmetic { static var zero: Self { fatalError() } static func + (lhs: Self, rhs: Self) -> Self { fatalError() } static func - (lhs: Self, rhs: Self) -> Self { fatalError() } typealias TangentVector = Self } extension HasStoredProperty { // expected-error @+1 {{cannot register derivative for stored property 'stored'}} @derivative(of: stored) func vjpStored() -> (value: Float, pullback: (Float) -> TangentVector) { return (stored, { _ in .zero }) } } // Test derivative registration for protocol requirements. Currently unsupported. // TODO(TF-982): Lift this restriction and add proper support. protocol ProtocolRequirementDerivative { // expected-note @+1 {{cannot yet register derivative default implementation for protocol requirements}} func requirement(_ x: Float) -> Float } extension ProtocolRequirementDerivative { // expected-error @+1 {{referenced declaration 'requirement' could not be resolved}} @derivative(of: requirement) func vjpRequirement(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } } // Test `inout` parameters. func multipleSemanticResults(_ x: inout Float) -> Float { return x } // expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}} @derivative(of: multipleSemanticResults) func vjpMultipleSemanticResults(x: inout Float) -> ( value: Float, pullback: (Float) -> Float ) { return (multipleSemanticResults(&x), { $0 }) } struct InoutParameters: Differentiable { typealias TangentVector = DummyTangentVector mutating func move(by _: TangentVector) {} } extension InoutParameters { // expected-note @+1 4 {{'staticMethod(_:rhs:)' defined here}} static func staticMethod(_ lhs: inout Self, rhs: Self) {} // Test wrt `inout` parameter. @derivative(of: staticMethod) static func vjpWrtInout(_ lhs: inout Self, _ rhs: Self) -> ( value: Void, pullback: (inout TangentVector) -> TangentVector ) { fatalError() } // expected-error @+1 {{function result's 'pullback' type does not match 'staticMethod(_:rhs:)'}} @derivative(of: staticMethod) static func vjpWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> ( // expected-note @+1 {{'pullback' does not have expected type '(inout InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(inout DummyTangentVector) -> DummyTangentVector')}} value: Void, pullback: (TangentVector) -> TangentVector ) { fatalError() } @derivative(of: staticMethod) static func jvpWrtInout(_ lhs: inout Self, _ rhs: Self) -> ( value: Void, differential: (inout TangentVector, TangentVector) -> Void ) { fatalError() } // expected-error @+1 {{function result's 'differential' type does not match 'staticMethod(_:rhs:)'}} @derivative(of: staticMethod) static func jvpWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> ( // expected-note @+1 {{'differential' does not have expected type '(inout InoutParameters.TangentVector, InoutParameters.TangentVector) -> ()' (aka '(inout DummyTangentVector, DummyTangentVector) -> ()')}} value: Void, differential: (TangentVector, TangentVector) -> Void ) { fatalError() } // Test non-wrt `inout` parameter. @derivative(of: staticMethod, wrt: rhs) static func vjpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> ( value: Void, pullback: (TangentVector) -> TangentVector ) { fatalError() } // expected-error @+1 {{function result's 'pullback' type does not match 'staticMethod(_:rhs:)'}} @derivative(of: staticMethod, wrt: rhs) static func vjpNotWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> ( // expected-note @+1 {{'pullback' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}} value: Void, pullback: (inout TangentVector) -> TangentVector ) { fatalError() } @derivative(of: staticMethod, wrt: rhs) static func jvpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> ( value: Void, differential: (TangentVector) -> TangentVector ) { fatalError() } // expected-error @+1 {{function result's 'differential' type does not match 'staticMethod(_:rhs:)'}} @derivative(of: staticMethod, wrt: rhs) static func jvpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> ( // expected-note @+1 {{'differential' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}} value: Void, differential: (inout TangentVector) -> TangentVector ) { fatalError() } } extension InoutParameters { // expected-note @+1 4 {{'mutatingMethod' defined here}} mutating func mutatingMethod(_ other: Self) {} // Test wrt `inout` `self` parameter. @derivative(of: mutatingMethod) mutating func vjpWrtInout(_ other: Self) -> ( value: Void, pullback: (inout TangentVector) -> TangentVector ) { fatalError() } // expected-error @+1 {{function result's 'pullback' type does not match 'mutatingMethod'}} @derivative(of: mutatingMethod) mutating func vjpWrtInoutMismatch(_ other: Self) -> ( // expected-note @+1 {{'pullback' does not have expected type '(inout InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(inout DummyTangentVector) -> DummyTangentVector')}} value: Void, pullback: (TangentVector) -> TangentVector ) { fatalError() } @derivative(of: mutatingMethod) mutating func jvpWrtInout(_ other: Self) -> ( value: Void, differential: (inout TangentVector, TangentVector) -> Void ) { fatalError() } // expected-error @+1 {{function result's 'differential' type does not match 'mutatingMethod'}} @derivative(of: mutatingMethod) mutating func jvpWrtInoutMismatch(_ other: Self) -> ( // expected-note @+1 {{'differential' does not have expected type '(inout InoutParameters.TangentVector, InoutParameters.TangentVector) -> ()' (aka '(inout DummyTangentVector, DummyTangentVector) -> ()')}} value: Void, differential: (TangentVector, TangentVector) -> Void ) { fatalError() } // Test non-wrt `inout` `self` parameter. @derivative(of: mutatingMethod, wrt: other) mutating func vjpNotWrtInout(_ other: Self) -> ( value: Void, pullback: (TangentVector) -> TangentVector ) { fatalError() } // expected-error @+1 {{function result's 'pullback' type does not match 'mutatingMethod'}} @derivative(of: mutatingMethod, wrt: other) mutating func vjpNotWrtInoutMismatch(_ other: Self) -> ( // expected-note @+1 {{'pullback' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}} value: Void, pullback: (inout TangentVector) -> TangentVector ) { fatalError() } @derivative(of: mutatingMethod, wrt: other) mutating func jvpNotWrtInout(_ other: Self) -> ( value: Void, differential: (TangentVector) -> TangentVector ) { fatalError() } // expected-error @+1 {{function result's 'differential' type does not match 'mutatingMethod'}} @derivative(of: mutatingMethod, wrt: other) mutating func jvpNotWrtInoutMismatch(_ other: Self) -> ( // expected-note @+1 {{'differential' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}} value: Void, differential: (TangentVector, TangentVector) -> Void ) { fatalError() } } // Test no semantic results. func noSemanticResults(_ x: Float) {} // expected-error @+1 {{cannot differentiate void function 'noSemanticResults'}} @derivative(of: noSemanticResults) func vjpNoSemanticResults(_ x: Float) -> (value: Void, pullback: Void) {} // Test multiple semantic results. extension InoutParameters { func multipleSemanticResults(_ x: inout Float) -> Float { x } // expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}} @derivative(of: multipleSemanticResults) func vjpMultipleSemanticResults(_ x: inout Float) -> ( value: Float, pullback: (inout Float) -> Void ) { fatalError() } func inoutVoid(_ x: Float, _ void: inout Void) -> Float {} // expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}} @derivative(of: inoutVoid) func vjpInoutVoidParameter(_ x: Float, _ void: inout Void) -> ( value: Float, pullback: (inout Float) -> Void ) { fatalError() } } // Test original/derivative function `inout` parameter mismatches. extension InoutParameters { // expected-note @+1 {{candidate instance method does not have expected type '(InoutParameters) -> (inout Float) -> Void'}} func inoutParameterMismatch(_ x: Float) {} // expected-error @+1 {{referenced declaration 'inoutParameterMismatch' could not be resolved}} @derivative(of: inoutParameterMismatch) func vjpInoutParameterMismatch(_ x: inout Float) -> (value: Void, pullback: (inout Float) -> Void) { fatalError() } // expected-note @+1 {{candidate instance method does not have expected type '(inout InoutParameters) -> (Float) -> Void'}} func mutatingMismatch(_ x: Float) {} // expected-error @+1 {{referenced declaration 'mutatingMismatch' could not be resolved}} @derivative(of: mutatingMismatch) mutating func vjpMutatingMismatch(_ x: Float) -> (value: Void, pullback: (inout Float) -> Void) { fatalError() } } // Test cross-file derivative registration. extension FloatingPoint where Self: Differentiable { @usableFromInline @derivative(of: rounded) func vjpRounded() -> ( value: Self, pullback: (Self.TangentVector) -> (Self.TangentVector) ) { fatalError() } } extension Differentiable where Self: AdditiveArithmetic { // expected-error @+1 {{referenced declaration '+' could not be resolved}} @derivative(of: +) static func vjpPlus(x: Self, y: Self) -> ( value: Self, pullback: (Self.TangentVector) -> (Self.TangentVector, Self.TangentVector) ) { return (x + y, { v in (v, v) }) } } extension AdditiveArithmetic where Self: Differentiable, Self == Self.TangentVector { // expected-error @+1 {{referenced declaration '+' could not be resolved}} @derivative(of: +) func vjpPlusInstanceMethod(x: Self, y: Self) -> ( value: Self, pullback: (Self) -> (Self, Self) ) { return (x + y, { v in (v, v) }) } } // Test derivatives of default implementations. protocol HasADefaultImplementation { func req(_ x: Float) -> Float } extension HasADefaultImplementation { func req(_ x: Float) -> Float { x } // ok @derivative(of: req) func req(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { (x, { 10 * $0 }) } } // Test default derivatives of requirements. protocol HasADefaultDerivative { // expected-note @+1 {{cannot yet register derivative default implementation for protocol requirements}} func req(_ x: Float) -> Float } extension HasADefaultDerivative { // TODO(TF-982): Support default derivatives for protocol requirements. // expected-error @+1 {{referenced declaration 'req' could not be resolved}} @derivative(of: req) func vjpReq(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { (x, { 10 * $0 }) } } // MARK: - Original function visibility = derivative function visibility public func public_original_public_derivative(_ x: Float) -> Float { x } @derivative(of: public_original_public_derivative) public func _public_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } public func public_original_usablefrominline_derivative(_ x: Float) -> Float { x } @usableFromInline @derivative(of: public_original_usablefrominline_derivative) func _public_original_usablefrominline_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } func internal_original_internal_derivative(_ x: Float) -> Float { x } @derivative(of: internal_original_internal_derivative) func _internal_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } private func private_original_private_derivative(_ x: Float) -> Float { x } @derivative(of: private_original_private_derivative) private func _private_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } fileprivate func fileprivate_original_fileprivate_derivative(_ x: Float) -> Float { x } @derivative(of: fileprivate_original_fileprivate_derivative) fileprivate func _fileprivate_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } func internal_original_usablefrominline_derivative(_ x: Float) -> Float { x } @usableFromInline @derivative(of: internal_original_usablefrominline_derivative) func _internal_original_usablefrominline_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } func internal_original_inlinable_derivative(_ x: Float) -> Float { x } @inlinable @derivative(of: internal_original_inlinable_derivative) func _internal_original_inlinable_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } func internal_original_alwaysemitintoclient_derivative(_ x: Float) -> Float { x } @_alwaysEmitIntoClient @derivative(of: internal_original_alwaysemitintoclient_derivative) func _internal_original_alwaysemitintoclient_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } // MARK: - Original function visibility < derivative function visibility @usableFromInline func usablefrominline_original_public_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_usablefrominline_original_public_derivative' is public, but original function 'usablefrominline_original_public_derivative' is internal}} @derivative(of: usablefrominline_original_public_derivative) // expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-7=internal}} public func _usablefrominline_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } func internal_original_public_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_internal_original_public_derivative' is public, but original function 'internal_original_public_derivative' is internal}} @derivative(of: internal_original_public_derivative) // expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-7=internal}} public func _internal_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } private func private_original_usablefrominline_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_usablefrominline_derivative' is internal, but original function 'private_original_usablefrominline_derivative' is private}} @derivative(of: private_original_usablefrominline_derivative) @usableFromInline // expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-1=private }} func _private_original_usablefrominline_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } private func private_original_public_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_public_derivative' is public, but original function 'private_original_public_derivative' is private}} @derivative(of: private_original_public_derivative) // expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-7=private}} public func _private_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } private func private_original_internal_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_internal_derivative' is internal, but original function 'private_original_internal_derivative' is private}} @derivative(of: private_original_internal_derivative) // expected-note @+1 {{mark the derivative function as 'private' to match the original function}} func _private_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } fileprivate func fileprivate_original_private_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_fileprivate_original_private_derivative' is private, but original function 'fileprivate_original_private_derivative' is fileprivate}} @derivative(of: fileprivate_original_private_derivative) // expected-note @+1 {{mark the derivative function as 'fileprivate' to match the original function}} {{1-8=fileprivate}} private func _fileprivate_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } private func private_original_fileprivate_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_fileprivate_derivative' is fileprivate, but original function 'private_original_fileprivate_derivative' is private}} @derivative(of: private_original_fileprivate_derivative) // expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-12=private}} fileprivate func _private_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } // MARK: - Original function visibility > derivative function visibility public func public_original_private_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_public_original_private_derivative' is fileprivate, but original function 'public_original_private_derivative' is public}} @derivative(of: public_original_private_derivative) // expected-note @+1 {{mark the derivative function as '@usableFromInline' to match the original function}} {{1-1=@usableFromInline }} fileprivate func _public_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } public func public_original_internal_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_public_original_internal_derivative' is internal, but original function 'public_original_internal_derivative' is public}} @derivative(of: public_original_internal_derivative) // expected-note @+1 {{mark the derivative function as '@usableFromInline' to match the original function}} {{1-1=@usableFromInline }} func _public_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } func internal_original_fileprivate_derivative(_ x: Float) -> Float { x } // expected-error @+1 {{derivative function must have same access level as original function; derivative function '_internal_original_fileprivate_derivative' is fileprivate, but original function 'internal_original_fileprivate_derivative' is internal}} @derivative(of: internal_original_fileprivate_derivative) // expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-12=internal}} fileprivate func _internal_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } // Test invalid reference to an accessor of a non-storage declaration. // expected-note @+1 {{candidate global function does not have a getter}} func function(_ x: Float) -> Float { x } // expected-error @+1 {{referenced declaration 'function' could not be resolved}} @derivative(of: function(_:).get) func vjpFunction(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } // Test ambiguity that exists when Type function name is the same // as an accessor label. extension Float { // Original function name conflicts with an accessor name ("set"). func set() -> Float { self } // Original function name does not conflict with an accessor name. func method() -> Float { self } // Test ambiguous parse. // Expected: // - Base type: `Float` // - Declaration name: `set` // - Accessor kind: <none> // Actual: // - Base type: <none> // - Declaration name: `Float` // - Accessor kind: `set` // expected-error @+1 {{cannot find 'Float' in scope}} @derivative(of: Float.set) func jvpSet() -> (value: Float, differential: (Float) -> Float) { fatalError() } @derivative(of: Float.method) func jvpMethod() -> (value: Float, differential: (Float) -> Float) { fatalError() } } // Test original function with opaque result type. // expected-note @+1 {{candidate global function does not have expected type '(Float) -> Float'}} func opaqueResult(_ x: Float) -> some Differentiable { x } // expected-error @+1 {{referenced declaration 'opaqueResult' could not be resolved}} @derivative(of: opaqueResult) func vjpOpaqueResult(_ x: Float) -> (value: Float, pullback: (Float) -> Float) { fatalError() } // Test instance vs static method mismatch. struct StaticMismatch<T: Differentiable> { // expected-note @+1 {{original function 'init(_:)' is a 'static' method}} init(_ x: T) {} // expected-note @+1 {{original function 'instanceMethod' is an instance method}} func instanceMethod(_ x: T) -> T { x } // expected-note @+1 {{original function 'staticMethod' is a 'static' method}} static func staticMethod(_ x: T) -> T { x } // expected-error @+1 {{unexpected derivative function declaration; 'init(_:)' requires the derivative function 'vjpInit' to be a 'static' method}} @derivative(of: init) // expected-note @+1 {{make derivative function 'vjpInit' a 'static' method}}{{3-3=static }} func vjpInit(_ x: T) -> (value: Self, pullback: (T.TangentVector) -> T.TangentVector) { fatalError() } // expected-error @+1 {{unexpected derivative function declaration; 'instanceMethod' requires the derivative function 'jvpInstance' to be an instance method}} @derivative(of: instanceMethod) // expected-note @+1 {{make derivative function 'jvpInstance' an instance method}}{{3-10=}} static func jvpInstance(_ x: T) -> ( value: T, differential: (T.TangentVector) -> (T.TangentVector) ) { return (x, { $0 }) } // expected-error @+1 {{unexpected derivative function declaration; 'staticMethod' requires the derivative function 'jvpStatic' to be a 'static' method}} @derivative(of: staticMethod) // expected-note @+1 {{make derivative function 'jvpStatic' a 'static' method}}{{3-3=static }} func jvpStatic(_ x: T) -> ( value: T, differential: (T.TangentVector) -> (T.TangentVector) ) { return (x, { $0 }) } }
apache-2.0
danielsaidi/KeyboardKit
Sources/KeyboardKit/UIKit/Extensions/UIColor+ClearInteractable.swift
1
424
// // UIColor+ClearInteractable.swift // KeyboardKit // // Created by Daniel Saidi on 2019-06-02. // Copyright © 2021 Daniel Saidi. All rights reserved. // import UIKit public extension UIColor { /** This color can be used instead of `.clear`, which makes a view stop registering touches and gestures. */ static var clearInteractable: UIColor { UIColor(white: 1, alpha: 0.005) } }
mit
Sage-Bionetworks/BridgeAppSDK
BridgeAppSDK/SBAGenericStepDataSource.swift
1
22186
// // SBAGenericStepDataSource.swift // BridgeAppSDK // // Created by Josh Bruhin on 6/5/17. // Copyright © 2017 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. 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. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // 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 OWNER 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 /** SBAGenericStepDataSource: the internal model for SBAGenericStepViewController. It provides the UITableViewDataSource, manages and stores answers provided thru user input, and provides an ORKResult with those anwers upon request. It also provides several convenience methods for saving or selecting answers, checking if all answers are valid, and retrieving specific model objects that may be needed by the ViewController. The tableView data source is comprised of 3 objects: 1) SBAGenericStepTableSection - An object representing a section in the tableView. It has one or more SBAGenericStepTableItemGroups. 2) SBAGenericStepTableItemGroup - An object representing a specific question supplied by ORKStep in the form of ORKFormItem. An ORKFormItem can have multiple answer options, such as a boolean question or text choice question. Or, it can have just one answer option, in the case of alpha/numeric questions. Upon init(), the ItemGroup will create one or more SBAGenericStepTableItem representing the answer options for the ORKFormItem. The ItemGroup is responsible for storing/computing the answers for its ORKFormItem. 3) SBAGenericStepTableItem - An object representing a specific answer option from the ItemGroup (ORKFormItem), such as a Yes or No choice in a boolean question or a string or number that's entered thru a text field. There will be one TableItem for each indexPath in the tableView. */ public protocol SBAGenericStepDataSourceDelegate { func answersDidChange() } open class SBAGenericStepDataSource: NSObject { open var delegate: SBAGenericStepDataSourceDelegate? open var sections: Array<SBAGenericStepTableSection> = Array() open var step: ORKStep? /** Initialize a new SBAGenericStepDataSource. @param step The ORKStep @param result The previous ORKResult, if any */ public init(step: ORKStep?, result: ORKResult?) { super.init() self.step = step populate() if result != nil { updateAnswers(from: result!) } } func updateAnswers(from result: ORKResult) { guard let taskResult = result as? ORKTaskResult else { return } // find the existing result for this step, if any if let stepResult = taskResult.result(forIdentifier: step!.identifier) as? ORKStepResult, let stepResults = stepResult.results as? [ORKQuestionResult] { // for each form item result, save the existing answer to our model for result in stepResults { let answer = result.answer ?? ORKNullAnswerValue() if let group = itemGroup(with: result.identifier) { group.answer = answer as AnyObject } } } } public func updateDefaults(_ defaults: NSMutableDictionary) { // TODO: Josh Bruhin, 6/12/17 - implement. this may require access to a HealthKit source. for section in sections { section.itemGroups.forEach({ if let newAnswer = defaults[$0.formItem.identifier] { $0.defaultAnswer = newAnswer as AnyObject } }) } // notify our delegate that the result changed if let delegate = delegate { delegate.answersDidChange() } } /** Determine if all answers are valid. Also checks the case where answers are required but one has not been provided. @return A Bool indicating if all answers are valid */ open func allAnswersValid() -> Bool { for section in sections { for itemGroup in section.itemGroups { if !itemGroup.isAnswerValid { return false } } } return true } /** Retrieve the 'SBAGenericStepTableItemGroup' with a specific ORKFormItem identifier. @param identifier The identifier of the ORKFormItem assigned to the ItemGroup @return The requested SBAGenericStepTableItemGroup, or nil if it cannot be found */ open func itemGroup(with identifier: String) -> SBAGenericStepTableItemGroup? { for section in sections { for itemGroup in section.itemGroups { if itemGroup.formItem.identifier == identifier { return itemGroup } } } return nil } /** Retrieve the 'SBAGenericStepTableItemGroup' for a specific IndexPath. @param indexPath The IndexPath that represents the ItemGroup in the tableView @return The requested SBAGenericStepTableItemGroup, or nil if it cannot be found */ open func itemGroup(at indexPath: IndexPath) -> SBAGenericStepTableItemGroup? { let section = sections[indexPath.section] for itemGroup in section.itemGroups { if itemGroup.beginningRowIndex ... itemGroup.beginningRowIndex + (itemGroup.items.count - 1) ~= indexPath.row { return itemGroup } } return nil } /** Retrieve the 'SBAGenericStepTableItem' for a specific IndexPath. @param indexPath The IndexPath that represents the TableItem in the tableView @return The requested SBAGenericStepTableItem, or nil if it cannot be found */ open func tableItem(at indexPath: IndexPath) -> SBAGenericStepTableItem? { if let itemGroup = itemGroup(at: indexPath) { let index = indexPath.row - itemGroup.beginningRowIndex return itemGroup.items[index] } return nil } /** Save an answer for a specific IndexPath. @param answer The object to be save as the answer @param indexPath The IndexPath that represents the TableItemGroup in the tableView */ open func saveAnswer(_ answer: AnyObject, at indexPath: IndexPath) { let itemGroup = self.itemGroup(at: indexPath) itemGroup?.answer = answer // inform delegate that answers have changed if let delegate = delegate { delegate.answersDidChange() } } /** Select or deselect the answer option for a specific IndexPath. @param indexPath The IndexPath that represents the TableItemGroup in the tableView */ open func selectAnswer(selected: Bool, at indexPath: IndexPath) { let itemGroup = self.itemGroup(at: indexPath) itemGroup?.select(selected, indexPath: indexPath) // inform delegate that answers have changed if let delegate = delegate { delegate.answersDidChange() } } /** Retrieve the current ORKStepResult. @return An ORKStepResult object with the current answers for all of its ORKFormItems */ open func results(parentResult: ORKStepResult) -> ORKStepResult { guard let formItems = formItemsWithAnswerFormat() else { return parentResult } // "Now" is the end time of the result, which is either actually now, // or the last time we were in the responder chain. let now = parentResult.endDate for formItem: ORKFormItem in formItems { var answer = ORKNullAnswerValue() var answerDate = now var systemCalendar = Calendar.current var systemTimeZone = NSTimeZone.system if let itemGroup = itemGroup(with: formItem.identifier) { answer = itemGroup.answer // check that answer is not NSNull (ORKNullAnswerValue) // Skipped forms report a "null" value for every item -- by skipping, the user has explicitly said they don't want // to report any values from this form. if !(answer is NSNull) { answerDate = itemGroup.answerDate ?? now systemCalendar = itemGroup.calendar systemTimeZone = itemGroup.timezone } } guard let result = formItem.answerFormat?.result(withIdentifier: formItem.identifier, answer: answer) else { continue } let impliedAnswerFormat = formItem.answerFormat?.implied() if let dateAnswerFormat = impliedAnswerFormat as? ORKDateAnswerFormat, let dateQuestionResult = result as? ORKDateQuestionResult, let _ = dateQuestionResult.dateAnswer { let usedCalendar = dateAnswerFormat.calendar ?? systemCalendar dateQuestionResult.calendar = usedCalendar dateQuestionResult.timeZone = systemTimeZone } else if let numericAnswerFormat = impliedAnswerFormat as? ORKNumericAnswerFormat, let numericQuestionFormat = result as? ORKNumericQuestionResult, numericQuestionFormat.unit == nil { numericQuestionFormat.unit = numericAnswerFormat.unit } result.startDate = answerDate result.endDate = answerDate parentResult.addResult(result) } return parentResult } fileprivate func formItemsWithAnswerFormat() -> Array<ORKFormItem>? { return self.formItems()?.filter { $0.answerFormat != nil } } fileprivate func formItems() -> [ORKFormItem]? { guard let formStep = self.step as? SBAFormStepProtocol else { return nil } return formStep.formItems } fileprivate func populate() { guard let items = formItems(), items.count > 0 else { return } let singleSelectionTypes: [ORKQuestionType] = [.boolean, .singleChoice, .multipleChoice, .location] for item in items { // some form items need to be in their own section var needExclusiveSection = false if let answerFormat = item.answerFormat?.implied() { let multiCellChoice = singleSelectionTypes.contains(answerFormat.questionType) && !(answerFormat is ORKValuePickerAnswerFormat) let multiLineTextEntry = answerFormat.questionType == .text let scale = answerFormat.questionType == .scale needExclusiveSection = multiCellChoice || multiLineTextEntry || scale } // if we don't need an exclusive section and we have an existing section and it's not exclusive ('singleFormItem'), // then add this item to that existing section, otherwise create a new one if !needExclusiveSection, let lastSection = sections.last, !lastSection.singleFormItem { lastSection.add(formItem: item) } else { let section = SBAGenericStepTableSection(sectionIndex: sections.count) section.add(formItem: item) section.title = item.text section.singleFormItem = needExclusiveSection sections.append(section) } } } } open class SBAGenericStepTableSection: NSObject { open var itemGroups: Array<SBAGenericStepTableItemGroup> = Array() private var _title: String? var title: String? { get { return _title } set (newValue) { _title = newValue?.uppercased(with: Locale.current) } } /** Indicates whether this section is exclusive to a single form item or can contain multiple form items. */ public var singleFormItem = false let index: Int! public init(sectionIndex: Int) { self.index = sectionIndex super.init() } /** Add a new ORKFormItem, which results in the creation and addition of a new SBAGenericStepTableItemGroup to the section. The ItemGroup essectially represents the FormItem and is reponsible for storing and providing answers for the FormItem when a ORKStepResult is requested. @param formItem The ORKFormItem to add to the section */ public func add(formItem: ORKFormItem) { guard itemGroups.sba_find({ $0.formItem.identifier == formItem.identifier }) == nil else { assertionFailure("Cannot add ORKFormItem with duplicate identifier.") return } itemGroups.append(SBAGenericStepTableItemGroup(formItem: formItem, beginningRowIndex: itemCount())) } /** Returns the total count of all Items in this section. @return The total number of SBAGenericStepTableItems in this section */ public func itemCount() -> Int { return itemGroups.reduce(0, {$0 + $1.items.count}) } } open class SBAGenericStepTableItemGroup: NSObject { let formItem: ORKFormItem! var items: [SBAGenericStepTableItem]! var beginningRowIndex = 0 var singleSelection: Bool = true var answerDate: Date? var calendar = Calendar.current var timezone = TimeZone.current var defaultAnswer: Any = ORKNullAnswerValue() as Any private var _answer: Any? /** Save an answer for this ItemGroup (FormItem). This is used only for those questions that have single answers, such as text and numeric answers, as opposed to booleans or text choice answers. */ public var answer: Any! { get { return internalAnswer() } set { setInternalAnswer(newValue) } } /** Determine if the current answer is valid. Also checks the case where answer is required but one has not been provided. @return A Bool indicating if answer is valid */ public var isAnswerValid: Bool { // if answer is NOT optional and it equals Null (ORKNullAnswerValue()), or is nil, then it's invalid if !formItem.isOptional, answer is NSNull || answer == nil { return false } return formItem.answerFormat?.implied().isAnswerValid(answer) ?? false } /** Initialize a new ItemGroup with an ORKFormItem. Pass a beginningRowIndex since sections can have multiple ItemGroups. @param formItem The ORKFormItem to add to the model @param beginningRowIndex The row index in the section at which this formItem begins */ fileprivate init(formItem: ORKFormItem, beginningRowIndex: Int) { self.formItem = formItem super.init() if let textChoiceAnswerFormat = formItem.answerFormat?.implied() as? ORKTextChoiceAnswerFormat { singleSelection = textChoiceAnswerFormat.style == .singleChoice self.items = textChoiceAnswerFormat.textChoices.enumerated().map { (index, _) -> SBAGenericStepTableItem in SBAGenericStepTableItem(formItem: formItem, choiceIndex: index, rowIndex: beginningRowIndex + index) } } else { let tableItem = SBAGenericStepTableItem(formItem: formItem, choiceIndex: 0, rowIndex: beginningRowIndex) self.items = [tableItem] } } /** Select or de-select an item (answer) at a specific indexPath. This is used for text choice and boolean answers. @param selected A bool indicating if item should be selected @param indexPath The IndexPath of the item */ fileprivate func select(_ selected: Bool, indexPath: IndexPath) { // to get index of our item, add our beginningRowIndex to indexPath.row let index = beginningRowIndex + indexPath.row if items.count > index { items[index].selected = selected } // if we selected an item and this is a single-selection group, then we iterate // our other items and de-select them if singleSelection { for (ii, item) in items.enumerated() { item.selected = (ii == index) } } } fileprivate func internalAnswer() -> Any { guard let answerFormat = items.first?.formItem?.answerFormat else { return _answer ?? defaultAnswer } switch answerFormat { case is ORKBooleanAnswerFormat: return answerForBoolean() case is ORKMultipleValuePickerAnswerFormat, is ORKTextChoiceAnswerFormat: return answerForTextChoice() default: return _answer ?? defaultAnswer } } fileprivate func setInternalAnswer(_ answer: Any) { guard let answerFormat = items.first?.formItem?.answerFormat else { return } switch answerFormat { case is ORKBooleanAnswerFormat: // iterate our items and find the item with a value equal to our answer, // then select that item let formattedAnswer = answer as? NSNumber for item in items { if (item.choice?.value as? NSNumber)?.boolValue == formattedAnswer?.boolValue { item.selected = true } } case is ORKTextChoiceAnswerFormat: // iterate our items and find the items with a value that is contained in our // answer, which should be an array, then select those items if let arrayAnswer = answer as? Array<AnyObject> { for item in items { item.selected = (item.choice?.value != nil) && arrayAnswer.contains(where: { (value) -> Bool in return item.choice!.value === value }) } } case is ORKMultipleValuePickerAnswerFormat: // TODO: Josh Bruhin, 6/12/17 - implement this answer format. fatalError("setInternalAnswer for ORKMultipleValuePickerAnswerFormat not implemented") default: _answer = answer } } private func answerForTextChoice() -> AnyObject { let array = self.items.sba_mapAndFilter { $0.selected ? $0.choice?.value : nil } return array.count > 0 ? array as AnyObject : ORKNullAnswerValue() as AnyObject } private func answerForBoolean() -> AnyObject { for item in items { if item.selected { if let value = item.choice?.value as? NSNumber { return NSDecimalNumber(value: value.boolValue) } } } return ORKNullAnswerValue() as AnyObject } } open class SBAGenericStepTableItem: NSObject { // the same formItem assigned to the group that this item belongs to var formItem: ORKFormItem? var answerFormat: ORKAnswerFormat? var choice: ORKTextChoice? var choiceIndex = 0 var rowIndex = 0 var selected: Bool = false /** Initialize a new SBAGenericStepTableItem @param formItem The ORKFormItem representing this tableItem. @param choiceIndex The index of this item relative to all the choices in this ItemGroup @param rowIndex The index of this item relative to all rows in the section in which this item resides */ fileprivate init(formItem: ORKFormItem!, choiceIndex: Int, rowIndex: Int) { super.init() commonInit(formItem: formItem) self.choiceIndex = choiceIndex self.rowIndex = rowIndex if let textChoiceFormat = textChoiceAnswerFormat() { choice = textChoiceFormat.textChoices[choiceIndex] } } func commonInit(formItem: ORKFormItem!) { self.formItem = formItem self.answerFormat = formItem.answerFormat?.implied() } func textChoiceAnswerFormat() -> ORKTextChoiceAnswerFormat? { guard let textChoiceFormat = self.answerFormat as? ORKTextChoiceAnswerFormat else { return nil } return textChoiceFormat } }
bsd-3-clause
chrisvalford/Heros
Heros/SecondViewController.swift
1
525
// // SecondViewController.swift // Heros // // Created by Christopher Alford on 13.05.17. // Copyright © 2017 marine+Digital. All rights reserved. // import UIKit class SecondViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
valentin7/pineapple-ios
Pineapple/SettingsTableViewController.swift
1
6430
// // SettingsTableViewController.swift // Pineapple // // Created by Valentin Perez on 7/18/15. // Copyright (c) 2015 Valpe Technologies. All rights reserved. // import UIKit import Parse import SVProgressHUD import MessageUI class SettingsTableViewController: UITableViewController, MFMailComposeViewControllerDelegate { @IBOutlet var settingsTableView: UITableView! let user = PFUser.currentUser()! var parent : UIViewController! override func viewDidLoad() { super.viewDidLoad() parent = self.parentViewController // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() settingsTableView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func unwindToMainViewController (sender: UIStoryboardSegue){ // bug? exit segue doesn't dismiss so we do it manually... self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func tappedSendFeedback(sender: AnyObject) { sendFeedback() } @IBAction func tappedLogout(sender: AnyObject) { logout() } // MARK: - Table view data source override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if (section == 0){ let name = user["name"] as! String return name } else { return "" } } override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { print("YOO") if (indexPath.section == 0) { print("SECTION 0 DAW") switch indexPath.row { case 0: print("ch pass") let vc = self.storyboard?.instantiateViewControllerWithIdentifier("passwordChangeController") as! PasswordChangeViewController parent.presentViewController(vc, animated: true, completion: nil) case 1: print("Change phone") let vc = self.storyboard?.instantiateViewControllerWithIdentifier("phoneChangeController") as! PasswordChangeViewController parent.presentViewController(vc, animated: true, completion: nil) default: print("Add credit yo") } } else if (indexPath.section == 1) { print("DIFF SECTION 1") } } func sendFeedback() { print("TRYNNA SEND FEEDBACK") let mailComposeViewController = configuredMailComposeViewController() if MFMailComposeViewController.canSendMail() { self.presentViewController(mailComposeViewController, animated: true, completion: nil) } else { self.showSendMailErrorAlert() } } func configuredMailComposeViewController() -> MFMailComposeViewController { let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property mailComposerVC.setToRecipients(["hello@pineapple.world"]) mailComposerVC.setSubject("Feedback for Pineapple") mailComposerVC.setMessageBody("", isHTML: false) return mailComposerVC } func showSendMailErrorAlert() { let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK") sendMailErrorAlert.show() } // MARK: MFMailComposeViewControllerDelegate func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { controller.dismissViewControllerAnimated(true, completion: nil) } func logout(){ let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) PFUser.logOut() SVProgressHUD.show() let vc : OnboardViewController = self.storyboard!.instantiateViewControllerWithIdentifier("onboardController") as! OnboardViewController let app : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate SVProgressHUD.dismiss() app.window!.rootViewController = vc } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
RajatDhasmana/rajat_appinventiv
VehiclesCollection/VehiclesCollection/PreviewVC.swift
1
860
// // PreviewVC.swift // VehiclesCollection // // Created by Rajat Dhasmana on 18/02/17. // Copyright © 2017 appinventiv. All rights reserved. // import UIKit class PreviewVC: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
EBGToo/SBCommons
Sources/Func.swift
1
5637
// // Func.swift // SBCommons // // Created by Ed Gamble on 10/22/15. // Copyright © 2015 Edward B. Gamble Jr. All rights reserved. // // See the LICENSE file at the project root for license information. // See the CONTRIBUTORS file at the project root for a list of contributors. // /** * The Y-combinator - for the hell of it * * - argument f: * * - returns: A function */ func Y<T, R> (_ f: @escaping (@escaping (T) -> R) -> ((T) -> R)) -> ((T) -> R) { return { t in f(Y(f))(t) } } /** Factorial, defined using the Y-combinator */ let factorial = Y { f in { n in n == 0 ? 1 : n * f(n - 1) } } /** * A function that always returns x * * - argument x: * * - returns: A function of (y:T) that (always) return x */ public func always<T> (_ x:T) -> (_ y:T) -> T { return { (y:T) in return x } } /** * Complememnt a predicate * * - argument pred: The function to complement * * - returns: A function as !pred */ public func complement<T> (_ pred : @escaping (T) -> Bool) -> (T) -> Bool { return { (x:T) in return !pred(x) } } /** * Compose functions `f` and `g` as `f(g(x))` * * - argument f: * - argument g: * * - returns: a function of `x:T` returning `f(g(x))` */ public func compose<T, U, V> (f: @escaping (U) -> V, g: @escaping (T) -> U) -> (T) -> V { return { (x:T) in f (g (x)) } } /** * Disjoin two predicates * * - argument pred1: * - argument pred2: * * - returns: A function of `x:T` that returns pred1(x) || pred2(x) */ public func disjoin<T> (pred1: @escaping (T) -> Bool, pred2: @escaping (T) -> Bool) -> (T) -> Bool { return { (x:T) in pred1 (x) || pred2 (x) } } /** * Conjoin two predicates * * - argument pred1: * - argument pred2: * * - returns: A function of `x:T` that returns pred1(x) && pred2(x) */ public func conjoin<T> (pred1: @escaping (T) -> Bool, pred2: @escaping (T) -> Bool) -> (T) -> Bool { return { (x:T) in pred1 (x) && pred2 (x) } } /** * * * - argument pred: * - argument x: * * - returns: A function of (y:T) that returns pred(x,y) */ public func equalTo<T> (pred: @escaping (T, T) -> Bool, x:T) -> (T) -> Bool { return { (y:T) in return pred (x, y) } } // MARK: - Sequence App Type public protocol SequenceAppType : Sequence { /** Think different: renaming of `forEach` to be analogous to `map` */ func app ( _ body: (Self.Iterator.Element) -> Void) -> Void } extension Sequence { public func app (_ body: (Self.Iterator.Element) throws -> Void) rethrows -> Void { for item in self { try body (item) } } } // MARK: Sequence Logic Type public protocol SequenceLogicType : Sequence { /** * Check if any element satisfies `predicate`. * * - argument predicate: * * - returns: `true` if any element satisfies `predicate`; `false` otherwise */ func any (_ predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Bool /** * Check if all elements satisfy `predicate`. * * - argument predicate: * * - returns: `true` if all elements satisfy `predicate`; `false` otherwise */ func all (_ predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Bool } extension Sequence { public func any (_ predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Bool { for elt in self { if (try predicate (elt)) { return true } } return false } public func all (_ predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Bool { for elt in self { if (try !predicate (elt)) { return false } } return true } } // MARK: Sequence Scan Type public protocol SequenceScanType : Sequence { /** * Scan `self` element by element combining elements. Resulting array has one element more * than `self`. * * - argument initial: the resulting array's initial element * - argument combine: the function combining the 'accumulated' value with next element * * - retuns: array with scanned elements */ func scan <R> (_ initial: R, combine: (R, Iterator.Element) -> R) -> [R] } extension Sequence { func scan <R> (_ initial: R, combine: (R, Iterator.Element) -> R) -> [R] { var result = Array<R> (repeating: initial, count: 1) var accum = initial for elt in self { accum = combine (accum, elt) result.append(accum) } return result } } // Mark: Curried Functions /** * Curry application of `predicate` on `x`; returns a function of `y` returning `predicate(x,y)` * * - argument predicate: the predicate * - argument x: * * - returns: A function of (y:T) that returns predicate(x,y) */ public func equateUsing<T> (_ predicate: @escaping (T, T) -> Bool) -> (T) -> (T) -> Bool { return { (x:T) -> (T) -> Bool in return { (y:T) -> Bool in return predicate (x, y) } } } /** Curry `any()` using `predicate` */ public func anyUsing <S: Sequence> (_ predicate: @escaping (S.Iterator.Element) -> Bool) -> (S) -> Bool { return { (source:S) -> Bool in return source.any (predicate) } } /** Curry `all()` using `predicate`. */ public func allUsing <S: Sequence> (_ predicate: @escaping (S.Iterator.Element) -> Bool) -> (S) -> Bool { return { (source:S) -> Bool in return source.all (predicate) } } /** Curry `map()` using `transform`. */ public func mapUsing <S: Sequence, T> (_ transform: @escaping (S.Iterator.Element) -> T) -> (S) -> [T] { return { (source:S) in return source.map (transform) } } /** Curry `app()` using `body`. */ public func appUsing <S: Sequence> (_ body: @escaping (S.Iterator.Element) -> Void) -> (S) -> Void { return { (source:S) in return source.app (body) } }
mit
SwiftKitz/Appz
Appz/Appz/Apps/GoogleMail.swift
1
988
// // GoogleMail.swift // Pods // // Created by Mariam AlJamea on 1/2/16. // Copyright © 2016 kitz. All rights reserved. // public extension Applications { struct GoogleMail: ExternalApplication { public typealias ActionType = Applications.GoogleMail.Action public let scheme = "googlegmail:" public let fallbackURL = "https://mail.google.com/" public let appStoreId = "422689480" public init() {} } } // MARK: - Actions public extension Applications.GoogleMail { enum Action { case open } } extension Applications.GoogleMail.Action: ExternalApplicationAction { public var paths: ActionPaths { switch self { case .open: return ActionPaths( app: Path( pathComponents: ["app"], queryParameters: [:] ), web: Path() ) } } }
mit
LoopKit/LoopKit
LoopKitHostedTests/InsulinDeliveryStoreTests.swift
1
46170
// // InsulinDeliveryStoreTests.swift // LoopKitHostedTests // // Created by Darin Krauss on 10/22/20. // Copyright © 2020 LoopKit Authors. All rights reserved. // import XCTest import HealthKit @testable import LoopKit class InsulinDeliveryStoreTestsBase: PersistenceControllerTestCase { internal let entry1 = DoseEntry(type: .basal, startDate: Date(timeIntervalSinceNow: -.minutes(6)), endDate: Date(timeIntervalSinceNow: -.minutes(5.5)), value: 1.8, unit: .unitsPerHour, deliveredUnits: 0.015, syncIdentifier: "4B14522E-A7B5-4E73-B76B-5043CD7176B0", scheduledBasalRate: nil) internal let entry2 = DoseEntry(type: .tempBasal, startDate: Date(timeIntervalSinceNow: -.minutes(2)), endDate: Date(timeIntervalSinceNow: -.minutes(1.5)), value: 2.4, unit: .unitsPerHour, deliveredUnits: 0.02, syncIdentifier: "A1F8E29B-33D6-4B38-B4CD-D84F14744871", scheduledBasalRate: HKQuantity(unit: .internationalUnitsPerHour, doubleValue: 1.8)) internal let entry3 = DoseEntry(type: .bolus, startDate: Date(timeIntervalSinceNow: -.minutes(4)), endDate: Date(timeIntervalSinceNow: -.minutes(3.5)), value: 1.0, unit: .units, deliveredUnits: nil, syncIdentifier: "1A1D6192-1521-4469-B962-1B82C4534BB1", scheduledBasalRate: nil) internal let device = HKDevice(name: UUID().uuidString, manufacturer: UUID().uuidString, model: UUID().uuidString, hardwareVersion: UUID().uuidString, firmwareVersion: UUID().uuidString, softwareVersion: UUID().uuidString, localIdentifier: UUID().uuidString, udiDeviceIdentifier: UUID().uuidString) var healthStore: HKHealthStoreMock! var insulinDeliveryStore: InsulinDeliveryStore! var authorizationStatus: HKAuthorizationStatus = .notDetermined override func setUp() { super.setUp() let semaphore = DispatchSemaphore(value: 0) cacheStore.onReady { error in XCTAssertNil(error) semaphore.signal() } semaphore.wait() healthStore = HKHealthStoreMock() healthStore.authorizationStatus = authorizationStatus insulinDeliveryStore = InsulinDeliveryStore(healthStore: healthStore, cacheStore: cacheStore, cacheLength: .hours(1), provenanceIdentifier: HKSource.default().bundleIdentifier) } override func tearDown() { let semaphore = DispatchSemaphore(value: 0) insulinDeliveryStore.purgeAllDoseEntries(healthKitPredicate: HKQuery.predicateForObjects(from: HKSource.default())) { error in XCTAssertNil(error) semaphore.signal() } semaphore.wait() insulinDeliveryStore = nil healthStore = nil super.tearDown() } } class InsulinDeliveryStoreTestsAuthorized: InsulinDeliveryStoreTestsBase { override func setUp() { authorizationStatus = .sharingAuthorized super.setUp() } func testObserverQueryStartup() { // Check that an observer query was registered even before authorize() is called. XCTAssertFalse(insulinDeliveryStore.authorizationRequired); XCTAssertNotNil(insulinDeliveryStore.observerQuery); } } class InsulinDeliveryStoreTests: InsulinDeliveryStoreTestsBase { // MARK: - HealthKitSampleStore func testHealthKitQueryAnchorPersistence() { var observerQuery: HKObserverQueryMock? = nil var anchoredObjectQuery: HKAnchoredObjectQueryMock? = nil XCTAssert(insulinDeliveryStore.authorizationRequired); XCTAssertNil(insulinDeliveryStore.observerQuery); insulinDeliveryStore.createObserverQuery = { (sampleType, predicate, updateHandler) -> HKObserverQuery in observerQuery = HKObserverQueryMock(sampleType: sampleType, predicate: predicate, updateHandler: updateHandler) return observerQuery! } let authorizationCompletion = expectation(description: "authorization completion") insulinDeliveryStore.authorize { (result) in authorizationCompletion.fulfill() } waitForExpectations(timeout: 10) XCTAssertNotNil(observerQuery) let anchoredObjectQueryCreationExpectation = expectation(description: "anchored object query creation") insulinDeliveryStore.createAnchoredObjectQuery = { (sampleType, predicate, anchor, limit, resultsHandler) -> HKAnchoredObjectQuery in anchoredObjectQuery = HKAnchoredObjectQueryMock(type: sampleType, predicate: predicate, anchor: anchor, limit: limit, resultsHandler: resultsHandler) anchoredObjectQueryCreationExpectation.fulfill() return anchoredObjectQuery! } let observerQueryCompletionExpectation = expectation(description: "observer query completion") let observerQueryCompletionHandler = { observerQueryCompletionExpectation.fulfill() } // This simulates a signal marking the arrival of new HK Data. observerQuery!.updateHandler(observerQuery!, observerQueryCompletionHandler, nil) wait(for: [anchoredObjectQueryCreationExpectation], timeout: 10) // Trigger results handler for anchored object query let returnedAnchor = HKQueryAnchor(fromValue: 5) anchoredObjectQuery!.resultsHandler(anchoredObjectQuery!, [], [], returnedAnchor, nil) // Wait for observerQueryCompletionExpectation waitForExpectations(timeout: 10) XCTAssertNotNil(insulinDeliveryStore.queryAnchor) cacheStore.managedObjectContext.performAndWait {} // Create a new glucose store, and ensure it uses the last query anchor let newInsulinDeliveryStore = InsulinDeliveryStore(healthStore: healthStore, cacheStore: cacheStore, provenanceIdentifier: HKSource.default().bundleIdentifier) let newAuthorizationCompletion = expectation(description: "authorization completion") observerQuery = nil newInsulinDeliveryStore.createObserverQuery = { (sampleType, predicate, updateHandler) -> HKObserverQuery in observerQuery = HKObserverQueryMock(sampleType: sampleType, predicate: predicate, updateHandler: updateHandler) return observerQuery! } newInsulinDeliveryStore.authorize { (result) in newAuthorizationCompletion.fulfill() } waitForExpectations(timeout: 10) anchoredObjectQuery = nil let newAnchoredObjectQueryCreationExpectation = expectation(description: "new anchored object query creation") newInsulinDeliveryStore.createAnchoredObjectQuery = { (sampleType, predicate, anchor, limit, resultsHandler) -> HKAnchoredObjectQuery in anchoredObjectQuery = HKAnchoredObjectQueryMock(type: sampleType, predicate: predicate, anchor: anchor, limit: limit, resultsHandler: resultsHandler) newAnchoredObjectQueryCreationExpectation.fulfill() return anchoredObjectQuery! } // This simulates a signal marking the arrival of new HK Data. observerQuery!.updateHandler(observerQuery!, {}, nil) waitForExpectations(timeout: 10) // Assert new glucose store is querying with the last anchor that our HealthKit mock returned XCTAssertEqual(returnedAnchor, anchoredObjectQuery?.anchor) anchoredObjectQuery!.resultsHandler(anchoredObjectQuery!, [], [], returnedAnchor, nil) } // MARK: - Fetching func testGetDoseEntries() { let addDoseEntriesCompletion = expectation(description: "addDoseEntries") insulinDeliveryStore.addDoseEntries([entry1, entry2, entry3], from: device, syncVersion: 2) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success: break } addDoseEntriesCompletion.fulfill() } waitForExpectations(timeout: 10) let getDoseEntries1Completion = expectation(description: "getDoseEntries1") insulinDeliveryStore.getDoseEntries() { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 3) XCTAssertEqual(entries[0].type, self.entry1.type) XCTAssertEqual(entries[0].startDate, self.entry1.startDate) XCTAssertEqual(entries[0].endDate, self.entry1.endDate) XCTAssertEqual(entries[0].value, 0.015) XCTAssertEqual(entries[0].unit, .units) XCTAssertNil(entries[0].deliveredUnits) XCTAssertEqual(entries[0].description, self.entry1.description) XCTAssertEqual(entries[0].syncIdentifier, self.entry1.syncIdentifier) XCTAssertEqual(entries[0].scheduledBasalRate, self.entry1.scheduledBasalRate) XCTAssertEqual(entries[1].type, self.entry3.type) XCTAssertEqual(entries[1].startDate, self.entry3.startDate) XCTAssertEqual(entries[1].endDate, self.entry3.endDate) XCTAssertEqual(entries[1].value, self.entry3.value) XCTAssertEqual(entries[1].unit, self.entry3.unit) XCTAssertEqual(entries[1].deliveredUnits, self.entry3.deliveredUnits) XCTAssertEqual(entries[1].description, self.entry3.description) XCTAssertEqual(entries[1].syncIdentifier, self.entry3.syncIdentifier) XCTAssertEqual(entries[1].scheduledBasalRate, self.entry3.scheduledBasalRate) XCTAssertEqual(entries[2].type, self.entry2.type) XCTAssertEqual(entries[2].startDate, self.entry2.startDate) XCTAssertEqual(entries[2].endDate, self.entry2.endDate) XCTAssertEqual(entries[2].value, self.entry2.value) XCTAssertEqual(entries[2].unit, self.entry2.unit) XCTAssertEqual(entries[2].deliveredUnits, self.entry2.deliveredUnits) XCTAssertEqual(entries[2].description, self.entry2.description) XCTAssertEqual(entries[2].syncIdentifier, self.entry2.syncIdentifier) XCTAssertEqual(entries[2].scheduledBasalRate, self.entry2.scheduledBasalRate) } getDoseEntries1Completion.fulfill() } waitForExpectations(timeout: 10) let getDoseEntries2Completion = expectation(description: "getDoseEntries2") insulinDeliveryStore.getDoseEntries(start: Date(timeIntervalSinceNow: -.minutes(3.75)), end: Date(timeIntervalSinceNow: -.minutes(1.75))) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 2) XCTAssertEqual(entries[0].type, self.entry3.type) XCTAssertEqual(entries[0].startDate, self.entry3.startDate) XCTAssertEqual(entries[0].endDate, self.entry3.endDate) XCTAssertEqual(entries[0].value, self.entry3.value) XCTAssertEqual(entries[0].unit, self.entry3.unit) XCTAssertEqual(entries[0].deliveredUnits, self.entry3.deliveredUnits) XCTAssertEqual(entries[0].description, self.entry3.description) XCTAssertEqual(entries[0].syncIdentifier, self.entry3.syncIdentifier) XCTAssertEqual(entries[0].scheduledBasalRate, self.entry3.scheduledBasalRate) XCTAssertEqual(entries[1].type, self.entry2.type) XCTAssertEqual(entries[1].startDate, self.entry2.startDate) XCTAssertEqual(entries[1].endDate, self.entry2.endDate) XCTAssertEqual(entries[1].value, self.entry2.value) XCTAssertEqual(entries[1].unit, self.entry2.unit) XCTAssertEqual(entries[1].deliveredUnits, self.entry2.deliveredUnits) XCTAssertEqual(entries[1].description, self.entry2.description) XCTAssertEqual(entries[1].syncIdentifier, self.entry2.syncIdentifier) XCTAssertEqual(entries[1].scheduledBasalRate, self.entry2.scheduledBasalRate) } getDoseEntries2Completion.fulfill() } waitForExpectations(timeout: 10) let purgeCachedInsulinDeliveryObjectsCompletion = expectation(description: "purgeCachedInsulinDeliveryObjects") insulinDeliveryStore.purgeCachedInsulinDeliveryObjects() { error in XCTAssertNil(error) purgeCachedInsulinDeliveryObjectsCompletion.fulfill() } waitForExpectations(timeout: 10) let getDoseEntries3Completion = expectation(description: "getDoseEntries3") insulinDeliveryStore.getDoseEntries() { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 0) } getDoseEntries3Completion.fulfill() } waitForExpectations(timeout: 10) } func testLastBasalEndDate() { let getLastImmutableBasalEndDate1Completion = expectation(description: "getLastImmutableBasalEndDate1") insulinDeliveryStore.getLastImmutableBasalEndDate() { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let lastBasalEndDate): XCTAssertEqual(lastBasalEndDate, .distantPast) } getLastImmutableBasalEndDate1Completion.fulfill() } waitForExpectations(timeout: 10) let addDoseEntriesCompletion = expectation(description: "addDoseEntries") insulinDeliveryStore.addDoseEntries([entry1, entry2, entry3], from: device, syncVersion: 2) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success: break } addDoseEntriesCompletion.fulfill() } waitForExpectations(timeout: 10) let getLastImmutableBasalEndDate2Completion = expectation(description: "getLastImmutableBasalEndDate2") insulinDeliveryStore.getLastImmutableBasalEndDate() { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let lastBasalEndDate): XCTAssertEqual(lastBasalEndDate, self.entry2.endDate) } getLastImmutableBasalEndDate2Completion.fulfill() } waitForExpectations(timeout: 10) let purgeCachedInsulinDeliveryObjectsCompletion = expectation(description: "purgeCachedInsulinDeliveryObjects") insulinDeliveryStore.purgeCachedInsulinDeliveryObjects() { error in XCTAssertNil(error) purgeCachedInsulinDeliveryObjectsCompletion.fulfill() } waitForExpectations(timeout: 10) let getLastImmutableBasalEndDate3Completion = expectation(description: "getLastImmutableBasalEndDate3") insulinDeliveryStore.getLastImmutableBasalEndDate() { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let lastBasalEndDate): XCTAssertEqual(lastBasalEndDate, .distantPast) } getLastImmutableBasalEndDate3Completion.fulfill() } waitForExpectations(timeout: 10) } // MARK: - Modification func testAddDoseEntries() { let addDoseEntries1Completion = expectation(description: "addDoseEntries1") insulinDeliveryStore.addDoseEntries([entry1, entry2, entry3], from: device, syncVersion: 2) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success: break } addDoseEntries1Completion.fulfill() } waitForExpectations(timeout: 10) let getDoseEntries1Completion = expectation(description: "getDoseEntries1") insulinDeliveryStore.getDoseEntries() { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 3) XCTAssertEqual(entries[0].type, self.entry1.type) XCTAssertEqual(entries[0].startDate, self.entry1.startDate) XCTAssertEqual(entries[0].endDate, self.entry1.endDate) XCTAssertEqual(entries[0].value, 0.015) XCTAssertEqual(entries[0].unit, .units) XCTAssertNil(entries[0].deliveredUnits) XCTAssertEqual(entries[0].description, self.entry1.description) XCTAssertEqual(entries[0].syncIdentifier, self.entry1.syncIdentifier) XCTAssertEqual(entries[0].scheduledBasalRate, self.entry1.scheduledBasalRate) XCTAssertEqual(entries[1].type, self.entry3.type) XCTAssertEqual(entries[1].startDate, self.entry3.startDate) XCTAssertEqual(entries[1].endDate, self.entry3.endDate) XCTAssertEqual(entries[1].value, self.entry3.value) XCTAssertEqual(entries[1].unit, self.entry3.unit) XCTAssertEqual(entries[1].deliveredUnits, self.entry3.deliveredUnits) XCTAssertEqual(entries[1].description, self.entry3.description) XCTAssertEqual(entries[1].syncIdentifier, self.entry3.syncIdentifier) XCTAssertEqual(entries[1].scheduledBasalRate, self.entry3.scheduledBasalRate) XCTAssertEqual(entries[2].type, self.entry2.type) XCTAssertEqual(entries[2].startDate, self.entry2.startDate) XCTAssertEqual(entries[2].endDate, self.entry2.endDate) XCTAssertEqual(entries[2].value, self.entry2.value) XCTAssertEqual(entries[2].unit, self.entry2.unit) XCTAssertEqual(entries[2].deliveredUnits, self.entry2.deliveredUnits) XCTAssertEqual(entries[2].description, self.entry2.description) XCTAssertEqual(entries[2].syncIdentifier, self.entry2.syncIdentifier) XCTAssertEqual(entries[2].scheduledBasalRate, self.entry2.scheduledBasalRate) } getDoseEntries1Completion.fulfill() } waitForExpectations(timeout: 10) let addDoseEntries2Completion = expectation(description: "addDoseEntries2") insulinDeliveryStore.addDoseEntries([entry3, entry1, entry2], from: device, syncVersion: 2) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success: break } addDoseEntries2Completion.fulfill() } waitForExpectations(timeout: 10) let getDoseEntries2Completion = expectation(description: "getDoseEntries2Completion") insulinDeliveryStore.getDoseEntries() { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 3) XCTAssertEqual(entries[0].type, self.entry1.type) XCTAssertEqual(entries[0].startDate, self.entry1.startDate) XCTAssertEqual(entries[0].endDate, self.entry1.endDate) XCTAssertEqual(entries[0].value, 0.015) XCTAssertEqual(entries[0].unit, .units) XCTAssertNil(entries[0].deliveredUnits) XCTAssertEqual(entries[0].description, self.entry1.description) XCTAssertEqual(entries[0].syncIdentifier, self.entry1.syncIdentifier) XCTAssertEqual(entries[0].scheduledBasalRate, self.entry1.scheduledBasalRate) XCTAssertEqual(entries[1].type, self.entry3.type) XCTAssertEqual(entries[1].startDate, self.entry3.startDate) XCTAssertEqual(entries[1].endDate, self.entry3.endDate) XCTAssertEqual(entries[1].value, self.entry3.value) XCTAssertEqual(entries[1].unit, self.entry3.unit) XCTAssertEqual(entries[1].deliveredUnits, self.entry3.deliveredUnits) XCTAssertEqual(entries[1].description, self.entry3.description) XCTAssertEqual(entries[1].syncIdentifier, self.entry3.syncIdentifier) XCTAssertEqual(entries[1].scheduledBasalRate, self.entry3.scheduledBasalRate) XCTAssertEqual(entries[2].type, self.entry2.type) XCTAssertEqual(entries[2].startDate, self.entry2.startDate) XCTAssertEqual(entries[2].endDate, self.entry2.endDate) XCTAssertEqual(entries[2].value, self.entry2.value) XCTAssertEqual(entries[2].unit, self.entry2.unit) XCTAssertEqual(entries[2].deliveredUnits, self.entry2.deliveredUnits) XCTAssertEqual(entries[2].description, self.entry2.description) XCTAssertEqual(entries[2].syncIdentifier, self.entry2.syncIdentifier) XCTAssertEqual(entries[2].scheduledBasalRate, self.entry2.scheduledBasalRate) } getDoseEntries2Completion.fulfill() } waitForExpectations(timeout: 10) } func testAddDoseEntriesEmpty() { let addDoseEntriesCompletion = expectation(description: "addDoseEntries") insulinDeliveryStore.addDoseEntries([], from: device, syncVersion: 2) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success: break } addDoseEntriesCompletion.fulfill() } waitForExpectations(timeout: 10) } func testAddDoseEntriesNotification() { let doseEntriesDidChangeCompletion = expectation(description: "doseEntriesDidChange") let observer = NotificationCenter.default.addObserver(forName: InsulinDeliveryStore.doseEntriesDidChange, object: insulinDeliveryStore, queue: nil) { notification in doseEntriesDidChangeCompletion.fulfill() } let addDoseEntriesCompletion = expectation(description: "addDoseEntries") insulinDeliveryStore.addDoseEntries([entry1, entry2, entry3], from: device, syncVersion: 2) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success: break } addDoseEntriesCompletion.fulfill() } wait(for: [doseEntriesDidChangeCompletion, addDoseEntriesCompletion], timeout: 10, enforceOrder: true) NotificationCenter.default.removeObserver(observer) } func testManuallyEnteredDoses() { let manualEntry = DoseEntry(type: .bolus, startDate: Date(timeIntervalSinceNow: -.minutes(15)), endDate: Date(timeIntervalSinceNow: -.minutes(10)), value: 3.0, unit: .units, syncIdentifier: "C0AB1CBD-6B36-4113-9D49-709A022B2451", manuallyEntered: true) let addDoseEntriesCompletion = expectation(description: "addDoseEntries") insulinDeliveryStore.addDoseEntries([entry1, manualEntry, entry2, entry3], from: device, syncVersion: 2) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success: break } addDoseEntriesCompletion.fulfill() } waitForExpectations(timeout: 10) let getManuallyEnteredDoses1Completion = expectation(description: "getManuallyEnteredDoses1") insulinDeliveryStore.getManuallyEnteredDoses(since: .distantPast) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 1) XCTAssertEqual(entries[0], manualEntry) } getManuallyEnteredDoses1Completion.fulfill() } waitForExpectations(timeout: 10) let getManuallyEnteredDoses2Completion = expectation(description: "getManuallyEnteredDoses2") insulinDeliveryStore.getManuallyEnteredDoses(since: Date(timeIntervalSinceNow: -.minutes(12))) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 0) } getManuallyEnteredDoses2Completion.fulfill() } waitForExpectations(timeout: 10) let deleteAllManuallyEnteredDoses1Completion = expectation(description: "deleteAllManuallyEnteredDoses1") insulinDeliveryStore.deleteAllManuallyEnteredDoses(since: Date(timeIntervalSinceNow: -.minutes(12))) { error in XCTAssertNil(error) deleteAllManuallyEnteredDoses1Completion.fulfill() } waitForExpectations(timeout: 10) let getManuallyEnteredDoses3Completion = expectation(description: "getManuallyEnteredDoses3") insulinDeliveryStore.getManuallyEnteredDoses(since: .distantPast) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 1) XCTAssertEqual(entries[0], manualEntry) } getManuallyEnteredDoses3Completion.fulfill() } waitForExpectations(timeout: 10) let deleteAllManuallyEnteredDose2Completion = expectation(description: "deleteAllManuallyEnteredDose2") insulinDeliveryStore.deleteAllManuallyEnteredDoses(since: Date(timeIntervalSinceNow: -.minutes(20))) { error in XCTAssertNil(error) deleteAllManuallyEnteredDose2Completion.fulfill() } waitForExpectations(timeout: 10) let getManuallyEnteredDoses4Completion = expectation(description: "getManuallyEnteredDoses4") insulinDeliveryStore.getManuallyEnteredDoses(since: .distantPast) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 0) } getManuallyEnteredDoses4Completion.fulfill() } waitForExpectations(timeout: 10) } // MARK: - Cache Management func testEarliestCacheDate() { XCTAssertEqual(insulinDeliveryStore.earliestCacheDate.timeIntervalSinceNow, -.hours(1), accuracy: 1) } func testPurgeAllDoseEntries() { let addDoseEntriesCompletion = expectation(description: "addDoseEntries") insulinDeliveryStore.addDoseEntries([entry1, entry2, entry3], from: device, syncVersion: 2) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success: break } addDoseEntriesCompletion.fulfill() } waitForExpectations(timeout: 10) let getDoseEntries1Completion = expectation(description: "getDoseEntries1") insulinDeliveryStore.getDoseEntries() { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 3) } getDoseEntries1Completion.fulfill() } waitForExpectations(timeout: 10) let purgeAllDoseEntriesCompletion = expectation(description: "purgeAllDoseEntries") insulinDeliveryStore.purgeAllDoseEntries(healthKitPredicate: HKQuery.predicateForObjects(from: HKSource.default())) { error in XCTAssertNil(error) purgeAllDoseEntriesCompletion.fulfill() } waitForExpectations(timeout: 10) let getDoseEntries2Completion = expectation(description: "getDoseEntries2") insulinDeliveryStore.getDoseEntries() { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 0) } getDoseEntries2Completion.fulfill() } waitForExpectations(timeout: 10) } func testPurgeExpiredGlucoseObjects() { let expiredEntry = DoseEntry(type: .bolus, startDate: Date(timeIntervalSinceNow: -.hours(3)), endDate: Date(timeIntervalSinceNow: -.hours(2)), value: 3.0, unit: .units, deliveredUnits: nil, syncIdentifier: "7530B8CA-827A-4DE8-ADE3-9E10FF80A4A9", scheduledBasalRate: nil) let addDoseEntriesCompletion = expectation(description: "addDoseEntries") insulinDeliveryStore.addDoseEntries([entry1, entry2, entry3, expiredEntry], from: device, syncVersion: 2) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success: break } addDoseEntriesCompletion.fulfill() } waitForExpectations(timeout: 10) let getDoseEntriesCompletion = expectation(description: "getDoseEntries") insulinDeliveryStore.getDoseEntries() { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 3) } getDoseEntriesCompletion.fulfill() } waitForExpectations(timeout: 10) } func testPurgeCachedInsulinDeliveryObjects() { let addDoseEntriesCompletion = expectation(description: "addDoseEntries") insulinDeliveryStore.addDoseEntries([entry1, entry2, entry3], from: device, syncVersion: 2) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success: break } addDoseEntriesCompletion.fulfill() } waitForExpectations(timeout: 10) let getDoseEntries1Completion = expectation(description: "getDoseEntries1") insulinDeliveryStore.getDoseEntries() { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 3) } getDoseEntries1Completion.fulfill() } waitForExpectations(timeout: 10) let purgeCachedInsulinDeliveryObjects1Completion = expectation(description: "purgeCachedInsulinDeliveryObjects1") insulinDeliveryStore.purgeCachedInsulinDeliveryObjects(before: Date(timeIntervalSinceNow: -.minutes(5))) { error in XCTAssertNil(error) purgeCachedInsulinDeliveryObjects1Completion.fulfill() } waitForExpectations(timeout: 10) let getDoseEntries2Completion = expectation(description: "getDoseEntries2") insulinDeliveryStore.getDoseEntries() { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 2) } getDoseEntries2Completion.fulfill() } waitForExpectations(timeout: 10) let purgeCachedInsulinDeliveryObjects2Completion = expectation(description: "purgeCachedInsulinDeliveryObjects2") insulinDeliveryStore.purgeCachedInsulinDeliveryObjects() { error in XCTAssertNil(error) purgeCachedInsulinDeliveryObjects2Completion.fulfill() } waitForExpectations(timeout: 10) let getDoseEntries3Completion = expectation(description: "getDoseEntries3") insulinDeliveryStore.getDoseEntries() { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let entries): XCTAssertEqual(entries.count, 0) } getDoseEntries3Completion.fulfill() } waitForExpectations(timeout: 10) } func testPurgeCachedInsulinDeliveryObjectsNotification() { let addDoseEntriesCompletion = expectation(description: "addDoseEntries") insulinDeliveryStore.addDoseEntries([entry1, entry2, entry3], from: device, syncVersion: 2) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success: break } addDoseEntriesCompletion.fulfill() } waitForExpectations(timeout: 10) let doseEntriesDidChangeCompletion = expectation(description: "doseEntriesDidChange") let observer = NotificationCenter.default.addObserver(forName: InsulinDeliveryStore.doseEntriesDidChange, object: insulinDeliveryStore, queue: nil) { notification in doseEntriesDidChangeCompletion.fulfill() } let purgeCachedInsulinDeliveryObjectsCompletion = expectation(description: "purgeCachedInsulinDeliveryObjects") insulinDeliveryStore.purgeCachedInsulinDeliveryObjects() { error in XCTAssertNil(error) purgeCachedInsulinDeliveryObjectsCompletion.fulfill() } wait(for: [doseEntriesDidChangeCompletion, purgeCachedInsulinDeliveryObjectsCompletion], timeout: 10, enforceOrder: true) NotificationCenter.default.removeObserver(observer) } } class InsulinDeliveryStoreQueryAnchorTests: XCTestCase { var rawValue: InsulinDeliveryStore.QueryAnchor.RawValue = [ "modificationCounter": Int64(123) ] func testInitializerDefault() { let queryAnchor = InsulinDeliveryStore.QueryAnchor() XCTAssertEqual(queryAnchor.modificationCounter, 0) } func testInitializerRawValue() { let queryAnchor = InsulinDeliveryStore.QueryAnchor(rawValue: rawValue) XCTAssertNotNil(queryAnchor) XCTAssertEqual(queryAnchor?.modificationCounter, 123) } func testInitializerRawValueMissingModificationCounter() { rawValue["modificationCounter"] = nil XCTAssertNil(InsulinDeliveryStore.QueryAnchor(rawValue: rawValue)) } func testInitializerRawValueInvalidModificationCounter() { rawValue["modificationCounter"] = "123" XCTAssertNil(InsulinDeliveryStore.QueryAnchor(rawValue: rawValue)) } func testRawValueWithDefault() { let rawValue = InsulinDeliveryStore.QueryAnchor().rawValue XCTAssertEqual(rawValue.count, 1) XCTAssertEqual(rawValue["modificationCounter"] as? Int64, Int64(0)) } func testRawValueWithNonDefault() { var queryAnchor = InsulinDeliveryStore.QueryAnchor() queryAnchor.modificationCounter = 123 let rawValue = queryAnchor.rawValue XCTAssertEqual(rawValue.count, 1) XCTAssertEqual(rawValue["modificationCounter"] as? Int64, Int64(123)) } } class InsulinDeliveryStoreQueryTests: PersistenceControllerTestCase { let insulinModel = WalshInsulinModel(actionDuration: .hours(4)) let basalProfile = BasalRateSchedule(rawValue: ["timeZone": -28800, "items": [["value": 0.75, "startTime": 0.0], ["value": 0.8, "startTime": 10800.0], ["value": 0.85, "startTime": 32400.0], ["value": 1.0, "startTime": 68400.0]]]) let insulinSensitivitySchedule = InsulinSensitivitySchedule(rawValue: ["unit": "mg/dL", "timeZone": -28800, "items": [["value": 40.0, "startTime": 0.0], ["value": 35.0, "startTime": 21600.0], ["value": 40.0, "startTime": 57600.0]]]) var insulinDeliveryStore: InsulinDeliveryStore! var completion: XCTestExpectation! var queryAnchor: InsulinDeliveryStore.QueryAnchor! var limit: Int! override func setUp() { super.setUp() insulinDeliveryStore = InsulinDeliveryStore(healthStore: HKHealthStoreMock(), storeSamplesToHealthKit: false, cacheStore: cacheStore, observationEnabled: false, provenanceIdentifier: HKSource.default().bundleIdentifier) completion = expectation(description: "Completion") queryAnchor = InsulinDeliveryStore.QueryAnchor() limit = Int.max } override func tearDown() { limit = nil queryAnchor = nil completion = nil insulinDeliveryStore = nil super.tearDown() } func testDoseEmptyWithDefaultQueryAnchor() { insulinDeliveryStore.executeDoseQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let created, let deleted): XCTAssertEqual(anchor.modificationCounter, 0) XCTAssertEqual(created.count, 0) XCTAssertEqual(deleted.count, 0) } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } func testDoseEmptyWithMissingQueryAnchor() { queryAnchor = nil insulinDeliveryStore.executeDoseQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let created, let deleted): XCTAssertEqual(anchor.modificationCounter, 0) XCTAssertEqual(created.count, 0) XCTAssertEqual(deleted.count, 0) } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } func testDoseEmptyWithNonDefaultQueryAnchor() { queryAnchor.modificationCounter = 1 insulinDeliveryStore.executeDoseQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let created, let deleted): XCTAssertEqual(anchor.modificationCounter, 1) XCTAssertEqual(created.count, 0) XCTAssertEqual(deleted.count, 0) } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } func testDoseDataWithUnusedQueryAnchor() { let doseData = [DoseDatum(), DoseDatum(deleted: true), DoseDatum()] addDoseData(doseData) insulinDeliveryStore.executeDoseQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let created, let deleted): XCTAssertEqual(anchor.modificationCounter, 3) XCTAssertEqual(created.count, 2) XCTAssertEqual(deleted.count, 1) if created.count >= 2 { XCTAssertEqual(created[0].syncIdentifier, doseData[0].syncIdentifier) XCTAssertEqual(created[1].syncIdentifier, doseData[2].syncIdentifier) } if deleted.count >= 1 { XCTAssertEqual(deleted[0].syncIdentifier, doseData[1].syncIdentifier) } } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } func testDoseDataWithStaleQueryAnchor() { let doseData = [DoseDatum(), DoseDatum(deleted: true), DoseDatum()] addDoseData(doseData) queryAnchor.modificationCounter = 2 insulinDeliveryStore.executeDoseQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let created, let deleted): XCTAssertEqual(anchor.modificationCounter, 3) XCTAssertEqual(created.count, 1) XCTAssertEqual(deleted.count, 0) if created.count >= 1 { XCTAssertEqual(created[0].syncIdentifier, doseData[2].syncIdentifier) } } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } func testDoseDataWithCurrentQueryAnchor() { let doseData = [DoseDatum(), DoseDatum(deleted: true), DoseDatum()] addDoseData(doseData) queryAnchor.modificationCounter = 3 insulinDeliveryStore.executeDoseQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let created, let deleted): XCTAssertEqual(anchor.modificationCounter, 3) XCTAssertEqual(created.count, 0) XCTAssertEqual(deleted.count, 0) } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } func testDoseDataWithLimitCoveredByData() { let doseData = [DoseDatum(), DoseDatum(deleted: true), DoseDatum()] addDoseData(doseData) limit = 2 insulinDeliveryStore.executeDoseQuery(fromQueryAnchor: queryAnchor, limit: limit) { result in switch result { case .failure(let error): XCTFail("Unexpected failure: \(error)") case .success(let anchor, let created, let deleted): XCTAssertEqual(anchor.modificationCounter, 2) XCTAssertEqual(created.count, 1) XCTAssertEqual(deleted.count, 1) if created.count >= 1 { XCTAssertEqual(created[0].syncIdentifier, doseData[0].syncIdentifier) } if deleted.count >= 1 { XCTAssertEqual(deleted[0].syncIdentifier, doseData[1].syncIdentifier) } } self.completion.fulfill() } wait(for: [completion], timeout: 2, enforceOrder: true) } private func addDoseData(_ doseData: [DoseDatum]) { cacheStore.managedObjectContext.performAndWait { for doseDatum in doseData { let object = CachedInsulinDeliveryObject(context: self.cacheStore.managedObjectContext) object.provenanceIdentifier = HKSource.default().bundleIdentifier object.hasLoopKitOrigin = true object.startDate = Date().addingTimeInterval(-.minutes(15)) object.endDate = Date().addingTimeInterval(-.minutes(5)) object.syncIdentifier = doseDatum.syncIdentifier object.value = 1.0 object.reason = .bolus object.createdAt = Date() object.deletedAt = doseDatum.deleted ? Date() : nil object.manuallyEntered = false object.isSuspend = false self.cacheStore.save() } } } private struct DoseDatum { let syncIdentifier: String let deleted: Bool init(deleted: Bool = false) { self.syncIdentifier = UUID().uuidString self.deleted = deleted } } }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/07531-swift-sourcemanager-getmessage.swift
11
261
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct S<d { var b = [Void{ if true { class A : C { protocol A { class case c, protocol A {
mit
ryuichis/swift-ast
Sources/Parser/Parser+Type.swift
2
15909
/* Copyright 2016-2018 Ryuichi Intellectual Property and the Yanagiba project 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 AST import Lexer import Source extension Parser { func parseTypeAnnotation() throws -> TypeAnnotation? { let startLocation = getStartLocation() guard _lexer.match(.colon) else { return nil } var isInOutParameter = false let attrs = try parseAttributes() if _lexer.look().kind == .inout { _lexer.advance() isInOutParameter = true } let type = try parseType() let typeAnnotation = TypeAnnotation(type: type, attributes: attrs, isInOutParameter: isInOutParameter) typeAnnotation.setSourceRange(startLocation, type.sourceRange.end) return typeAnnotation } func parseType() throws -> Type { let attrs = try parseAttributes() let isOpaqueType = isOpaqueTypeHead() let atomicType = try parseAtomicType() let containerType = try parseContainerType(atomicType, attributes: attrs) return isOpaqueType ? OpaqueType(wrappedType: containerType) : containerType } func isOpaqueTypeHead() -> Bool { guard case .name("some")? = _lexer.look().kind.namedIdentifier else { return false } _lexer.advance() return true } private func parseAtomicType() throws -> Type { let lookedRange = getLookedRange() let matched = _lexer.read([ .leftSquare, .leftParen, .protocol, .Any, .Self, ]) switch matched { case .leftSquare: return try parseCollectionType(lookedRange.start) case .leftParen: return try parseParenthesizedType(lookedRange.start) case .protocol: return try parseOldSyntaxProtocolCompositionType(lookedRange.start) case .Any: let anyType = AnyType() anyType.setSourceRange(lookedRange) return anyType case .Self: let selfType = SelfType() selfType.setSourceRange(lookedRange) return selfType default: if let idHead = readNamedIdentifier() { return try parseIdentifierType(idHead, lookedRange) } else { throw _raiseFatal(.expectedType) } } } func parseIdentifierType(_ headId: Identifier, _ startRange: SourceRange) throws -> TypeIdentifier { var endLocation = startRange.end let headGenericArgumentClause = parseGenericArgumentClause() if let headGenericArg = headGenericArgumentClause { endLocation = headGenericArg.sourceRange.end } var names = [ TypeIdentifier.TypeName(name: headId, genericArgumentClause: headGenericArgumentClause) ] while _lexer.look().kind == .dot, case let .identifier(name, backticked) = _lexer.readNext(.dummyIdentifier) { endLocation = getStartLocation() let genericArgumentClause = parseGenericArgumentClause() if let genericArg = genericArgumentClause { endLocation = genericArg.sourceRange.end } let typeIdentifierName = TypeIdentifier.TypeName( name: backticked ? .backtickedName(name) : .name(name), genericArgumentClause: genericArgumentClause) names.append(typeIdentifierName) } let idType = TypeIdentifier(names: names) idType.setSourceRange(startRange.start, endLocation) return idType } private func parseCollectionType(_ startLocation: SourceLocation) throws -> Type { let type = try parseType() var endLocation = getEndLocation() switch _lexer.read([.rightSquare, .colon]) { case .rightSquare: let arrayType = ArrayType(elementType: type) arrayType.setSourceRange(startLocation, endLocation) return arrayType case .colon: let valueType = try parseType() endLocation = getEndLocation() try match(.rightSquare, orFatal: .expectedCloseSquareDictionaryType) let dictType = DictionaryType(keyType: type, valueType: valueType) dictType.setSourceRange(startLocation, endLocation) return dictType default: throw _raiseFatal(.expectedCloseSquareArrayType) } } private func parseParenthesizedType(_ startLocation: SourceLocation) throws -> ParenthesizedType { var endLocation = getEndLocation() if _lexer.match(.rightParen) { let parenType = ParenthesizedType(elements: []) parenType.sourceRange = SourceRange(start: startLocation, end: endLocation) return parenType } var elements: [ParenthesizedType.Element] = [] repeat { let element = try parseParenthesizedTypeElement() elements.append(element) } while _lexer.match(.comma) endLocation = getEndLocation() try match(.rightParen, orFatal: .expectedCloseParenParenthesizedType) let parenType = ParenthesizedType(elements: elements) parenType.sourceRange = SourceRange(start: startLocation, end: endLocation) return parenType } func parseTupleType(_ startLocation: SourceLocation) throws -> TupleType { return try parseParenthesizedType(startLocation).toTupleType() } private func parseParenthesizedTypeElement() throws -> ParenthesizedType.Element { var externalName: Identifier? var localName: Identifier? let type: Type var attributes: [Attribute] = [] var isInOutParameter = false let looked = _lexer.look() switch looked.kind { case .at: attributes = try parseAttributes() isInOutParameter = _lexer.match(.inout) type = try parseType() case .inout: isInOutParameter = true _lexer.advance() type = try parseType() default: if let name = looked.kind.namedIdentifierOrWildcard?.id { let elementBody = try parseParenthesizedTypeElementBody(name) type = elementBody.type externalName = elementBody.externalName localName = elementBody.localName attributes = elementBody.attributes isInOutParameter = elementBody.isInOutParameter } else { type = try parseType() } } let isVariadic = _lexer.match([ .prefixOperator("..."), .binaryOperator("..."), .postfixOperator("..."), ], exactMatch: true) return ParenthesizedType.Element( type: type, externalName: externalName, localName: localName, attributes: attributes, isInOutParameter: isInOutParameter, isVariadic: isVariadic) } private func parseParenthesizedTypeElementBody(_ name: Identifier) throws -> ParenthesizedType.Element { var externalName: Identifier? var internalName: Identifier? if let secondName = _lexer.look(ahead: 1).kind.namedIdentifier?.id, _lexer.look(ahead: 2).kind == .colon { externalName = name internalName = secondName _lexer.advance(by: 2) } else if _lexer.look(ahead: 1).kind == .colon { internalName = name _lexer.advance() } else { let nonLabeledType = try parseType() return ParenthesizedType.Element(type: nonLabeledType) } guard let typeAnnotation = try parseTypeAnnotation() else { throw _raiseFatal(.expectedTypeInTuple) } return ParenthesizedType.Element( type: typeAnnotation.type, externalName: externalName, localName: internalName, attributes: typeAnnotation.attributes, isInOutParameter: typeAnnotation.isInOutParameter) } func parseProtocolCompositionType(_ type: Type) throws -> ProtocolCompositionType { var endLocation = type.sourceRange.end var protocolTypes = [type] repeat { let idTypeRange = getLookedRange() guard let idHead = readNamedIdentifier() else { throw _raiseFatal(.expectedIdentifierTypeForProtocolComposition) } let idType = try parseIdentifierType(idHead, idTypeRange) protocolTypes.append(idType) endLocation = idType.sourceRange.end } while testAmp() let protoType = ProtocolCompositionType(protocolTypes: protocolTypes) protoType.setSourceRange(type.sourceLocation, endLocation) return protoType } func parseOldSyntaxProtocolCompositionType(_ startLocation: SourceLocation) throws -> ProtocolCompositionType { try assert(_lexer.matchUnicodeScalar("<"), orFatal: .expectedLeftChevronProtocolComposition) if _lexer.matchUnicodeScalar(">") { return ProtocolCompositionType(protocolTypes: []) } var protocolTypes: [Type] = [] repeat { let nestedRange = getLookedRange() guard let idHead = readNamedIdentifier() else { throw _raiseFatal(.expectedIdentifierTypeForProtocolComposition) } protocolTypes.append(try parseIdentifierType(idHead, nestedRange)) } while _lexer.match(.comma) let endLocation = getEndLocation() try assert(_lexer.matchUnicodeScalar(">"), orFatal: .expectedRightChevronProtocolComposition) let protoType = ProtocolCompositionType(protocolTypes: protocolTypes) protoType.setSourceRange(startLocation, endLocation) return protoType } private func parseContainerType( /* swift-lint:rule_configure(CYCLOMATIC_COMPLEXITY=16) swift-lint:suppress(high_ncss) */ _ type: Type, attributes attrs: Attributes = [] ) throws -> Type { func getAtomicType() throws -> Type { do { if let parenthesizedType = type as? ParenthesizedType { return try parenthesizedType.toTupleType() } return type } catch ParenthesizedType.TupleConversionError.isVariadic { throw _raiseFatal(.tupleTypeVariadicElement) } catch ParenthesizedType.TupleConversionError.multipleLabels { throw _raiseFatal(.tupleTypeMultipleLabels) } } if _lexer.matchUnicodeScalar("?", immediateFollow: true) { let atomicType = try getAtomicType() let containerType = OptionalType(wrappedType: atomicType) containerType.setSourceRange(atomicType.sourceLocation, atomicType.sourceRange.end.nextColumn) return try parseContainerType(containerType) } if _lexer.matchUnicodeScalar("!", immediateFollow: true) { let atomicType = try getAtomicType() let containerType = ImplicitlyUnwrappedOptionalType(wrappedType: atomicType) containerType.setSourceRange(atomicType.sourceLocation, atomicType.sourceRange.end.nextColumn) return try parseContainerType(containerType) } if testAmp() { let atomicType = try getAtomicType() let protocolCompositionType = try parseProtocolCompositionType(atomicType) return try parseContainerType(protocolCompositionType) } let examined = _lexer.examine([ .throws, .rethrows, .arrow, .dot, ]) guard examined.0 else { return try getAtomicType() } var parsedType: Type switch examined.1 { case .throws: try match(.arrow, orFatal: .throwsInWrongPosition("throws")) parsedType = try parseFunctionType(attributes: attrs, type: type, throwKind: .throwing) case .rethrows: try match(.arrow, orFatal: .throwsInWrongPosition("rethrows")) parsedType = try parseFunctionType(attributes: attrs, type: type, throwKind: .rethrowing) case .arrow: parsedType = try parseFunctionType(attributes: attrs, type: type, throwKind: .nothrowing) case .dot: let atomicType = try getAtomicType() let metatypeEndLocation = getEndLocation() let metatypeType: MetatypeType switch _lexer.read([.Type, .Protocol]) { case .Type: metatypeType = MetatypeType(referenceType: atomicType, kind: .type) case .Protocol: metatypeType = MetatypeType(referenceType: atomicType, kind: .protocol) default: throw _raiseFatal(.wrongIdentifierForMetatypeType) } metatypeType.setSourceRange(type.sourceLocation, metatypeEndLocation) parsedType = metatypeType default: return try getAtomicType() } return try parseContainerType(parsedType) } private func parseFunctionType(attributes attrs: Attributes, type: Type, throwKind: ThrowsKind) throws -> Type { guard let parenthesizedType = type as? ParenthesizedType else { throw _raiseFatal(.expectedFunctionTypeArguments) } let funcArguments = parenthesizedType.elements.map { FunctionType.Argument(type: $0.type, externalName: $0.externalName, localName: $0.localName, attributes: $0.attributes, isInOutParameter: $0.isInOutParameter, isVariadic: $0.isVariadic) } let returnType = try parseType() let funcType = FunctionType( attributes: attrs, arguments: funcArguments, returnType: returnType, throwsKind: throwKind) funcType.setSourceRange(type.sourceLocation, returnType.sourceRange.end) return funcType } func parseTypeInheritanceClause() throws -> TypeInheritanceClause? { guard _lexer.match(.colon) else { return nil } var classRequirement = false if _lexer.match(.class) { classRequirement = true guard _lexer.match(.comma) else { return TypeInheritanceClause(classRequirement: classRequirement) } } var types = [TypeIdentifier]() repeat { let typeSourceRange = getLookedRange() if _lexer.match(.class) { throw _raiseFatal(.lateClassRequirement) } else if let idHead = readNamedIdentifier() { let type = try parseIdentifierType(idHead, typeSourceRange) types.append(type) } else { throw _raiseFatal(.expectedTypeRestriction) } } while _lexer.match(.comma) return TypeInheritanceClause( classRequirement: classRequirement, typeInheritanceList: types) } } fileprivate class ParenthesizedType : Type { fileprivate enum TupleConversionError : Error { case isVariadic case multipleLabels } fileprivate class Element { fileprivate let externalName: Identifier? fileprivate let localName: Identifier? fileprivate let type: Type fileprivate let attributes: Attributes fileprivate let isInOutParameter: Bool fileprivate let isVariadic: Bool fileprivate init(type: Type, externalName: Identifier? = nil, localName: Identifier? = nil, attributes: Attributes = [], isInOutParameter: Bool = false, isVariadic: Bool = false) { self.externalName = externalName self.localName = localName self.type = type self.attributes = attributes self.isInOutParameter = isInOutParameter self.isVariadic = isVariadic } } fileprivate let elements: [Element] fileprivate init(elements: [Element]) { self.elements = elements } fileprivate var textDescription: String { return "" } fileprivate var sourceRange: SourceRange = .EMPTY fileprivate func toTupleType() throws -> TupleType { var tupleElements: [TupleType.Element] = [] for e in elements { if e.externalName != nil { throw TupleConversionError.multipleLabels } else if e.isVariadic { throw TupleConversionError.isVariadic } else if let name = e.localName { let tupleElement = TupleType.Element( type: e.type, name: name, attributes: e.attributes, isInOutParameter: e.isInOutParameter) tupleElements.append(tupleElement) } else { let tupleElement = TupleType.Element(type: e.type) tupleElements.append(tupleElement) } } let tupleType = TupleType(elements: tupleElements) tupleType.setSourceRange(sourceRange) return tupleType } }
apache-2.0
THECALLR/sdk-ios
ThecallrApi/ThecallrApiTests/ThecallrApiTests.swift
1
907
// // ThecallrApiTests.swift // ThecallrApiTests // // Created by THECALLR on 25/09/14. // Copyright (c) 2014 THECALLR. All rights reserved. // import UIKit import XCTest class ThecallrApiTests: 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
vimeo/VimeoUpload
VimeoUpload/Upload/Operations/Async/ExportSessionExportOperation.swift
1
5697
// // ExportSessionExportOperation.swift // VimeoUpload // // Created by Hanssen, Alfie on 12/22/15. // Copyright © 2015 Vimeo. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import AVFoundation import VimeoNetworking import Photos public typealias ExportProgressBlock = (AVAssetExportSession, Double) -> Void @objc open class ExportSessionExportOperation: ConcurrentOperation { let operationQueue: OperationQueue @objc open var downloadProgressBlock: ProgressBlock? @objc open var exportProgressBlock: ExportProgressBlock? private let phAsset: PHAsset @objc open var error: NSError? { didSet { if self.error != nil { self.state = .finished } } } @objc open var result: URL? private let documentsFolderURL: URL? /// Initializes an instance of `ExportSessionExportOperation`. /// /// - Parameters: /// - phAsset: An instance of `PHAsset` representing a media that the /// user picks from the Photos app. /// - documentsFolderURL: An URL pointing to a Documents folder; /// default to `nil`. For third-party use, this argument should not be /// filled. @objc public init(phAsset: PHAsset, documentsFolderURL: URL? = nil) { self.phAsset = phAsset self.operationQueue = OperationQueue() self.operationQueue.maxConcurrentOperationCount = 1 self.documentsFolderURL = documentsFolderURL super.init() } deinit { self.operationQueue.cancelAllOperations() } // MARK: Overrides @objc override open func main() { if self.isCancelled { return } self.requestExportSession() } @objc override open func cancel() { super.cancel() self.operationQueue.cancelAllOperations() if let url = self.result { FileManager.default.deleteFile(at: url) } } // MARK: Public API func requestExportSession() { let operation = ExportSessionOperation(phAsset: self.phAsset) operation.progressBlock = self.downloadProgressBlock operation.completionBlock = { [weak self] () -> Void in DispatchQueue.main.async(execute: { [weak self] () -> Void in guard let strongSelf = self else { return } if operation.isCancelled == true { return } if let error = operation.error { strongSelf.error = error } else { let exportSession = operation.result! let exportOperation = ExportOperation(exportSession: exportSession, documentsFolderURL: strongSelf.documentsFolderURL) strongSelf.performExport(exportOperation: exportOperation) } }) } self.operationQueue.addOperation(operation) } func performExport(exportOperation: ExportOperation) { exportOperation.progressBlock = { [weak self] (progress: Double) -> Void in // This block is called on a background thread if let progressBlock = self?.exportProgressBlock { DispatchQueue.main.async(execute: { () -> Void in progressBlock(exportOperation.exportSession, progress) }) } } exportOperation.completionBlock = { [weak self] () -> Void in DispatchQueue.main.async(execute: { [weak self] () -> Void in guard let strongSelf = self else { return } if exportOperation.isCancelled == true { return } if let error = exportOperation.error { strongSelf.error = error } else { let url = exportOperation.outputURL! strongSelf.result = url strongSelf.state = .finished } }) } self.operationQueue.addOperation(exportOperation) } }
mit
markohlebar/Fontana
Spreadit/View/Cells/NavigationCell.swift
1
701
// // NavigationCell.swift // Spreadit // // Created by Marko Hlebar on 02/02/2016. // Copyright © 2016 Marko Hlebar. All rights reserved. // import UIKit import BIND class NavigationCell: BNDTableViewCell { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private var _bindings :[AnyObject]? override internal var bindings:[AnyObject]! { get { if _bindings == nil { _bindings = [ bndBIND(viewModel, "title", "~>", self, "textLabel.text", "", nil) ] } return _bindings } set { _bindings = newValue } } }
agpl-3.0
rwbutler/TypographyKit
TypographyKit/Classes/TypographyKitColorCell.swift
1
2261
// // TKColorCell.swift // TypographyKit // // Created by Ross Butler on 8/13/19. // import Foundation import UIKit @available(iOS 9.0, *) class TypographyKitColorCell: UITableViewCell { private var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.font = UIFont(name: "Avenir-Book", size: 17.0) titleLabel.textColor = .white titleLabel.translatesAutoresizingMaskIntoConstraints = false return titleLabel }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) configureView() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(title: String, color: UIColor?) { titleLabel.text = title if let backgroundColor = color { self.contentView.backgroundColor = backgroundColor } layoutIfNeeded() } } @available(iOS 9.0, *) private extension TypographyKitColorCell { private func configureView() { let effectView = self.effectView() effectView.addSubview(titleLabel) NSLayoutConstraint.activate([ titleLabel.leftAnchor.constraint(equalTo: effectView.leftAnchor, constant: 10.0), titleLabel.rightAnchor.constraint(equalTo: effectView.rightAnchor, constant: -10.0), titleLabel.topAnchor.constraint(equalTo: effectView.topAnchor, constant: 10.0), titleLabel.bottomAnchor.constraint(equalTo: effectView.bottomAnchor, constant: -10.0) ]) } private func effectView() -> UIView { let blur = UIBlurEffect(style: .dark) let effectView = UIVisualEffectView(effect: blur) effectView.translatesAutoresizingMaskIntoConstraints = false effectView.clipsToBounds = true effectView.layer.cornerRadius = 5.0 contentView.addSubview(effectView) NSLayoutConstraint.activate([ effectView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 10.0), effectView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor) ]) return effectView.contentView } }
mit
gunterhager/AnnotationClustering
Example/AppDelegate.swift
1
2172
// // AppDelegate.swift // Example // // Created by Gunter Hager on 07.06.16. // Copyright © 2016 Gunter Hager. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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:. } }
mit
jkolb/midnightbacon
RedditTests/RedditTests.swift
1
1940
// // RedditTests.swift // RedditTests // // Copyright (c) 2015 Justin Kolb - http://franticapparatus.net // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import XCTest class RedditTests: 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
hanangellove/TextFieldEffects
TextFieldEffects/TextFieldEffects/MadokaTextField.swift
11
5506
// // MadokaTextField.swift // TextFieldEffects // // Created by Raúl Riera on 05/02/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit @IBDesignable public class MadokaTextField: TextFieldEffects { @IBInspectable public var placeholderColor: UIColor? { didSet { updatePlaceholder() } } @IBInspectable public var borderColor: UIColor? { didSet { updateBorder() } } override public var placeholder: String? { didSet { updatePlaceholder() } } override public var bounds: CGRect { didSet { updateBorder() updatePlaceholder() } } private let borderThickness: CGFloat = 1 private let placeholderInsets = CGPoint(x: 6, y: 6) private let textFieldInsets = CGPoint(x: 6, y: 6) private let borderLayer = CAShapeLayer() private var backgroundLayerColor: UIColor? // MARK: - TextFieldsEffectsProtocol override func drawViewsForRect(rect: CGRect) { let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height)) placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(font) updateBorder() updatePlaceholder() layer.addSublayer(borderLayer) addSubview(placeholderLabel) } private func updateBorder() { //let path = CGPathCreateWithRect(rectForBorder(bounds), nil) let rect = rectForBorder(bounds) let path = UIBezierPath() path.moveToPoint(CGPoint(x: rect.origin.x + borderThickness, y: rect.height - borderThickness)) path.addLineToPoint(CGPoint(x: rect.width - borderThickness, y: rect.height - borderThickness)) path.addLineToPoint(CGPoint(x: rect.width - borderThickness, y: rect.origin.y + borderThickness)) path.addLineToPoint(CGPoint(x: rect.origin.x + borderThickness, y: rect.origin.y + borderThickness)) path.closePath() borderLayer.path = path.CGPath borderLayer.lineCap = kCALineCapSquare borderLayer.lineWidth = borderThickness borderLayer.fillColor = nil borderLayer.strokeColor = borderColor?.CGColor borderLayer.strokeEnd = percentageForBottomBorder() } private func percentageForBottomBorder() -> CGFloat { let borderRect = rectForBorder(bounds) let sumOfSides = (borderRect.width * 2) + (borderRect.height * 2) return (borderRect.width * 100 / sumOfSides) / 100 } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder() || !text.isEmpty { animateViewsForTextEntry() } } private func placeholderFontFromFont(font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.65) return smallerFont } private func rectForBorder(bounds: CGRect) -> CGRect { var newRect = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font.lineHeight + textFieldInsets.y) return newRect } private func layoutPlaceholderInTextRect() { if !text.isEmpty { return } placeholderLabel.transform = CGAffineTransformIdentity let textRect = textRectForBounds(bounds) var originX = textRect.origin.x switch textAlignment { case .Center: originX += textRect.size.width/2 - placeholderLabel.bounds.width/2 case .Right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: textRect.height - placeholderLabel.bounds.height - placeholderInsets.y, width: placeholderLabel.bounds.width, height: placeholderLabel.bounds.height) } override func animateViewsForTextEntry() { borderLayer.strokeEnd = 1 UIView.animateWithDuration(0.3, animations: { () -> Void in let translate = CGAffineTransformMakeTranslation(-self.placeholderInsets.x, self.placeholderLabel.bounds.height + (self.placeholderInsets.y * 2)) let scale = CGAffineTransformMakeScale(0.9, 0.9) self.placeholderLabel.transform = CGAffineTransformConcat(translate, scale) }) } override func animateViewsForTextDisplay() { if text.isEmpty { borderLayer.strokeEnd = percentageForBottomBorder() UIView.animateWithDuration(0.3, animations: { () -> Void in self.placeholderLabel.transform = CGAffineTransformIdentity }) } } // MARK: - Overrides override public func editingRectForBounds(bounds: CGRect) -> CGRect { let newBounds = rectForBorder(bounds) return CGRectInset(newBounds, textFieldInsets.x, 0) } override public func textRectForBounds(bounds: CGRect) -> CGRect { let newBounds = rectForBorder(bounds) return CGRectInset(newBounds, textFieldInsets.x, 0) } }
mit
lanjing99/iOSByTutorials
iOS 8 by tutorials/Chapter 05 - Transition Coordinator Updates/KhromaLike/KhromaLike/ViewController.swift
1
3051
/* * Copyright (c) 2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit class ViewController: UIViewController, ColorSwatchSelectionDelegate { @IBOutlet var tallLayoutContrains: [NSLayoutConstraint]! @IBOutlet var wideLayoutContrains: [NSLayoutConstraint]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Wire up any swatch selectors we can find as VC children for viewController in childViewControllers as [UIViewController] { if let selector = viewController as? ColorSwatchSelector { selector.swatchSelectionDelegate = self } } } // #pragma mark <ColorSwatchSelectionDelegate> func didSelect(swatch: ColorSwatch, sender: AnyObject?) { for viewController in childViewControllers as [UIViewController] { if let selectable = viewController as? ColorSwatchSelectable { selectable.colorSwatch = swatch } } } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) let transitionToWide = size.width > size.height let constraintsToUninstall = transitionToWide ? tallLayoutContrains : wideLayoutContrains let constraintsToInstall = transitionToWide ? wideLayoutContrains : tallLayoutContrains // Ask Auto Layout to commit any outstanding changes view.layoutIfNeeded() // Animate to the new layout alongside the transition coordinator.animateAlongsideTransition({ _ in NSLayoutConstraint.deactivateConstraints(constraintsToUninstall) NSLayoutConstraint.activateConstraints(constraintsToInstall) self.view.layoutIfNeeded() }, completion: nil) } }
mit
mkaply/firefox-ios
ClientTests/StringExtensionsTests.swift
5
2780
/* 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 XCTest @testable import Client class StringExtensionsTests: XCTestCase { func testEllipsize() { // Odd maxLength. Note that we ellipsize with a Unicode join character to avoid wrapping. XCTAssertEqual("abcd…\u{2060}fgh", "abcdefgh".ellipsize(maxLength: 7)) // Even maxLength. XCTAssertEqual("abcd…\u{2060}ijkl", "abcdefghijkl".ellipsize(maxLength: 8)) // String shorter than maxLength. XCTAssertEqual("abcd", "abcd".ellipsize(maxLength: 7)) // Empty String. XCTAssertEqual("", "".ellipsize(maxLength: 8)) // maxLength < 2. XCTAssertEqual("abcdefgh", "abcdefgh".ellipsize(maxLength: 0)) } func testStringByTrimmingLeadingCharactersInSet() { XCTAssertEqual("foo ", " foo ".stringByTrimmingLeadingCharactersInSet(.whitespaces)) XCTAssertEqual("foo456", "123foo456".stringByTrimmingLeadingCharactersInSet(.decimalDigits)) XCTAssertEqual("", "123456".stringByTrimmingLeadingCharactersInSet(.decimalDigits)) } func testStringSplitWithNewline() { XCTAssertEqual("", "".stringSplitWithNewline()) XCTAssertEqual("foo", "foo".stringSplitWithNewline()) XCTAssertEqual("aaa\n bbb", "aaa bbb".stringSplitWithNewline()) XCTAssertEqual("Mark as\n Read", "Mark as Read".stringSplitWithNewline()) XCTAssertEqual("aa\n bbbbbb", "aa bbbbbb".stringSplitWithNewline()) } func testPercentEscaping() { func roundtripTest(_ input: String, _ expected: String, file: StaticString = #file, line: UInt = #line) { let observed = input.escape()! XCTAssertEqual(observed, expected, "input is \(input)", file: file, line: line) let roundtrip = observed.unescape() XCTAssertEqual(roundtrip, input, "encoded is \(observed)", file: file, line: line) } roundtripTest("https://mozilla.com", "https://mozilla.com") roundtripTest("http://www.cnn.com/2017/09/25/politics/north-korea-fm-us-bombers/index.html", "http://www.cnn.com/2017/09/25/politics/north-korea-fm-us-bombers/index.html") roundtripTest("http://mozilla.com/?a=foo&b=bar", "http://mozilla.com/%3Fa%3Dfoo%26b%3Dbar") } func testRemoveUnicodeFromFilename() { let file = "foo-\u{200F}cod.jpg" // Unicode RTL-switch code, becomes "foo-gpj.doc" let nounicode = "foo-cod.jpg" XCTAssert(file != nounicode) let strip = HTTPDownload.stripUnicode(fromFilename: file) XCTAssert(strip == nounicode) } }
mpl-2.0
adolfrank/Swift_practise
26-day/26-day/TableViewController.swift
1
5477
// // TableViewController.swift // 26-day // // Created by Hongbo Yu on 16/5/30. // Copyright © 2016年 Frank. All rights reserved. // import UIKit import CoreData class TableViewController: UITableViewController { var listItems = [NSManagedObject]() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: #selector(TableViewController.addItem)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContex = appDelegate.managedObjectContext let fetchRequest = NSFetchRequest(entityName: "ListEntity") do { let results = try managedContex.executeFetchRequest(fetchRequest) listItems = results as! [NSManagedObject] self.tableView.reloadData() } catch { print("error") } } // override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // // let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // let managedContex = appDelegate.managedObjectContext // // managedContex.deleteObject(listItems[indexPath.row]) // listItems.removeAtIndex(indexPath.row) // // self.tableView.reloadData() // // } func addItem() { let alertController = UIAlertController(title: "New Resolution", message: "", preferredStyle: UIAlertControllerStyle.Alert) let confirmAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.Default, handler: ({ (_) in if let field = alertController.textFields![0] as? UITextField { self.saveItem(field.text!) self.tableView.reloadData() } })) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) alertController.addTextFieldWithConfigurationHandler ({ (textField) in textField.placeholder = "Type smothing..." }) alertController.addAction(confirmAction) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } func saveItem(itemToSave: String) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContex = appDelegate.managedObjectContext let entity = NSEntityDescription.entityForName("ListEntity", inManagedObjectContext: managedContex) let item = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContex) item.setValue(itemToSave, forKey: "item") do { try managedContex.save() listItems.append(item) } catch { print("error") } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listItems.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell let item = listItems[indexPath.row] cell.textLabel?.text = item.valueForKey("item") as? String cell.textLabel?.font = UIFont(name: "", size: 25) return cell } override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let delete = UITableViewRowAction(style: .Normal, title: "Delete") { action, index in let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContex = appDelegate.managedObjectContext tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Right) managedContex.deleteObject(self.listItems[indexPath.row]) do { try managedContex.save() self.listItems.removeAtIndex(indexPath.row) self.tableView.reloadData() } catch { print("error: delete ") } } delete.backgroundColor = UIColor.redColor() return [delete] } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { } }
mit
itamaker/SunnyFPS
SunnyFPS/AppDelegate.swift
1
6090
// // AppDelegate.swift // SunnyFPS // // Created by jiazhaoyang on 16/2/15. // Copyright © 2016年 gitpark. 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 "com.gitpark.SunnyFPS" 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("SunnyFPS", 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
ArtSabintsev/Guitar
Sources/GuitarCase.swift
1
4737
// // GuitarCasing.swift // GuitarExample // // Created by Sabintsev, Arthur on 3/9/17. // Copyright © 2017 Arthur Ariel Sabintsev. All rights reserved. // import Foundation // MARK: - Case Operations public extension String { /// Returns a camel cased version of the string. /// /// let string = "HelloWorld" /// print(string.camelCased()) /// // Prints "helloWorld" /// /// - Returns: A camel cased copy of the string. @discardableResult func camelCased() -> String { return pascalCased().decapitalized() } /// Returns a capitalized version of the string. /// /// - Warning: This method is a modified implementation of Swift stdlib's `capitalized` computer variabled. /// /// let string = "hello World" /// print(string.capitalized()) /// // Prints "Hello World" /// /// - Returns: A capitalized copy of the string. @discardableResult func capitalized() -> String { let ranges = Guitar(chord: .firstCharacter).evaluateForRanges(from: self) var newString = self for range in ranges { let character = index(range.lowerBound, offsetBy: 0) let uppercasedCharacter = String(self[character]).uppercased() newString = newString.replacingCharacters(in: range, with: uppercasedCharacter) } return newString } /// Returns a decapitalized version of the string. /// /// let string = "Hello World" /// print(string.decapitalized()) /// // Prints "hello world" /// /// - Returns: A decapitalized copy of the string. @discardableResult func decapitalized() -> String { let ranges = Guitar(chord: .firstCharacter).evaluateForRanges(from: self) var newString = self for range in ranges { let character = self[range.lowerBound] let lowercasedCharacter = String(character).lowercased() newString = newString.replacingCharacters(in: range, with: lowercasedCharacter) } return newString } /// Returns the kebab cased (a.k.a. slug) version of the string. /// /// let string = "Hello World" /// print(string.kebabCased()) /// // Prints "hello-world" /// /// - Returns: The kebabg cased copy of the string. @discardableResult func kebabCased() -> String { return Guitar.sanitze(string: self).splitWordsByCase().replacingOccurrences(of: " ", with: "-").lowercased() } /// Returns a pascal cased version of the string. /// /// let string = "HELLO WORLD" /// print(string.pascalCased()) /// // Prints "HelloWorld" /// /// - Returns: A pascal cased copy of the string. @discardableResult func pascalCased() -> String { return Guitar.sanitze(string: self).splitWordsByCase().capitalized().components(separatedBy: .whitespaces).joined() } /// Returns the snake cased version of the string. /// /// let string = "Hello World" /// print(string.snakeCased()) /// // Prints "hello_world" /// /// - Returns: The snaked cased copy of the string. @discardableResult func snakeCased() -> String { return Guitar.sanitze(string: self).splitWordsByCase().replacingOccurrences(of: " ", with: "_").lowercased() } /// Splits a string into mutliple words, delimited by uppercase letters. /// /// let string = "HelloWorld" /// print(string.splitWordsByCase()) /// // Prints "Hello World" /// /// - Returns: A new string where each word in the original string is delimited by a whitespace. @discardableResult func splitWordsByCase() -> String { var newStringArray: [String] = [] for character in Guitar.sanitze(string: self) { if String(character) == String(character).uppercased() { newStringArray.append(" ") } newStringArray.append(String(character)) } return newStringArray .joined() .trimmingCharacters(in: .whitespacesAndNewlines) .components(separatedBy: .whitespaces) .filter({ !$0.isEmpty }) .joined(separator: " ") } /// Returns the swap cased version of the string. /// /// let string = "Hello World" /// print(string.swapCased()) /// // Prints "hELLO wORLD" /// /// - Returns: The swap cased copy of the string. @discardableResult func swapCased() -> String { return map({ String($0).isLowercased() ? String($0).uppercased() : String($0).lowercased() }).joined() } }
mit
argon/mas
MasKit/Models/SoftwareProduct.swift
1
995
// // SoftwareProduct.swift // MasKit // // Created by Ben Chatelain on 12/27/18. // Copyright © 2018 mas-cli. All rights reserved. // /// Protocol describing the members of CKSoftwareProduct used throughout MasKit. public protocol SoftwareProduct { var appName: String { get } var bundleIdentifier: String { get set } var bundlePath: String { get set } var bundleVersion: String { get set } var itemIdentifier: NSNumber { get set } } // MARK: - Equatable extension SoftwareProduct { static func == (lhs: Self, rhs: Self) -> Bool { return lhs.appName == rhs.appName && lhs.bundleIdentifier == rhs.bundleIdentifier && lhs.bundlePath == rhs.bundlePath && lhs.bundleVersion == rhs.bundleVersion && lhs.itemIdentifier == rhs.itemIdentifier } /// Returns bundleIdentifier if appName is empty string. var appNameOrBbundleIdentifier: String { appName == "" ? bundleIdentifier : appName } }
mit
ravirani/algorithms
Tree/BinaryTreeTraversals.swift
1
1270
// // BinaryTreeTraversals.swift // // Recursive preorder, inorder, and postorder traversals (DFS) // import Foundation class Node { var data: Int var left: Node? var right: Node? init(_ nodeData: Int) { self.data = nodeData } } // V L R func preorderTraversal(_ rootNode: Node?) -> [Int] { guard let node = rootNode else { return [] } var output = [Int]() output += [node.data] if let left = node.left { output += preorderTraversal(left) } if let right = node.right { output += preorderTraversal(right) } return output } // L V R func inorderTraversal(_ rootNode: Node?) -> [Int] { guard let node = rootNode else { return [] } var output = [Int]() if let left = node.left { output += inorderTraversal(left) } output += [node.data] if let right = node.right { output += inorderTraversal(right) } return output } // L R V func postorderTraversal(_ rootNode: Node?) -> [Int] { guard let node = rootNode else { return [] } var output = [Int]() if let left = node.left { output += postorderTraversal(left) } if let right = node.right { output += postorderTraversal(right) } output += [node.data] return output }
mit
pierrewehbe/MyVoice
MyVoiceUITests/MyVoiceUITests.swift
1
1235
// // MyVoiceUITests.swift // MyVoiceUITests // // Created by Pierre on 11/12/16. // Copyright © 2016 Pierre. All rights reserved. // import XCTest class MyVoiceUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/27663-swift-nominaltypedecl-prepareextensions.swift
1
454
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class a<T where g:a{struct Q{class C< c let a{let f=a<C
apache-2.0
ben-ng/swift
validation-test/stdlib/Collection/DefaultedRangeReplaceableBidirectionalCollection.swift
22
2174
// -*- swift -*- //===----------------------------------------------------------------------===// // Automatically Generated From validation-test/stdlib/Collection/Inputs/Template.swift.gyb // Do Not Edit Directly! //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest import StdlibCollectionUnittest var CollectionTests = TestSuite("Collection") // Test collections using value types as elements. do { var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap CollectionTests.addRangeReplaceableBidirectionalCollectionTests( makeCollection: { (elements: [OpaqueValue<Int>]) in return DefaultedRangeReplaceableBidirectionalCollection(elements: elements) }, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in return DefaultedRangeReplaceableBidirectionalCollection(elements: elements) }, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, resiliencyChecks: resiliencyChecks ) } // Test collections using a reference type as element. do { var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap CollectionTests.addRangeReplaceableBidirectionalCollectionTests( makeCollection: { (elements: [LifetimeTracked]) in return DefaultedRangeReplaceableBidirectionalCollection(elements: elements) }, wrapValue: { (element: OpaqueValue<Int>) in LifetimeTracked(element.value, identity: element.identity) }, extractValue: { (element: LifetimeTracked) in OpaqueValue(element.value, identity: element.identity) }, makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in // FIXME: use LifetimeTracked. return DefaultedRangeReplaceableBidirectionalCollection(elements: elements) }, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, resiliencyChecks: resiliencyChecks ) } runAllTests()
apache-2.0
josve05a/wikipedia-ios
Wikipedia/Code/WKWebView+EditSelectionJavascript.swift
3
3147
import WebKit extension WKWebView { private func selectedTextEditInfo(from dictionary: Dictionary<String, Any>) -> SelectedTextEditInfo? { guard let selectedAndAdjacentTextDict = dictionary["selectedAndAdjacentText"] as? Dictionary<String, Any>, let selectedText = selectedAndAdjacentTextDict["selectedText"] as? String, let textBeforeSelectedText = selectedAndAdjacentTextDict["textBeforeSelectedText"] as? String, let textAfterSelectedText = selectedAndAdjacentTextDict["textAfterSelectedText"] as? String, let isSelectedTextInTitleDescription = dictionary["isSelectedTextInTitleDescription"] as? Bool, let sectionID = dictionary["sectionID"] as? Int else { DDLogError("Error converting dictionary to SelectedTextEditInfo") return nil } let selectedAndAdjacentText = SelectedAndAdjacentText(selectedText: selectedText, textAfterSelectedText: textAfterSelectedText, textBeforeSelectedText: textBeforeSelectedText) return SelectedTextEditInfo(selectedAndAdjacentText: selectedAndAdjacentText, isSelectedTextInTitleDescription: isSelectedTextInTitleDescription, sectionID: sectionID) } @objc func wmf_getSelectedTextEditInfo(completionHandler: ((SelectedTextEditInfo?, Error?) -> Void)? = nil) { evaluateJavaScript("window.wmf.editTextSelection.getSelectedTextEditInfo()") { [weak self] (result, error) in guard let error = error else { guard let completionHandler = completionHandler else { return } guard let resultDict = result as? Dictionary<String, Any>, let selectedTextEditInfo = self?.selectedTextEditInfo(from: resultDict) else { DDLogError("Error handling 'getSelectedTextEditInfo()' dictionary response") return } completionHandler(selectedTextEditInfo, nil) return } DDLogError("Error when evaluating javascript on fetch and transform: \(error)") } } } class SelectedAndAdjacentText { public let selectedText: String public let textAfterSelectedText: String public let textBeforeSelectedText: String init(selectedText: String, textAfterSelectedText: String, textBeforeSelectedText: String) { self.selectedText = selectedText self.textAfterSelectedText = textAfterSelectedText self.textBeforeSelectedText = textBeforeSelectedText } } @objcMembers class SelectedTextEditInfo: NSObject { public let selectedAndAdjacentText: SelectedAndAdjacentText public let isSelectedTextInTitleDescription: Bool public let sectionID: Int init(selectedAndAdjacentText: SelectedAndAdjacentText, isSelectedTextInTitleDescription: Bool, sectionID: Int) { self.selectedAndAdjacentText = selectedAndAdjacentText self.isSelectedTextInTitleDescription = isSelectedTextInTitleDescription self.sectionID = sectionID } }
mit
katsumeshi/PhotoInfo
PhotoInfo/Classes/ArrayUtil.swift
1
1080
// // ArrayUtil.swift // photoinfo // // Created by Yuki Matsushita on 11/20/15. // Copyright © 2015 Yuki Matsushita. All rights reserved. // import MapKit extension Array where Element : OnlyCustomAnnotations { func getMaxDistance() -> Double { let locations = self.map { $0 as! MKAnnotation } .map{ CLLocation($0.coordinate) } var distances = [CLLocationDistance]() for var i = 0; i < locations.count - 1; i++ { for var j = i + 1; j < locations.count; j++ { let distance = locations[i].distanceFromLocation(locations[j]) distances.append(distance) } } distances.sortInPlace { $0 > $1 } return distances.first! } func find(photo:Photo) -> (index:Int, annotation:CustomAnnotation) { let annotations = self.map{ $0 as! CustomAnnotation } let annotation = annotations.filter { $0.photo == photo }.first! let index = annotations.indexOf(annotation)! return (index, annotation) } } func == (left: Photo, right: Photo) -> Bool { return left.asset == right.asset }
mit
fredrikcollden/LittleMaestro
GameViewController.swift
1
2083
// // GameViewController.swift // MaestroLevel // // Created by Fredrik Colldén on 2015-10-29. // Copyright (c) 2015 Marie. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController, GameSceneDelegate, StartSceneDelegate, CategoriesSceneDelegate { var whiteTransition = SKTransition.fadeWithColor(UIColor(red: CGFloat(1.0), green: CGFloat(1.0), blue: CGFloat(1.0), alpha: CGFloat(1.0)), duration: 1.0) override func viewDidLoad() { super.viewDidLoad() //GameData.sharedInstance.resetData() GameData.sharedInstance.loadData() let skView = self.view as! SKView let scene = StartScene(size: skView.bounds.size) skView.showsFPS = true skView.showsNodeCount = true skView.ignoresSiblingOrder = true scene.scaleMode = .AspectFill scene.startSceneDelegate = self skView.presentScene(scene) } func startSceneActions(action: String) { let skView = view as! SKView let categoriesScene = CategoriesScene(size: skView.bounds.size) categoriesScene.categoriesSceneDelegate = self skView.presentScene(categoriesScene, transition: whiteTransition) } func loadLevel (levelNo: Int) { let skView = view as! SKView let gameScene = GameScene(levelNo: levelNo, size: skView.bounds.size) gameScene.gameSceneDelegate = self skView.presentScene(gameScene, transition: whiteTransition) } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return .AllButUpsideDown } else { return .All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
lgpl-3.0
Mobilette/AniMee
Pods/p2.OAuth2/Sources/Base/OAuth2CodeGrantNoTokenType.swift
6
1016
// // OAuth2CodeGrantNoTokenType.swift // OAuth2 // // Created by Pascal Pfiffner on 1/15/16. // Copyright 2016 Pascal Pfiffner. // // 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. // /** Subclass to deal with sites that don't return `token_type`, such as Instagram or Bitly. */ public class OAuth2CodeGrantNoTokenType: OAuth2CodeGrant { public override init(settings: OAuth2JSON) { super.init(settings: settings) } override func assureCorrectBearerType(params: OAuth2JSON) throws { } }
mit
jasonwedepohl/udacity-ios-on-the-map
On The Map/On The Map/UdacityClient.swift
1
6746
// // UdacityClient.swift // On The Map // // Created by Jason Wedepohl on 2017/09/18. // // import Foundation import FacebookCore import FacebookLogin class UdacityClient { //MARK: Singleton static let shared = UdacityClient() //MARK: Constants let responseHeaderLength = 5 struct Url { static let session = "https://www.udacity.com/api/session" static let users = "https://www.udacity.com/api/users/" } struct UdacityResponseKey { static let user = "user" static let firstName = "first_name" static let lastName = "last_name" } //MARK: Properties let session = URLSession.shared var udacitySessionID: String? = nil var udacityAccountKey: String? = nil var udacityFirstName: String? = nil var udacityLastName: String? = nil //MARK: Functions func login(email: String, password: String, completion: @escaping (_ success: Bool, _ displayError: String?) -> Void) { let requestBody = UdacityLoginRequest.get(email, password) let request = getLoginRequest(withBody: requestBody) let task = session.dataTask(with: request as URLRequest) { data, response, error in self.handleLoginTaskCompletion(data, response, error, completion) } task.resume() } func loginWithFacebook(completion: @escaping (_ success: Bool, _ displayError: String?) -> Void) { guard let accessToken = AccessToken.current?.authenticationToken else { print("The Facebook access token is not set.") completion(false, DisplayError.unexpected) return } let requestBody = UdacityLoginWithFacebookRequest.get(accessToken) let request = getLoginRequest(withBody: requestBody) let task = session.dataTask(with: request as URLRequest) { data, response, error in self.handleLoginTaskCompletion(data, response, error, completion) } task.resume() } func logout(completion: @escaping (_ success: Bool, _ displayError: String?) -> Void) { //log out of Facebook if necessary if (AccessToken.current != nil) { let loginManager = LoginManager() loginManager.logOut() } let request = NSMutableURLRequest(url: URL(string: Url.session)!) request.httpMethod = WebMethod.delete //add anti-XSRF cookie so Udacity server knows this is the client that originally logged in if let xsrfCookie = Utilities.getCookie(withKey: Cookie.xsrfToken) { request.setValue(xsrfCookie.value, forHTTPHeaderField: RequestKey.xxsrfToken) } let task = session.dataTask(with: request as URLRequest) { data, response, error in let responseHandler = ResponseHandler(data, response, error) if let responseError = responseHandler.getResponseError() { completion(false, responseError) return } completion(true, nil) } task.resume() } private func getLoginRequest<T: Encodable>(withBody body: T) -> NSMutableURLRequest { let request = NSMutableURLRequest(url: URL(string: Url.session)!) request.httpMethod = WebMethod.post request.addValue(RequestValue.jsonType, forHTTPHeaderField: RequestKey.accept) request.addValue(RequestValue.jsonType, forHTTPHeaderField: RequestKey.contentType) request.httpBody = JSONParser.stringify(body).data(using: String.Encoding.utf8) return request } private func handleLoginTaskCompletion(_ data: Data?, _ response: URLResponse?, _ error: Error?, _ completion: @escaping (_ success: Bool, _ displayError: String?) -> Void) { let responseHandler = ResponseHandler(data, response, error) if let responseError = responseHandler.getResponseError() { completion(false, responseError) return } let subsetResponseData = subsetResponse(data!) guard let response:UdacityLoginResponse = JSONParser.decode(subsetResponseData) else { completion(false, DisplayError.unexpected) return } udacityAccountKey = response.account.key udacitySessionID = response.session.id getUserDetails(completion) } private func getUserDetails(_ completion: @escaping (_ success: Bool, _ displayError: String?) -> Void) { let request = NSMutableURLRequest(url: URL(string: Url.users + udacityAccountKey!)!) let task = session.dataTask(with: request as URLRequest) { data, response, error in let responseHandler = ResponseHandler(data, response, error) if let responseError = responseHandler.getResponseError() { completion(false, responseError) return } let subsetResponseData = self.subsetResponse(data!) //TODO: replace use of JSONSerialization with Swift 4 Codable guard let parsedResponse = JSONParser.deserialize(subsetResponseData) else { completion(false, DisplayError.unexpected) return } guard let responseDictionary = parsedResponse as? [String: AnyObject] else { completion(false, DisplayError.unexpected) return } guard let user = responseDictionary[UdacityResponseKey.user] as? [String: AnyObject] else { completion(false, DisplayError.unexpected) return } guard let firstName = user[UdacityResponseKey.firstName] as? String else { completion(false, DisplayError.unexpected) return } guard let lastName = user[UdacityResponseKey.lastName] as? String else { completion(false, DisplayError.unexpected) return } self.udacityFirstName = firstName self.udacityLastName = lastName completion(true, nil) } task.resume() } //All responses from Udacity API start with 5 characters that must be skipped private func subsetResponse(_ data: Data) -> Data { let range = Range(responseHeaderLength..<data.count) return data.subdata(in: range) } //MARK: Request structs private struct UdacityLoginRequest: Codable { private let udacity : Udacity private struct Udacity : Codable { let username: String let password: String } static func get(_ username: String, _ password: String) -> UdacityLoginRequest { return UdacityLoginRequest(udacity: Udacity(username: username, password: password)) } } private struct UdacityLoginWithFacebookRequest: Codable { private let facebook_mobile : FacebookMobile private struct FacebookMobile : Codable { let access_token: String } static func get(_ accessToken: String) -> UdacityLoginWithFacebookRequest { return UdacityLoginWithFacebookRequest(facebook_mobile: FacebookMobile(access_token: accessToken)) } } //MARK: Response structs private struct UdacityLoginResponse: Codable { let account: Account let session: Session struct Account: Codable { let registered: Bool let key: String } struct Session: Codable { let id: String let expiration: String } } }
mit
adrfer/swift
validation-test/compiler_crashers_fixed/27697-std-function-func-setboundvarstypeerror.swift
4
277
// RUN: not %target-swift-frontend %s -parse // 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 a<T where g:d{class A{class d<I func p{{class A{let a{d
apache-2.0
cxpyear/ZSZQApp
spdbapp/spdbapp/Classes/View/SignInTableviewCell.swift
1
659
// // SignInTableviewCell.swift // spdbapp // // Created by GBTouchG3 on 15/8/21. // Copyright (c) 2015年 shgbit. All rights reserved. // import UIKit class SignInTableviewCell: UITableViewCell { // @IBOutlet weak var lblSignInUserName: UILabel! @IBOutlet weak var lblSignInUserId: UILabel! @IBOutlet weak var btnSignIn: UIButton! override func awakeFromNib() { super.awakeFromNib() btnSignIn.layer.cornerRadius = 8 } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
bsd-3-clause
digdoritos/RestfulAPI-Example
RestfulAPI-Example/SlideMenuView.swift
1
553
// // SlideMenuView.swift // RestfulAPI-Example // // Created by Chun-Tang Wang on 27/03/2017. // Copyright © 2017 Chun-Tang Wang. All rights reserved. // import UIKit class SlideMenuView: UIView { @IBOutlet weak var userView: UIView! @IBOutlet weak var tableView: UITableView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() tableView.register(SlideMenuCell.self, forCellReuseIdentifier: "SlideMenuCell") } }
mit
sydvicious/firefox-ios
Providers/Profile.swift
2
26131
/* 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 Account import ReadingList import Shared import Storage import Sync import XCGLogger // TODO: same comment as for SyncAuthState.swift! private let log = XCGLogger.defaultInstance() public protocol SyncManager { func syncClients() -> SyncResult func syncClientsThenTabs() -> SyncResult func syncHistory() -> SyncResult func syncLogins() -> SyncResult func syncEverything() -> Success // The simplest possible approach. func beginTimedSyncs() func endTimedSyncs() func onRemovedAccount(account: FirefoxAccount?) -> Success func onAddedAccount() -> Success } typealias EngineIdentifier = String typealias SyncFunction = (SyncDelegate, Prefs, Ready) -> SyncResult class ProfileFileAccessor: FileAccessor { init(profile: Profile) { let profileDirName = "profile.\(profile.localName())" // Bug 1147262: First option is for device, second is for simulator. var rootPath: String? if let sharedContainerIdentifier = ExtensionUtils.sharedContainerIdentifier(), url = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(sharedContainerIdentifier), path = url.path { rootPath = path } else { log.error("Unable to find the shared container. Defaulting profile location to ~/Documents instead.") rootPath = String(NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString) } super.init(rootPath: rootPath!.stringByAppendingPathComponent(profileDirName)) } } class CommandStoringSyncDelegate: SyncDelegate { let profile: Profile init() { profile = BrowserProfile(localName: "profile", app: nil) } func displaySentTabForURL(URL: NSURL, title: String) { if let urlString = URL.absoluteString { let item = ShareItem(url: urlString, title: title, favicon: nil) self.profile.queue.addToQueue(item) } } } /** * This exists because the Sync code is extension-safe, and thus doesn't get * direct access to UIApplication.sharedApplication, which it would need to * display a notification. * This will also likely be the extension point for wipes, resets, and * getting access to data sources during a sync. */ let TabSendURLKey = "TabSendURL" let TabSendTitleKey = "TabSendTitle" let TabSendCategory = "TabSendCategory" enum SentTabAction: String { case View = "TabSendViewAction" case Bookmark = "TabSendBookmarkAction" case ReadingList = "TabSendReadingListAction" } class BrowserProfileSyncDelegate: SyncDelegate { let app: UIApplication init(app: UIApplication) { self.app = app } // SyncDelegate func displaySentTabForURL(URL: NSURL, title: String) { // check to see what the current notification settings are and only try and send a notification if // the user has agreed to them let currentSettings = app.currentUserNotificationSettings() if currentSettings.types.rawValue & UIUserNotificationType.Alert.rawValue != 0 { log.info("Displaying notification for URL \(URL.absoluteString)") let notification = UILocalNotification() notification.fireDate = NSDate() notification.timeZone = NSTimeZone.defaultTimeZone() notification.alertBody = String(format: NSLocalizedString("New tab: %@: %@", comment:"New tab [title] [url]"), title, URL.absoluteString!) notification.userInfo = [TabSendURLKey: URL.absoluteString!, TabSendTitleKey: title] notification.alertAction = nil notification.category = TabSendCategory app.presentLocalNotificationNow(notification) } } } /** * A Profile manages access to the user's data. */ protocol Profile: class { var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> { get } // var favicons: Favicons { get } var prefs: Prefs { get } var queue: TabQueue { get } var searchEngines: SearchEngines { get } var files: FileAccessor { get } var history: protocol<BrowserHistory, SyncableHistory> { get } var favicons: Favicons { get } var readingList: ReadingListService? { get } var logins: protocol<BrowserLogins, SyncableLogins> { get } func shutdown() // I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter. // Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>. func localName() -> String // URLs and account configuration. var accountConfiguration: FirefoxAccountConfiguration { get } // Do we have an account at all? func hasAccount() -> Bool // Do we have an account that (as far as we know) is in a syncable state? func hasSyncableAccount() -> Bool func getAccount() -> FirefoxAccount? func removeAccount() func setAccount(account: FirefoxAccount) func getClients() -> Deferred<Result<[RemoteClient]>> func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> func getCachedClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> func storeTabs(tabs: [RemoteTab]) -> Deferred<Result<Int>> func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) var syncManager: SyncManager { get } } public class BrowserProfile: Profile { private let name: String weak private var app: UIApplication? init(localName: String, app: UIApplication?) { self.name = localName self.app = app let notificationCenter = NSNotificationCenter.defaultCenter() let mainQueue = NSOperationQueue.mainQueue() notificationCenter.addObserver(self, selector: Selector("onLocationChange:"), name: "LocationChange", object: nil) if let baseBundleIdentifier = ExtensionUtils.baseBundleIdentifier() { KeychainWrapper.serviceName = baseBundleIdentifier } else { log.error("Unable to get the base bundle identifier. Keychain data will not be shared.") } // If the profile dir doesn't exist yet, this is first run (for this profile). if !files.exists("") { log.info("New profile. Removing old account data.") removeAccount() prefs.clearAll() } } // Extensions don't have a UIApplication. convenience init(localName: String) { self.init(localName: localName, app: nil) } func shutdown() { if dbCreated { db.close() } if loginsDBCreated { loginsDB.close() } } @objc func onLocationChange(notification: NSNotification) { if let v = notification.userInfo!["visitType"] as? Int, let visitType = VisitType(rawValue: v), let url = notification.userInfo!["url"] as? NSURL where !isIgnoredURL(url), let title = notification.userInfo!["title"] as? NSString { // We don't record a visit if no type was specified -- that means "ignore me". let site = Site(url: url.absoluteString!, title: title as String) let visit = SiteVisit(site: site, date: NSDate.nowMicroseconds(), type: visitType) log.debug("Recording visit for \(url) with type \(v).") history.addLocalVisit(visit) } else { let url = notification.userInfo!["url"] as? NSURL log.debug("Ignoring navigation for \(url).") } } deinit { self.syncManager.endTimedSyncs() NSNotificationCenter.defaultCenter().removeObserver(self) } func localName() -> String { return name } var files: FileAccessor { return ProfileFileAccessor(profile: self) } lazy var queue: TabQueue = { return SQLiteQueue(db: self.db) }() private var dbCreated = false lazy var db: BrowserDB = { self.dbCreated = true return BrowserDB(filename: "browser.db", files: self.files) }() /** * Favicons, history, and bookmarks are all stored in one intermeshed * collection of tables. */ private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory> = { return SQLiteHistory(db: self.db)! }() var favicons: Favicons { return self.places } var history: protocol<BrowserHistory, SyncableHistory> { return self.places } lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> = { return SQLiteBookmarks(db: self.db) }() lazy var searchEngines: SearchEngines = { return SearchEngines(prefs: self.prefs) }() func makePrefs() -> Prefs { return NSUserDefaultsPrefs(prefix: self.localName()) } lazy var prefs: Prefs = { return self.makePrefs() }() lazy var readingList: ReadingListService? = { return ReadingListService(profileStoragePath: self.files.rootPath) }() private lazy var remoteClientsAndTabs: RemoteClientsAndTabs = { return SQLiteRemoteClientsAndTabs(db: self.db) }() lazy var syncManager: SyncManager = { return BrowserSyncManager(profile: self) }() private func getSyncDelegate() -> SyncDelegate { if let app = self.app { return BrowserProfileSyncDelegate(app: app) } return CommandStoringSyncDelegate() } public func getClients() -> Deferred<Result<[RemoteClient]>> { return self.syncManager.syncClients() >>> { self.remoteClientsAndTabs.getClients() } } public func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> { return self.syncManager.syncClientsThenTabs() >>> { self.remoteClientsAndTabs.getClientsAndTabs() } } public func getCachedClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> { return self.remoteClientsAndTabs.getClientsAndTabs() } func storeTabs(tabs: [RemoteTab]) -> Deferred<Result<Int>> { return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs) } public func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) { let commands = items.map { item in SyncCommand.fromShareItem(item, withAction: "displayURI") } self.remoteClientsAndTabs.insertCommands(commands, forClients: clients) >>> { self.syncManager.syncClients() } } lazy var logins: protocol<BrowserLogins, SyncableLogins> = { return SQLiteLogins(db: self.loginsDB) }() private lazy var loginsKey: String? = { let key = "sqlcipher.key.logins.db" if KeychainWrapper.hasValueForKey(key) { return KeychainWrapper.stringForKey(key) } let Length: UInt = 256 let secret = Bytes.generateRandomBytes(Length).base64EncodedString KeychainWrapper.setString(secret, forKey: key) return secret }() private var loginsDBCreated = false private lazy var loginsDB: BrowserDB = { self.loginsDBCreated = true return BrowserDB(filename: "logins.db", secretKey: self.loginsKey, files: self.files) }() let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration() private lazy var account: FirefoxAccount? = { if let dictionary = KeychainWrapper.objectForKey(self.name + ".account") as? [String: AnyObject] { return FirefoxAccount.fromDictionary(dictionary) } return nil }() func hasAccount() -> Bool { return account != nil } func hasSyncableAccount() -> Bool { return account?.actionNeeded == FxAActionNeeded.None } func getAccount() -> FirefoxAccount? { return account } func removeAccount() { let old = self.account prefs.removeObjectForKey(PrefsKeys.KeyLastRemoteTabSyncTime) KeychainWrapper.removeObjectForKey(name + ".account") self.account = nil // tell any observers that our account has changed NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil) // Trigger cleanup. Pass in the account in case we want to try to remove // client-specific data from the server. self.syncManager.onRemovedAccount(old) // deregister for remote notifications app?.unregisterForRemoteNotifications() } func setAccount(account: FirefoxAccount) { KeychainWrapper.setObject(account.asDictionary(), forKey: name + ".account") self.account = account // register for notifications for the account registerForNotifications() // tell any observers that our account has changed NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil) self.syncManager.onAddedAccount() } func registerForNotifications() { let viewAction = UIMutableUserNotificationAction() viewAction.identifier = SentTabAction.View.rawValue viewAction.title = NSLocalizedString("View", comment: "View a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") viewAction.activationMode = UIUserNotificationActivationMode.Foreground viewAction.destructive = false viewAction.authenticationRequired = false let bookmarkAction = UIMutableUserNotificationAction() bookmarkAction.identifier = SentTabAction.Bookmark.rawValue bookmarkAction.title = NSLocalizedString("Bookmark", comment: "Bookmark a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") bookmarkAction.activationMode = UIUserNotificationActivationMode.Foreground bookmarkAction.destructive = false bookmarkAction.authenticationRequired = false let readingListAction = UIMutableUserNotificationAction() readingListAction.identifier = SentTabAction.ReadingList.rawValue readingListAction.title = NSLocalizedString("Add to Reading List", comment: "Add URL to the reading list - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") readingListAction.activationMode = UIUserNotificationActivationMode.Foreground readingListAction.destructive = false readingListAction.authenticationRequired = false let sentTabsCategory = UIMutableUserNotificationCategory() sentTabsCategory.identifier = TabSendCategory sentTabsCategory.setActions([readingListAction, bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Default) sentTabsCategory.setActions([bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Minimal) app?.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: [sentTabsCategory])) app?.registerForRemoteNotifications() } // Extends NSObject so we can use timers. class BrowserSyncManager: NSObject, SyncManager { unowned private let profile: BrowserProfile let FifteenMinutes = NSTimeInterval(60 * 15) let OneMinute = NSTimeInterval(60) private var syncTimer: NSTimer? = nil /** * Locking is managed by withSyncInputs. Make sure you take and release these * whenever you do anything Sync-ey. */ var syncLock = OSSpinLock() private func beginSyncing() -> Bool { return OSSpinLockTry(&syncLock) } private func endSyncing() { return OSSpinLockUnlock(&syncLock) } init(profile: BrowserProfile) { self.profile = profile super.init() let center = NSNotificationCenter.defaultCenter() center.addObserver(self, selector: "onLoginDidChange:", name: NotificationDataLoginDidChange, object: nil) } deinit { // Remove 'em all. NSNotificationCenter.defaultCenter().removeObserver(self) } // Simple in-memory rate limiting. var lastTriggeredLoginSync: Timestamp = 0 @objc func onLoginDidChange(notification: NSNotification) { log.debug("Login did change.") if (NSDate.now() - lastTriggeredLoginSync) > OneMinuteInMilliseconds { lastTriggeredLoginSync = NSDate.now() // Give it a few seconds. let when: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, SyncConstants.SyncDelayTriggered) // Trigger on the main queue. The bulk of the sync work runs in the background. dispatch_after(when, dispatch_get_main_queue()) { self.syncLogins() } } } var prefsForSync: Prefs { return self.profile.prefs.branch("sync") } func onAddedAccount() -> Success { return self.syncEverything() } func onRemovedAccount(account: FirefoxAccount?) -> Success { let h: SyncableHistory = self.profile.history let flagHistory = h.onRemovedAccount() let clearTabs = self.profile.remoteClientsAndTabs.onRemovedAccount() let done = allSucceed(flagHistory, clearTabs) // Clear prefs after we're done clearing everything else -- just in case // one of them needs the prefs and we race. Clear regardless of success // or failure. done.upon { result in // This will remove keys from the Keychain if they exist, as well // as wiping the Sync prefs. SyncStateMachine.clearStateFromPrefs(self.prefsForSync) } return done } private func repeatingTimerAtInterval(interval: NSTimeInterval, selector: Selector) -> NSTimer { return NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: selector, userInfo: nil, repeats: true) } func beginTimedSyncs() { if self.syncTimer != nil { log.debug("Already running sync timer.") return } let interval = FifteenMinutes let selector = Selector("syncOnTimer") log.debug("Starting sync timer.") self.syncTimer = repeatingTimerAtInterval(interval, selector: selector) } /** * The caller is responsible for calling this on the same thread on which it called * beginTimedSyncs. */ func endTimedSyncs() { if let t = self.syncTimer { log.debug("Stopping sync timer.") self.syncTimer = nil t.invalidate() } } private func syncClientsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing clients to storage.") let clientSynchronizer = ready.synchronizer(ClientsSynchronizer.self, delegate: delegate, prefs: prefs) return clientSynchronizer.synchronizeLocalClients(self.profile.remoteClientsAndTabs, withServer: ready.client, info: ready.info) } private func syncTabsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { let storage = self.profile.remoteClientsAndTabs let tabSynchronizer = ready.synchronizer(TabsSynchronizer.self, delegate: delegate, prefs: prefs) return tabSynchronizer.synchronizeLocalTabs(storage, withServer: ready.client, info: ready.info) } private func syncHistoryWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing history to storage.") let historySynchronizer = ready.synchronizer(HistorySynchronizer.self, delegate: delegate, prefs: prefs) return historySynchronizer.synchronizeLocalHistory(self.profile.history, withServer: ready.client, info: ready.info) } private func syncLoginsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing logins to storage.") let loginsSynchronizer = ready.synchronizer(LoginsSynchronizer.self, delegate: delegate, prefs: prefs) return loginsSynchronizer.synchronizeLocalLogins(self.profile.logins, withServer: ready.client, info: ready.info) } /** * Returns nil if there's no account. */ private func withSyncInputs<T>(label: EngineIdentifier? = nil, function: (SyncDelegate, Prefs, Ready) -> Deferred<Result<T>>) -> Deferred<Result<T>>? { if let account = profile.account { if !beginSyncing() { log.info("Not syncing \(label); already syncing something.") return deferResult(AlreadySyncingError()) } if let label = label { log.info("Syncing \(label).") } let authState = account.syncAuthState let syncPrefs = profile.prefs.branch("sync") let readyDeferred = SyncStateMachine.toReady(authState, prefs: syncPrefs) let delegate = profile.getSyncDelegate() let go = readyDeferred >>== { ready in function(delegate, syncPrefs, ready) } // Always unlock when we're done. go.upon({ res in self.endSyncing() }) return go } log.warning("No account; can't sync.") return nil } /** * Runs the single provided synchronization function and returns its status. */ private func sync(label: EngineIdentifier, function: (SyncDelegate, Prefs, Ready) -> SyncResult) -> SyncResult { return self.withSyncInputs(label: label, function: function) ?? deferResult(.NotStarted(.NoAccount)) } /** * Runs each of the provided synchronization functions with the same inputs. * Returns an array of IDs and SyncStatuses the same length as the input. */ private func syncSeveral(synchronizers: (EngineIdentifier, SyncFunction)...) -> Deferred<Result<[(EngineIdentifier, SyncStatus)]>> { typealias Pair = (EngineIdentifier, SyncStatus) let combined: (SyncDelegate, Prefs, Ready) -> Deferred<Result<[Pair]>> = { delegate, syncPrefs, ready in let thunks = synchronizers.map { (i, f) in return { () -> Deferred<Result<Pair>> in log.debug("Syncing \(i)…") return f(delegate, syncPrefs, ready) >>== { deferResult((i, $0)) } } } return accumulate(thunks) } return self.withSyncInputs(label: nil, function: combined) ?? deferResult(synchronizers.map { ($0.0, .NotStarted(.NoAccount)) }) } func syncEverything() -> Success { return self.syncSeveral( ("clients", self.syncClientsWithDelegate), ("tabs", self.syncTabsWithDelegate), ("logins", self.syncLoginsWithDelegate), ("history", self.syncHistoryWithDelegate) ) >>> succeed } @objc func syncOnTimer() { log.debug("Running timed logins sync.") // Note that we use .upon here rather than chaining with >>> precisely // to allow us to sync subsequent engines regardless of earlier failures. // We don't fork them in parallel because we want to limit perf impact // due to background syncs, and because we're cautious about correctness. self.syncLogins().upon { result in if let success = result.successValue { log.debug("Timed logins sync succeeded. Status: \(success.description).") } else { let reason = result.failureValue?.description ?? "none" log.debug("Timed logins sync failed. Reason: \(reason).") } log.debug("Running timed history sync.") self.syncHistory().upon { result in if let success = result.successValue { log.debug("Timed history sync succeeded. Status: \(success.description).") } else { let reason = result.failureValue?.description ?? "none" log.debug("Timed history sync failed. Reason: \(reason).") } } } } func syncClients() -> SyncResult { // TODO: recognize .NotStarted. return self.sync("clients", function: syncClientsWithDelegate) } func syncClientsThenTabs() -> SyncResult { return self.syncSeveral( ("clients", self.syncClientsWithDelegate), ("tabs", self.syncTabsWithDelegate) ) >>== { statuses in let tabsStatus = statuses[1].1 return deferResult(tabsStatus) } } func syncLogins() -> SyncResult { return self.sync("logins", function: syncLoginsWithDelegate) } func syncHistory() -> SyncResult { // TODO: recognize .NotStarted. return self.sync("history", function: syncHistoryWithDelegate) } } } class AlreadySyncingError: ErrorType { var description: String { return "Already syncing." } }
mpl-2.0
TheDarkCode/Example-Swift-Apps
Exercises and Basic Principles/custom-view-basics/custom-view-basics/BlueButton.swift
1
809
// // BlueButton.swift // custom-view-basics // // Created by Mark Hamilton on 2/20/16. // Copyright © 2016 dryverless. All rights reserved. // import UIKit class BlueButton: UIButton { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ // Called while being loaded from xib file override func awakeFromNib() { // Rounded Corners layer.cornerRadius = 5.0 // Background backgroundColor = UIColor(red: 46.0/255.0, green: 135.0/255.0, blue: 195.0/255.0, alpha: 1.0) // Title setTitleColor(UIColor.whiteColor(), forState: .Normal) } }
mit
changjiashuai/AudioKit
Tests/Tests/AKLinearADSREnvelope.swift
14
955
// // main.swift // AudioKit // // Created by Aurelius Prochazka and Nick Arner on 12/29/14. // Copyright (c) 2014 Aurelius Prochazka. All rights reserved. // import Foundation let testDuration: NSTimeInterval = 10.0 class Instrument : AKInstrument { override init() { super.init() let adsr = AKLinearADSREnvelope() enableParameterLog("ADSR value = ", parameter: adsr, timeInterval:0.02) let oscillator = AKOscillator() oscillator.amplitude = adsr setAudioOutput(oscillator) } } AKOrchestra.testForDuration(testDuration) let instrument = Instrument() AKOrchestra.addInstrument(instrument) let note1 = AKNote() let note2 = AKNote() let phrase = AKPhrase() phrase.addNote(note1, atTime:0.5) phrase.stopNote(note1, atTime: 2.5) note2.duration.floatValue = 5.0 phrase.addNote(note2, atTime:3.5) instrument.playPhrase(phrase) NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
mit
tuannme/Up
Up+/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallZigZag.swift
2
3650
// // NVActivityIndicatorAnimationBallZigZag.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import QuartzCore class NVActivityIndicatorAnimationBallZigZag: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSize: CGFloat = size.width / 5 let duration: CFTimeInterval = 0.7 let deltaX = size.width / 2 - circleSize / 2 let deltaY = size.height / 2 - circleSize / 2 let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize) // Circle 1 animation let animation = CAKeyframeAnimation(keyPath:"transform") animation.keyTimes = [0.0, 0.33, 0.66, 1.0] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circle 1 circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation) // Circle 2 animation animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))] // Draw circle 2 circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation) } func circleAt(frame: CGRect, layer: CALayer, size: CGSize, color: UIColor, animation: CAAnimation) { let circle = NVActivityIndicatorShape.circle.layerWith(size: size, color: color) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } }
mit
nathantannar4/NTComponents
NTComponents/Extensions/Int.swift
1
3613
// // Int.swift // NTComponents // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 6/26/17. // public extension Int { public var cgFloat: CGFloat { return CGFloat(self) } /** Return a random number between `min` and `max`. - note: The maximum value cannot be more than `UInt32.max - 1` - parameter min: The minimum value of the random value (defaults to `0`). - parameter max: The maximum value of the random value (defaults to `UInt32.max - 1`) - returns: Returns a random value between `min` and `max`. */ public static func random(min : Int = 0, max : Int = Int.max) -> Int { precondition(min <= max, "attempt to call random() with min > max") let diff = UInt(bitPattern: max &- min) let result = UInt.random(min: 0, max: diff) return min + Int(bitPattern: result) } /** Return a random number with exactly `digits` digits. - parameter digits: The number of digits the random number should have. - returns: Returns a random number with exactly `digits` digits. */ public static func number(digits : Int? = nil) -> Int { let nbDigits = digits != nil ? digits! : Int.random(min: 1, max: 9) let maximum = pow(10, Double(nbDigits)) - 1 let result = Int.random(min: Int(pow(10, Double(nbDigits - 1))), max: Int(maximum)) return result } public func randomize(variation : Int) -> Int { let multiplier = Double(Int.random(min: 100 - variation, max: 100 + variation)) / 100 let randomized = Double(self) * multiplier return Int(randomized) + 1 } } private extension UInt { static func random(min : UInt, max : UInt) -> UInt { precondition(min <= max, "attempt to call random() with min > max") if min == UInt.min && max == UInt.max { var result : UInt = 0 arc4random_buf(&result, MemoryLayout.size(ofValue: result)) return result } else { let range = max - min + 1 let limit = UInt.max - UInt.max % range var result : UInt = 0 repeat { arc4random_buf(&result, MemoryLayout.size(ofValue: result)) } while result >= limit result = result % range return min + result } } }
mit
softwarenerd/Stately
Stately/Code/Event.swift
1
4356
// // Event.swift // Stately // // Created by Brian Lambert on 10/4/16. // See the LICENSE.md file in the project root for license information. // import Foundation // Types alias for a transition tuple. public typealias Transition = (fromState: State?, toState: State) // Event error enumeration. public enum EventError: Error { case NameEmpty case NoTransitions case DuplicateTransition(fromState: State) case MultipleWildcardTransitions } // Event class. public class Event : Hashable { // The name of the event. public let name: String // The set of transitions for the event. let transitions: [Transition] // The wildcard transition. let wildcardTransition: Transition? /// Initializes a new instance of the Event class. /// /// - Parameters: /// - name: The name of the event. Each event must have a unique name. /// - transitions: The transitions for the event. An event must define at least one transition. /// A transition with a from state of nil is the wildcard transition and will match any from /// state. Only one wildcard transition may defined for an event. public init(name nameIn: String, transitions transitionsIn: [Transition]) throws { // Validate the event name. if nameIn.isEmpty { throw EventError.NameEmpty } // At least one transition must be specified. if transitionsIn.count == 0 { throw EventError.NoTransitions } // Ensure that there are no duplicate from state transitions defined. (While this wouldn't strictly // be a bad thing, the presence of duplicate from state transitions more than likely indicates that // there is a bug in the definition of the state machine, so we don't allow it.) Also, there can be // only one wildcard transition (a transition with a nil from state) defined. var wildcardTransitionTemp: Transition? = nil var fromStatesTemp = Set<State>(minimumCapacity: transitionsIn.count) for transition in transitionsIn { // See if there's a from state. If there is, ensure it's not a duplicate. If there isn't, then // ensure there is only one wildcard transition. if let fromState = transition.fromState { if fromStatesTemp.contains(fromState) { throw EventError.DuplicateTransition(fromState: fromState) } else { fromStatesTemp.insert(fromState) } } else { if wildcardTransitionTemp != nil { throw EventError.MultipleWildcardTransitions } else { wildcardTransitionTemp = transition } } } // Initialize. name = nameIn transitions = transitionsIn wildcardTransition = wildcardTransitionTemp } /// Returns the transition with the specified from state, if one is found; otherwise, nil. /// /// - Parameters: /// - fromState: The from state. func transition(fromState: State) -> State? { // Find the transition. If it cannot be found, and there's a wildcard transition, return its to state. // Otherwise, nil will be returned. guard let transition = (transitions.first(where: { (transition: Transition) -> Bool in return transition.fromState === fromState })) else { return wildcardTransition?.toState } // Return the to state. return transition.toState; } /// Gets the hash value. /// /// Hash values are not guaranteed to be equal across different executions of /// your program. Do not save hash values to use during a future execution. public var hashValue: Int { get { return name.hashValue } } /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func ==(lhs: Event, rhs: Event) -> Bool { return lhs === rhs } }
mit
iPantry/iPantry-iOS
Pantry/Models/Item.swift
1
4398
// // Item.swift // Pantry // // Created by Justin Oroz on 7/29/17. // Copyright © 2017 Justin Oroz. All rights reserved. // import Foundation import Alamofire import FirebaseAuth struct Item { /// let ean: String public let suggestions: FirebaseSuggestions public let UPCResults: [UPCDatabaseItem] private var modified = FireDictionary() public var UPCResultIndex = 0 private(set) var expirationEstimate: Int? public var selectedUPCResult: UPCDatabaseItem? { guard UPCResults.count > 0 else { return nil } return UPCResults[UPCResultIndex] } /// Returns data which can be sent to Firebase var data: FireDictionary { return modified } var title: String? { get { if let userItem = self.modified["title"] as? String { return userItem } else if !self.UPCResults.isEmpty, let upcItem = self.UPCResults[UPCResultIndex].title { return upcItem } else { return nil } } set { self.modified["title"] = newValue } } var description: String? { get { if let userItem = self.modified["description"] as? String { return userItem } else if !self.UPCResults.isEmpty, let upcItem = self.UPCResults[UPCResultIndex].description { return upcItem } else { return nil } } set { self.modified["description"] = newValue } } var quantity: UInt? { return self.modified["quantity"] as? UInt } var purchasedDate: String? { return self.modified["purchasedDate"] as? String } var weight: String? { get { if let userItem = self.modified["weight"] as? String { return userItem } else if !self.UPCResults.isEmpty, let upcItem = self.UPCResults[UPCResultIndex].weight { return upcItem } else { return nil } } set { self["size"] = newValue } } var size: String? { get { if let userItem = self.modified["size"] as? String { return userItem } else if !self.UPCResults.isEmpty, let upcItem = self.UPCResults[UPCResultIndex].size { return upcItem } else { return nil } } set { self["size"] = newValue } } // init from firebase and possible upcdb data init(_ ean: String, _ suggestions: FirebaseSuggestions? = nil, _ upcData: [UPCDatabaseItem]? = nil) { self.ean = ean self.suggestions = suggestions ?? FirebaseSuggestions() self.UPCResults = upcData ?? [UPCDatabaseItem]() } subscript(index: String) -> FireValue? { get { let upcInfo = (UPCResults.count > 0) ? UPCResults[UPCResultIndex] : nil return modified[index] ?? upcInfo?[index] as? FireValue } set(newValue) { //can only modify string: values if newValue == nil { modified[index] = newValue return } // UPC results are empty, save the data if UPCResults.count == 0 { modified[index] = newValue return } // if not in UPC results if UPCResults[UPCResultIndex][index] == nil { modified[index] = newValue return } switch newValue!.type { case .bool(let val): if UPCResults[UPCResultIndex][index] as? Bool != val { modified[index] = val } else { // do not allow uploading of same data modified[index] = nil } case .string(let val): if UPCResults[UPCResultIndex][index] as? String != val { modified[index] = val } else { modified[index] = nil } default: return } } } static func lookup(by UPC: String, completion: ((Item?, Error?) -> Void)?) { let dispatch = DispatchGroup() var upcData = [UPCDatabaseItem]() var firebaseSuggestions = FirebaseSuggestions() var itemError: Error? // TODO: Return Item instead dispatch.enter() UPCDB.current.lookup(by: UPC, returned: { (data, error) in defer { dispatch.leave() } guard error == nil, data != nil else { itemError = error //completion?(nil, itemError) return } upcData = data! }) // TODO: Request Firebase Suggestions dispatch.enter() //firebaseData = ["": ""] dispatch.leave() // after both requests are complete dispatch.notify(queue: DispatchQueue.global(qos: DispatchQoS.userInitiated.qosClass)) { guard itemError == nil else { completion?(nil, itemError) return } let item = Item(UPC, firebaseSuggestions, upcData) // If no data or suggestions, alert user guard !firebaseSuggestions.isEmpty || upcData.count > 0 else { completion?(nil, nil) return } completion?(item, nil) } } }
agpl-3.0
astralbodies/CleanRooms
CleanRooms/Services/Model/Room.swift
1
1248
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Foundation import CoreData public class Room: NSManagedObject { // Insert code here to add functionality to your managed object subclass }
mit
CombineCommunity/CombineExt
Tests/PassthroughRelayTests.swift
1
3625
// // PassthroughRelayTests.swift // CombineExtTests // // Created by Shai Mishali on 15/03/2020. // Copyright © 2020 Combine Community. All rights reserved. // #if !os(watchOS) import XCTest import Combine import CombineExt @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) class PassthroughRelayTests: XCTestCase { private var relay: PassthroughRelay<String>? private var values = [String]() private var subscriptions = Set<AnyCancellable>() override func setUp() { relay = PassthroughRelay<String>() subscriptions = .init() values = [] } func testFinishesOnDeinit() { var completed = false relay? .sink(receiveCompletion: { _ in completed = true }, receiveValue: { _ in }) .store(in: &subscriptions) XCTAssertFalse(completed) relay = nil XCTAssertTrue(completed) } func testNoReplay() { relay?.accept("these") relay?.accept("values") relay?.accept("shouldnt") relay?.accept("be") relay?.accept("forwaded") relay? .sink(receiveValue: { self.values.append($0) }) .store(in: &subscriptions) XCTAssertEqual(values, []) relay?.accept("yo") XCTAssertEqual(values, ["yo"]) relay?.accept("sup") XCTAssertEqual(values, ["yo", "sup"]) var secondInitial: String? _ = relay?.sink(receiveValue: { secondInitial = $0 }) XCTAssertNil(secondInitial) } func testVoidAccept() { let voidRelay = PassthroughRelay<Void>() var count = 0 voidRelay .sink(receiveValue: { count += 1 }) .store(in: &subscriptions) voidRelay.accept() voidRelay.accept() voidRelay.accept() voidRelay.accept() voidRelay.accept() XCTAssertEqual(count, 5) } func testSubscribePublisher() { var completed = false relay? .sink(receiveCompletion: { _ in completed = true }, receiveValue: { self.values.append($0) }) .store(in: &subscriptions) ["1", "2", "3"] .publisher .subscribe(relay!) .store(in: &subscriptions) XCTAssertFalse(completed) XCTAssertEqual(values, ["1", "2", "3"]) } func testSubscribeRelay_Passthroughs() { var completed = false let input = PassthroughRelay<String>() let output = PassthroughRelay<String>() input .subscribe(output) .store(in: &subscriptions) output .sink(receiveCompletion: { _ in completed = true }, receiveValue: { self.values.append($0) }) .store(in: &subscriptions) input.accept("1") input.accept("2") input.accept("3") XCTAssertFalse(completed) XCTAssertEqual(values, ["1", "2", "3"]) } func testSubscribeRelay_CurrentValueToPassthrough() { var completed = false let input = CurrentValueRelay<String>("initial") let output = PassthroughRelay<String>() input .subscribe(output) .store(in: &subscriptions) output .sink(receiveCompletion: { _ in completed = true }, receiveValue: { self.values.append($0) }) .store(in: &subscriptions) input.accept("1") input.accept("2") input.accept("3") XCTAssertFalse(completed) XCTAssertEqual(values, ["initial", "1", "2", "3"]) } } #endif
mit
ZhangHangwei/100_days_Swift
Project_31/Project_30/PhotoCell.swift
2
326
// // PhotoCell.swift // Project_30 // // Created by 章航伟 on 07/02/2017. // Copyright © 2017 Harvie. All rights reserved. // import UIKit class PhotoCell: UICollectionViewCell { @IBOutlet weak var image: UIImageView! override func awakeFromNib() { super.awakeFromNib() } }
mit
MaciejGad/InjectStory
Demo/InjectStoryTests/InjectStoryTests.swift
1
1763
// // InjectStoryTests.swift // InjectStoryTests // // Created by Maciej Gad on 30.10.2016. // Copyright © 2016 Maciej Gad. All rights reserved. // import XCTest @testable import InjectStory class InjectStoryTests: XCTestCase { func testIfViewControllerCallMeowMethod() { //given let spy = AnimalSoundSpy() //override value returned by viewModelInjection ViewController.viewModelInjection.overrideOnce = { spy } let sut = viewController() //when _ = sut.view //then XCTAssertTrue(spy.makeSoundCalled) } func testIfViewControllerSetLabelTitle() { //given let givenSound = "meow meow I'm a cow" let fake = AnimalSoundFake(sound: givenSound) //override value returned by viewModelInjection ViewController.viewModelInjection.overrideOnce = { fake } let sut = viewController() //when _ = sut.view //then guard let soudText = sut.soundLabel.text else { XCTFail() return } XCTAssertEqual(soudText, givenSound) } private func viewController() -> ViewController { let storyboard = UIStoryboard(name: "Main", bundle: nil) return storyboard.instantiateViewController(withIdentifier: "viewController") as! ViewController } } class AnimalSoundSpy: AnimalSound { var makeSoundCalled = false func makeSound() -> String{ makeSoundCalled = true return "" } } class AnimalSoundFake: AnimalSound { let sound:String init(sound:String) { self.sound = sound } func makeSound() -> String { return sound } }
mit
zhuyunfeng1224/XiheMtxx
XiheMtxx/VC/EditImage/RotateCtrlView.swift
1
12287
// // RotateCtrlView.swift // XiheMtxx // // Created by echo on 2017/3/3. // Copyright © 2017年 羲和. All rights reserved. // import UIKit protocol RotateCtrlViewDelegate { func rotateImageChanged() -> Void } class RotateCtrlView: UIView { var delegate: RotateCtrlViewDelegate? lazy var bgView: UIView = { let _bgView = UIView(frame: CGRect(origin: CGPoint.zero, size: self.frame.size)) _bgView.backgroundColor = UIColor.colorWithHexString(hex: "#2c2e30") _bgView.clipsToBounds = true return _bgView }() lazy var imageView: UIImageView = { let _imageView = UIImageView(frame: CGRect(origin: CGPoint.zero, size: self.frame.size)) _imageView.clipsToBounds = true _imageView.contentMode = .scaleAspectFit return _imageView }() lazy var clearMaskView: GrayView = { let _maskView = GrayView(frame: CGRect(origin: CGPoint.zero, size: self.frame.size)) _maskView.clearFrame = CGRect(origin: CGPoint.zero, size: self.frame.size) _maskView.isUserInteractionEnabled = false return _maskView }() // 结束执行块 var dismissCompletation: ((UIImage) -> (Void))? /// 原始图片 var originImage: UIImage? { didSet { self.imageView.image = originImage self.image = originImage } } /// 编辑后的图片 var image: UIImage? { didSet { self.imageView.image = image } } var enlarged: Bool = false { didSet { UIView.animate(withDuration: 0.3) { let signX = self.scale.width / fabs(self.scale.width) let signY = self.scale.height / fabs(self.scale.height) if self.enlarged { let scale = self.imageViewScale() self.scale = CGSize(width: signX * scale, height: signY * scale) self.newImageTransform() self.clearMaskView.clearFrame = self.imageView.bounds } else { self.scale = CGSize(width: signX, height: signY) self.newImageTransform() let cutSize = self.imageView.bounds.size.applying(CGAffineTransform(scaleX: 1 / self.imageViewScale(), y: 1 / self.imageViewScale())) self.clearMaskView.clearFrame = CGRect(x: self.imageView.center.x - cutSize.width/2, y: self.imageView.center.y - cutSize.height/2, width: cutSize.width, height: cutSize.height) } } } } /// 旋转角度 var rotation: CGFloat = 0.0 /// 缩放倍数 var scale: CGSize = CGSize(width: 1, height: 1) /// 上一次拖动的位置 lazy var lastPosition = CGPoint.zero override init(frame: CGRect) { super.init(frame: frame) self.isUserInteractionEnabled = true self.addSubview(self.bgView) self.bgView.addSubview(self.imageView) self.bgView.addSubview(self.clearMaskView) // 拖动手势 let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panImage(gesture:))) self.bgView.addGestureRecognizer(panGesture) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var isHidden: Bool { didSet { if isHidden == true { self.generateNewTransformImage() } } } func generateNewTransformImage() -> Void { if self.image == nil { return } // 生成剪切后的图片 if let cgImage = self.newTransformedImage(transform: self.imageView.transform, sourceImage: (self.image?.cgImage)!, imageSize: (self.image?.size)!) { self.image = UIImage(cgImage: cgImage) } if let dismissCompletation = self.dismissCompletation { dismissCompletation(self.image!) self.rotation = 0 self.scale = CGSize(width: 1, height: 1) self.imageView.transform = .identity } } // MARK: Action Events // 拖动手势响应 func panImage(gesture: UIPanGestureRecognizer) -> Void { if gesture.state == .changed { let origin = CGPoint(x: self.bgView.frame.size.width/2, y: self.bgView.frame.size.height/2) let currentPosition = gesture.location(in: self.bgView) let vectorA = CGPoint(x: lastPosition.x - origin.x, y: lastPosition.y - origin.y) let vectorB = CGPoint(x: currentPosition.x - origin.x, y: currentPosition.y - origin.y) // 向量a的模 let modA = sqrtf(powf(Float(vectorA.x), 2) + powf(Float(vectorA.y), 2)) // 向量b的模 let modB = sqrtf(powf(Float(vectorB.x), 2) + powf(Float(vectorB.y), 2)) // 向量a,b的点乘 let pointMuti = Float(vectorA.x * vectorB.x + vectorA.y * vectorB.y) // 夹角 let angle = acos(pointMuti / (modA * modB)) // 叉乘求旋转方向,顺时针还是逆时针 let signX = Float(self.scale.width / fabs(self.scale.width)) let signY = Float(self.scale.height / fabs(self.scale.height)) let crossAB = vectorA.x * vectorB.y - vectorA.y * vectorB.x let sign: Float = crossAB > 0.0 ? 1.0: -1.0 if !angle.isNaN && angle != 0.0 { self.rotation += CGFloat(angle * sign * signX * signY) self.newImageTransform() self.clearMaskView.clearFrame = self.caculateCutRect() } } else if gesture.state == .ended || gesture.state == .cancelled { // 取消放大 self.enlarged = true } lastPosition = gesture.location(in: self.bgView) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // 点击缩小 if self.enlarged == true { self.enlarged = false } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { // 取消放大 self.enlarged = true } func rotateReset() -> Void { self.rotation = 0 self.scale = CGSize(width: 1, height: 1) self.image = self.originImage UIView.animate(withDuration: 0.3) { self.imageView.transform = .identity } } func rotateLeft() -> Void { self.rotation += CGFloat(-Float.pi / 2) UIView.animate(withDuration: 0.3) { self.newImageTransform() } } func rotateRight() -> Void { self.rotation += CGFloat(Float.pi / 2) UIView.animate(withDuration: 0.3) { self.newImageTransform() } } func rotateHorizontalMirror() -> Void { self.scale = CGSize(width: self.scale.width * -1, height: self.scale.height) UIView.animate(withDuration: 0.3) { self.newImageTransform() } } func rotateVerticalnMirror() -> Void { self.scale = CGSize(width: self.scale.width, height: self.scale.height * -1) UIView.animate(withDuration: 0.3) { self.newImageTransform() } } func resetLayoutOfSubviews() -> Void { let rect = self.imageRectToFit() self.bgView.frame = rect self.imageView.frame = self.bgView.bounds self.clearMaskView.frame = self.bgView.bounds self.clearMaskView.center = self.imageView.center } // MARK: Private Method // 计算剪切区域 func caculateCutRect() -> CGRect { let scale = self.enlarged ? self.imageViewScale() : 1 / self.imageViewScale() let cutSize = self.imageView.bounds.size.applying(CGAffineTransform(scaleX: scale, y: scale)) let cutFrame = CGRect(x: self.imageView.center.x - cutSize.width/2, y: self.imageView.center.y - cutSize.height/2, width: cutSize.width, height: cutSize.height) return cutFrame } // 旋转之后图片放大的倍数 func imageViewScale() -> CGFloat { let scaleX = self.imageView.frame.size.width / self.imageView.bounds.size.width let scaleY = self.imageView.frame.size.height / self.imageView.bounds.size.height let scale = fabsf(Float(scaleX)) > fabsf(Float(scaleY)) ? scaleX : scaleY return scale } func newImageTransform() -> Void { let transform = CGAffineTransform(rotationAngle: self.rotation) let scaleTransform = CGAffineTransform(scaleX: self.scale.width, y: self.scale.height) self.imageView.transform = transform.concatenating(scaleTransform) if self.delegate != nil { self.delegate?.rotateImageChanged() } } /// create a new image according to transform and origin image /// /// - Parameters: /// - transform: the transform after image rotated /// - sourceImage: sourceImage /// - imageSize: size of sourceImage /// - Returns: new Image func newTransformedImage(transform: CGAffineTransform, sourceImage:CGImage, imageSize: CGSize) -> CGImage? { // 计算旋转后图片的大小 let size = CGSize(width: imageSize.width * self.imageViewScale(), height: imageSize.height * self.imageViewScale()) // 创建画布 let context = CGContext.init(data: nil, width: Int(imageSize.width), height: Int(imageSize.height), bitsPerComponent: sourceImage.bitsPerComponent, bytesPerRow: 0, space: sourceImage.colorSpace!, bitmapInfo: sourceImage.bitmapInfo.rawValue) context?.setFillColor(UIColor.clear.cgColor) context?.fill(CGRect(origin: CGPoint.zero, size: imageSize)) // quartz旋转以左上角为中心,so 将画布移到右下角,旋转之后再向上移到原来位置 context?.translateBy(x: imageSize.width / 2, y: imageSize.height / 2) context?.concatenate(transform.inverted()) context?.translateBy(x: -size.width / 2, y: -size.height / 2) context?.draw(sourceImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let result = context?.makeImage() assert(result != nil, "旋转图片剪切失败") UIGraphicsEndImageContext() return result! } func imageRectToFit() -> CGRect { let rect = self.frame // 原始图片View的尺寸 let originImageScale = (self.image?.size.width)!/(self.image?.size.height)! let imageViewSize = rect.size let imageViewScale = imageViewSize.width/imageViewSize.height var imageSizeInView = imageViewSize // 得出图片在ImageView中的尺寸 if imageViewScale <= originImageScale { imageSizeInView = CGSize(width: imageViewSize.width, height: imageViewSize.width / originImageScale) } else { imageSizeInView = CGSize(width: imageViewSize.height * originImageScale, height: imageViewSize.height) } let imageOriginInView = CGPoint(x: (rect.size.width - imageSizeInView.width)/2, y: (rect.size.height - imageSizeInView.height)/2) return CGRect(origin: imageOriginInView, size: imageSizeInView) } }
mit
radazzouz/firefox-ios
SyncTests/MockSyncServer.swift
1
17774
/* 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 GCDWebServers import SwiftyJSON @testable import Sync import XCTest private let log = Logger.syncLogger private func optTimestamp(x: AnyObject?) -> Timestamp? { guard let str = x as? String else { return nil } return decimalSecondsStringToTimestamp(str) } private func optStringArray(x: AnyObject?) -> [String]? { guard let str = x as? String else { return nil } return str.components(separatedBy: ",").map { $0.trimmingCharacters(in:NSCharacterSet.whitespacesAndNewlines) } } private struct SyncRequestSpec { let collection: String let id: String? let ids: [String]? let limit: Int? let offset: String? let sort: SortOption? let newer: Timestamp? let full: Bool static func fromRequest(request: GCDWebServerRequest) -> SyncRequestSpec? { // Input is "/1.5/user/storage/collection", possibly with "/id" at the end. // That means we get five or six path components here, the first being empty. let parts = request.path!.components(separatedBy: "/").filter { !$0.isEmpty } let id: String? let query = request.query as! [String: AnyObject] let ids = optStringArray(x: query["ids"]) let newer = optTimestamp(x: query["newer"]) let full: Bool = query["full"] != nil let limit: Int? if let lim = query["limit"] as? String { limit = Int(lim) } else { limit = nil } let offset = query["offset"] as? String let sort: SortOption? switch query["sort"] as? String ?? "" { case "oldest": sort = SortOption.OldestFirst case "newest": sort = SortOption.NewestFirst case "index": sort = SortOption.Index default: sort = nil } if parts.count < 4 { return nil } if parts[2] != "storage" { return nil } // Use dropFirst, you say! It's buggy. switch parts.count { case 4: id = nil case 5: id = parts[4] default: // Uh oh. return nil } return SyncRequestSpec(collection: parts[3], id: id, ids: ids, limit: limit, offset: offset, sort: sort, newer: newer, full: full) } } struct SyncDeleteRequestSpec { let collection: String? let id: GUID? let ids: [GUID]? let wholeCollection: Bool static func fromRequest(request: GCDWebServerRequest) -> SyncDeleteRequestSpec? { // Input is "/1.5/user{/storage{/collection{/id}}}". // That means we get four, five, or six path components here, the first being empty. return SyncDeleteRequestSpec.fromPath(path: request.path!, withQuery: request.query as! [NSString : AnyObject]) } static func fromPath(path: String, withQuery query: [NSString: AnyObject]) -> SyncDeleteRequestSpec? { let parts = path.components(separatedBy: "/").filter { !$0.isEmpty } let queryIDs: [GUID]? = (query["ids"] as? String)?.components(separatedBy: ",") guard [2, 4, 5].contains(parts.count) else { return nil } if parts.count == 2 { return SyncDeleteRequestSpec(collection: nil, id: nil, ids: queryIDs, wholeCollection: true) } if parts[2] != "storage" { return nil } if parts.count == 4 { let hasIDs = queryIDs != nil return SyncDeleteRequestSpec(collection: parts[3], id: nil, ids: queryIDs, wholeCollection: !hasIDs) } return SyncDeleteRequestSpec(collection: parts[3], id: parts[4], ids: queryIDs, wholeCollection: false) } } private struct SyncPutRequestSpec { let collection: String let id: String static func fromRequest(request: GCDWebServerRequest) -> SyncPutRequestSpec? { // Input is "/1.5/user/storage/collection/id}}}". // That means we get six path components here, the first being empty. let parts = request.path!.components(separatedBy: "/").filter { !$0.isEmpty } guard parts.count == 5 else { return nil } if parts[2] != "storage" { return nil } return SyncPutRequestSpec(collection: parts[3], id: parts[4]) } } class MockSyncServer { let server = GCDWebServer() let username: String var offsets: Int = 0 var continuations: [String: [EnvelopeJSON]] = [:] var collections: [String: (modified: Timestamp, records: [String: EnvelopeJSON])] = [:] var baseURL: String! init(username: String) { self.username = username } class func makeValidEnvelope(guid: GUID, modified: Timestamp) -> EnvelopeJSON { let clientBody: [String: Any] = [ "id": guid, "name": "Foobar", "commands": [], "type": "mobile", ] let clientBodyString = JSON(object: clientBody).rawString()! let clientRecord: [String : Any] = [ "id": guid, "collection": "clients", "payload": clientBodyString, "modified": Double(modified) / 1000, ] return EnvelopeJSON(JSON(object: clientRecord).rawString()!) } class func withHeaders(response: GCDWebServerResponse, lastModified: Timestamp? = nil, records: Int? = nil, timestamp: Timestamp? = nil) -> GCDWebServerResponse { let timestamp = timestamp ?? Date.now() let xWeaveTimestamp = millisecondsToDecimalSeconds(timestamp) response.setValue("\(xWeaveTimestamp)", forAdditionalHeader: "X-Weave-Timestamp") if let lastModified = lastModified { let xLastModified = millisecondsToDecimalSeconds(lastModified) response.setValue("\(xLastModified)", forAdditionalHeader: "X-Last-Modified") } if let records = records { response.setValue("\(records)", forAdditionalHeader: "X-Weave-Records") } return response } func storeRecords(records: [EnvelopeJSON], inCollection collection: String, now: Timestamp? = nil) { let now = now ?? Date.now() let coll = self.collections[collection] var out = coll?.records ?? [:] records.forEach { out[$0.id] = $0.withModified(now) } let newModified = max(now, coll?.modified ?? 0) self.collections[collection] = (modified: newModified, records: out) } private func splitArray<T>(items: [T], at: Int) -> ([T], [T]) { return (Array(items.dropLast(items.count - at)), Array(items.dropFirst(at))) } private func recordsMatchingSpec(spec: SyncRequestSpec) -> (records: [EnvelopeJSON], offsetID: String?)? { // If we have a provided offset, handle that directly. if let offset = spec.offset { log.debug("Got provided offset \(offset).") guard let remainder = self.continuations[offset] else { log.error("Unknown offset.") return nil } // Remove the old one. self.continuations.removeValue(forKey: offset) // Handle the smaller-than-limit or no-provided-limit cases. guard let limit = spec.limit, limit < remainder.count else { log.debug("Returning all remaining items.") return (remainder, nil) } // Record the next continuation and return the first slice of records. let next = "\(self.offsets)" self.offsets += 1 let (returned, remaining) = splitArray(items: remainder, at: limit) self.continuations[next] = remaining log.debug("Returning \(limit) items; next continuation is \(next).") return (returned, next) } guard let records = self.collections[spec.collection]?.records.values else { // No matching records. return ([], nil) } var items = Array(records) log.debug("Got \(items.count) candidate records.") if spec.newer ?? 0 > 0 { items = items.filter { $0.modified > spec.newer! } } if let ids = spec.ids { let ids = Set(ids) items = items.filter { ids.contains($0.id) } } if let sort = spec.sort { switch sort { case SortOption.NewestFirst: items = items.sorted { $0.modified > $1.modified } log.debug("Sorted items newest first: \(items.map { $0.modified })") case SortOption.OldestFirst: items = items.sorted { $0.modified < $1.modified } log.debug("Sorted items oldest first: \(items.map { $0.modified })") case SortOption.Index: log.warning("Index sorting not yet supported.") } } if let limit = spec.limit, items.count > limit { let next = "\(self.offsets)" self.offsets += 1 let (returned, remaining) = splitArray(items: items, at: limit) self.continuations[next] = remaining return (returned, next) } return (items, nil) } private func recordResponse(record: EnvelopeJSON) -> GCDWebServerResponse { let body = record.asJSON().rawString()! let bodyData = body.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json") return MockSyncServer.withHeaders(response: response!, lastModified: record.modified) } private func modifiedResponse(timestamp: Timestamp) -> GCDWebServerResponse { let body = JSON(object: ["modified": timestamp]).rawString() let bodyData = body?.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json")! return MockSyncServer.withHeaders(response: response) } func modifiedTimeForCollection(collection: String) -> Timestamp? { return self.collections[collection]?.modified } func removeAllItemsFromCollection(collection: String, atTime: Timestamp) { if self.collections[collection] != nil { self.collections[collection] = (atTime, [:]) } } func start() { let basePath = "/1.5/\(self.username)" let storagePath = "\(basePath)/storage/" let infoCollectionsPath = "\(basePath)/info/collections" server?.addHandler(forMethod: "GET", path: infoCollectionsPath, request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in var ic = [String: Any]() var lastModified: Timestamp = 0 for collection in self.collections.keys { if let timestamp = self.modifiedTimeForCollection(collection: collection) { ic[collection] = Double(timestamp) / 1000 lastModified = max(lastModified, timestamp) } } let body = JSON(object: ic).rawString() let bodyData = body?.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json")! return MockSyncServer.withHeaders(response: response, lastModified: lastModified, records: ic.count) } let matchPut: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in guard method == "PUT", path?.startsWith(basePath) ?? false else { return nil } return GCDWebServerDataRequest(method: method, url: url, headers: headers, path: path, query: query) } server?.addHandler(match: matchPut) { (request) -> GCDWebServerResponse! in guard let request = request as? GCDWebServerDataRequest else { return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 400)) } guard let spec = SyncPutRequestSpec.fromRequest(request: request) else { return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 400)) } var body = JSON(object: request.jsonObject) body["modified"] = JSON(stringLiteral: millisecondsToDecimalSeconds(Date.now())) let record = EnvelopeJSON(body) self.storeRecords(records: [record], inCollection: spec.collection) let timestamp = self.modifiedTimeForCollection(collection: spec.collection)! let response = GCDWebServerDataResponse(data: millisecondsToDecimalSeconds(timestamp).utf8EncodedData, contentType: "application/json") return MockSyncServer.withHeaders(response: response!) } let matchDelete: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in guard method == "DELETE" && (path?.startsWith(basePath))! else { return nil } return GCDWebServerRequest(method: method, url: url, headers: headers, path: path, query: query) } server?.addHandler(match: matchDelete) { (request) -> GCDWebServerResponse! in guard let spec = SyncDeleteRequestSpec.fromRequest(request: request!) else { return GCDWebServerDataResponse(statusCode: 400) } if let collection = spec.collection, let id = spec.id { guard var items = self.collections[collection]?.records else { // Unable to find the requested collection. return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 404)) } guard let item = items[id] else { // Unable to find the requested id. return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 404)) } items.removeValue(forKey: id) return self.modifiedResponse(timestamp: item.modified) } if let collection = spec.collection { if spec.wholeCollection { self.collections.removeValue(forKey: collection) } else { if let ids = spec.ids, var map = self.collections[collection]?.records { for id in ids { map.removeValue(forKey: id) } self.collections[collection] = (Date.now(), records: map) } } return self.modifiedResponse(timestamp: Date.now()) } self.collections = [:] return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(data: "{}".utf8EncodedData, contentType: "application/json")) } let match: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in guard method == "GET", path?.startsWith(storagePath) ?? false else { return nil } return GCDWebServerRequest(method: method, url: url, headers: headers, path: path, query: query) } server?.addHandler(match: match) { (request) -> GCDWebServerResponse! in // 1. Decide what the URL is asking for. It might be a collection fetch or // an individual record, and it might have query parameters. guard let spec = SyncRequestSpec.fromRequest(request: request!) else { return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 400)) } // 2. Grab the matching set of records. Prune based on TTL, exclude with X-I-U-S, etc. if let id = spec.id { guard let collection = self.collections[spec.collection], let record = collection.records[id] else { // Unable to find the requested collection/id. return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 404)) } return self.recordResponse(record: record) } guard let (items, offset) = self.recordsMatchingSpec(spec: spec) else { // Unable to find the provided offset. return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 400)) } // TODO: TTL // TODO: X-I-U-S let body = JSON(object: items.map { $0.asJSON() }).rawString() let bodyData = body?.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json") // 3. Compute the correct set of headers: timestamps, X-Weave-Records, etc. if let offset = offset { response?.setValue(offset, forAdditionalHeader: "X-Weave-Next-Offset") } let timestamp = self.modifiedTimeForCollection(collection: spec.collection)! log.debug("Returning GET response with X-Last-Modified for \(items.count) records: \(timestamp).") return MockSyncServer.withHeaders(response: response!, lastModified: timestamp, records: items.count) } if server?.start(withPort: 0, bonjourName: nil) == false { XCTFail("Can't start the GCDWebServer.") } baseURL = "http://localhost:\(server!.port)\(basePath)" } }
mpl-2.0
minorblend/SnowFallView
Example/SnowFallViewExample/ViewController.swift
1
547
// // ViewController.swift // SnowFallViewExample // // Copyright © 2016 Ha Nyung Chung. All rights reserved. // import UIKit import SnowFallView class ViewController: UIViewController { var snowFallView: SnowFallView? override func loadView() { self.snowFallView = SnowFallView() self.view = self.snowFallView } override func viewDidAppear(animated: Bool) { self.snowFallView?.start() } override func viewDidDisappear(animated: Bool) { self.snowFallView?.stop() } }
mit
Beaver/BeaverCodeGen
Pods/Beaver/Beaver/Middleware/LoggingMiddleware.swift
3
656
extension Store.Middleware { /// A MiddleWare logging every actions and state updates public static var logging: Store<StateType>.Middleware { return Store<StateType>.Middleware(name: "LoggingMiddleware") { action, update in #if DEBUG print(">>>>>>>>>>>") print("action: \(String(describing: action))") if let update = update { print("-----------") print("old state: \(String(describing: update.oldState))") print("-----------") print("new state: \(update.newState)") } print("<<<<<<<<<<<") #endif } } }
mit
justindhill/Jiramazing
src/model/Priority.swift
1
853
// // Priority.swift // Pods // // Created by Justin Hill on 8/19/16. // // import Foundation import HexColors @objc(JRAPriority) public class Priority: NSObject { @objc(identifier) public var id: String? public var url: NSURL? public var color: UIColor? public var priorityDescription: String? public var name: String? init(attributes: [String: AnyObject]) { super.init() if let urlString = attributes["self"] as? String { self.url = NSURL(string: urlString) } if let colorString = attributes["statusColor"] as? String { self.color = UIColor.hx_colorWithHexString(colorString) } self.priorityDescription = attributes["description"] as? String self.name = attributes["name"] as? String self.id = attributes["id"] as? String } }
mit
sivu22/AnyTracker
AnyTracker/App.swift
1
6470
// // App.swift // AnyTracker // // Created by Cristian Sava on 10/02/16. // Copyright © 2016 Cristian Sava. All rights reserved. // import UIKit import Foundation struct Constants { struct Key { static let noContent = "NoContent" static let numberSeparator = "NumberSeparator" static let dateFormatLong = "DateFormatLong" static let addNewListTop = "AddNewListTop" static let addNewItemTop = "AddNewItemTop" } struct Text { static let listAll = "ALL" static let listItems = " Items" } struct File { static let ext = ".json" static let lists = "lists.json" static let list = "list" static let item = "item" } struct Limits { static let itemsPerList = 128 } struct Colors { static let ItemSum = UIColor(red: 0, green: 122, blue: 255) static let ItemCounter = UIColor(red: 85, green: 205, blue: 0) static let ItemJournal = UIColor(red: 255, green: 132, blue: 0) } struct Animations { static let keyboardDuration = 0.3 static let keyboardCurve = UIView.AnimationCurve.easeOut static let keyboardDistanceToControl: CGFloat = 10 } } enum Status: String, Error { case errorDefault = "Unknown error" case errorInputString = "Bad input found!" case errorIndex = "Index error" case errorFailedToAddList = "Failed to add list. Try again later" case errorListsFileSave = "Could not save lists data" case errorListsFileLoad = "Failed to load lists data" case errorListsBadCache = "Corrupted data!" case errorListFileSave = "Could not save list. Try again later" case errorListFileLoad = "Failed to load list" case errorListDelete = "Failed to delete list" case errorItemBadID = "Wrong item ID. Please try again" case errorItemFileSave = "Could not save item. Try again later" case errorItemFileLoad = "Failed to load item" case errorJSONDeserialize = "Could not load data: corrupted/invalid format" case errorJSONSerialize = "Failed to serialize data" func createErrorAlert() -> UIAlertController { var title: String; switch self { case .errorDefault, .errorInputString, .errorIndex: title = "Fatal error" case .errorFailedToAddList, .errorListsFileSave, .errorListsFileLoad, .errorListsBadCache, .errorListFileSave, .errorListFileLoad, .errorListDelete, .errorItemBadID, .errorItemFileSave, .errorItemFileLoad, .errorJSONDeserialize, .errorJSONSerialize: title = "Error" } let alert = UIAlertController(title: title, message: self.rawValue, preferredStyle: UIAlertController.Style.alert) let defaultAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil) alert.addAction(defaultAction) return alert } } class App { static fileprivate(set) var version: String = { let appPlist = Bundle.main.infoDictionary as [String: AnyObject]? return appPlist!["CFBundleShortVersionString"] as! String }() // Array of lists ID var lists: Lists? // Settings fileprivate(set) var noContent: Bool fileprivate(set) var numberSeparator: Bool fileprivate(set) var dateFormatLong: Bool fileprivate(set) var addNewListTop: Bool fileprivate(set) var addNewItemTop: Bool init(noContent: Bool, numberSeparator: Bool, dateFormatLong: Bool, addNewListTop: Bool, addNewItemTop: Bool) { self.noContent = noContent self.numberSeparator = numberSeparator self.dateFormatLong = dateFormatLong self.addNewListTop = addNewListTop self.addNewItemTop = addNewItemTop Utils.debugLog("Initialized a new App instance with settings \(self.noContent),\(self.numberSeparator),\(self.dateFormatLong),\(self.addNewListTop),\(self.addNewItemTop)") } func appInit() { Utils.debugLog("App init...") setupDefaultValues() loadSettings() } func appPause() { Utils.debugLog("App moves to inactive state...") } func appResume() { Utils.debugLog("App moves to active state...") } func appExit() { Utils.debugLog("App will terminate...") } fileprivate func setupDefaultValues() { let defaultPrefsFile = Bundle.main.url(forResource: "DefaultSettings", withExtension: "plist") if let prefsFile = defaultPrefsFile { let defaultPrefs = NSDictionary(contentsOf: prefsFile) as! [String : AnyObject] UserDefaults.standard.register(defaults: defaultPrefs) } else { Utils.debugLog("DefaultSettings not found in bundle!") } } fileprivate func loadSettings() { noContent = UserDefaults.standard.bool(forKey: Constants.Key.noContent) numberSeparator = UserDefaults.standard.bool(forKey: Constants.Key.numberSeparator) dateFormatLong = UserDefaults.standard.bool(forKey: Constants.Key.dateFormatLong) addNewListTop = UserDefaults.standard.bool(forKey: Constants.Key.addNewListTop) addNewItemTop = UserDefaults.standard.bool(forKey: Constants.Key.addNewItemTop) } func toggleNoContent() { Utils.debugLog("toggleNoContent") noContent = !noContent UserDefaults.standard.set(noContent, forKey: Constants.Key.noContent) } func toggleNumberSeparator() { Utils.debugLog("toggleNumberSeparator") numberSeparator = !numberSeparator UserDefaults.standard.set(numberSeparator, forKey: Constants.Key.numberSeparator) } func toggleDateFormatLong() { Utils.debugLog("toggleDateFormatLong") dateFormatLong = !dateFormatLong UserDefaults.standard.set(dateFormatLong, forKey: Constants.Key.dateFormatLong) } func toggleAddNewListTop() { Utils.debugLog("toggleAddNewListTop") addNewListTop = !addNewListTop UserDefaults.standard.set(addNewListTop, forKey: Constants.Key.addNewListTop) } func toggleAddNewItemTop() { Utils.debugLog("toggleAddNewItemTop") addNewItemTop = !addNewItemTop UserDefaults.standard.set(addNewItemTop, forKey: Constants.Key.addNewItemTop) } }
mit
radex/swift-compiler-crashes
crashes-fuzzing/08462-void.swift
11
238
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum B{ let a=0.g enum S{ class A{ struct Q<T where H:T{ struct B<H:a
mit
ericmarkmartin/Nightscouter2
Common/Extensions/NSURL-Extensions.swift
1
5494
// // NSURL-Extensions.swift // // import Foundation // MARK: NSURL Validation // Modified by Peter // Created by James Hickman on 11/18/14. // Copyright (c) 2014 NitWit Studios. All rights reserved. public extension NSURL { public struct ValidationQueue { public static var queue = NSOperationQueue() } enum ValidationError: ErrorType { case Empty(String) case OnlyPrefix(String) case ContainsWhitespace(String) case CouldNotCreateURL(String) } public class func validateUrl(urlString: String?) throws -> NSURL { // Description: This function will validate the format of a URL, re-format if necessary, then attempt to make a header request to verify the URL actually exists and responds. // Return Value: This function has no return value but uses a closure to send the response to the caller. var formattedUrlString : String? // Ignore Nils & Empty Strings if (urlString == nil || urlString == "") { throw ValidationError.Empty("Url String was empty") } // Ignore prefixes (including partials) let prefixes = ["http://www.", "https://www.", "www."] for prefix in prefixes { if ((prefix.rangeOfString(urlString!, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)) != nil){ throw ValidationError.OnlyPrefix("Url String was prefix only") } } // Ignore URLs with spaces (NOTE - You should use the below method in the caller to remove spaces before attempting to validate a URL) let range = urlString!.rangeOfCharacterFromSet(NSCharacterSet.whitespaceCharacterSet()) if let _ = range { throw ValidationError.ContainsWhitespace("Url String cannot contain whitespaces") } // Check that URL already contains required 'http://' or 'https://', prepend if it does not formattedUrlString = urlString if (!formattedUrlString!.hasPrefix("http://") && !formattedUrlString!.hasPrefix("https://")) { formattedUrlString = "https://"+urlString! } guard let finalURL = NSURL(string: formattedUrlString!) else { throw ValidationError.CouldNotCreateURL("Url could not be created.") } return finalURL } public class func validateUrl(urlString: String?, completion:(success: Bool, urlString: String? , error: NSString) -> Void) { let parsedURL = try? validateUrl(urlString) // Check that an NSURL can actually be created with the formatted string if let validatedUrl = parsedURL //NSURL(string: formattedUrlString!) { // Test that URL actually exists by sending a URL request that returns only the header response let request = NSMutableURLRequest(URL: validatedUrl) request.HTTPMethod = "HEAD" ValidationQueue.queue.cancelAllOperations() let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: ValidationQueue.queue) let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in let url = request.URL!.absoluteString // URL failed - No Response if (error != nil) { completion(success: false, urlString: url, error: "The url: \(url) received no response") return } // URL Responded - Check Status Code if let urlResponse = response as? NSHTTPURLResponse { if ((urlResponse.statusCode >= 200 && urlResponse.statusCode < 400) || urlResponse.statusCode == 405) // 200-399 = Valid Responses, 405 = Valid Response (Weird Response on some valid URLs) { completion(success: true, urlString: url, error: "The url: \(url) is valid!") return } else // Error { completion(success: false, urlString: url, error: "The url: \(url) received a \(urlResponse.statusCode) response") return } } }) task.resume() } } } // Created by Pete // inspired by https://github.com/ReactiveCocoa/ReactiveCocoaIO/blob/master/ReactiveCocoaIO/NSURL%2BTrailingSlash.m // MARK: Detect and remove trailing forward slash in URL. public extension NSURL { public var hasTrailingSlash: Bool { return self.absoluteString.hasSuffix("/") } public var URLByAppendingTrailingSlash: NSURL? { if !self.hasTrailingSlash, let newURL = NSURL(string: self.absoluteString.stringByAppendingString("/")){ return newURL } return nil } public var URLByDeletingTrailingSlash: NSURL? { let urlString = self.absoluteString let stepBackOne = urlString.endIndex.advancedBy(-1) if self.hasTrailingSlash, let newURL = NSURL(string: urlString.substringToIndex(stepBackOne)) { return newURL } return nil } }
mit
Yalantis/PixPic
PixPic/Classes/Services/ExceptionHandler.swift
1
630
// // ExceptionHandler.swift // PixPic // // Created by AndrewPetrov on 2/2/16. // Copyright © 2016 Yalantis. All rights reserved. // import Foundation enum Exception: String, ErrorType { case NoConnection = "There is no internet connection" case CantApplyStickers = "You can't apply stickers to the photo" case CantCreateParseFile = "You can't create parse file" case InvalidSessionToken = "You can't get authorization data from Facebook" } class ExceptionHandler { static func handle(exception: Exception) { AlertManager.sharedInstance.showSimpleAlert(exception.rawValue) } }
mit
codingTheHole/BuildingAppleWatchProjectsBook
Xcode Projects by Chapter/5086_Code_Ch10_Advanced Navigation/AdvanceNavigation WatchKit Extension/ExtensionDelegate.swift
1
1023
// // ExtensionDelegate.swift // AdvanceNavigation WatchKit Extension // // Created by Stuart Grimshaw on 21/12/15. // Copyright © 2015 Stuart Grimshaw. All rights reserved. // import WatchKit class ExtensionDelegate: NSObject, WKExtensionDelegate { func applicationDidFinishLaunching() { // Perform any final initialization of your application. } func applicationDidBecomeActive() { // 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 applicationWillResignActive() { // 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, etc. } }
cc0-1.0
crepashok/The-Complete-Watch-OS2-Developer-Course
Section-11/Quote Of The Day/Quote Of The Day WatchKit Extension/GlanceController.swift
1
736
// // GlanceController.swift // Quote Of The Day WatchKit Extension // // Created by Pavlo Cretsu on 4/19/16. // Copyright © 2016 Pasha Cretsu. All rights reserved. // import WatchKit import Foundation class GlanceController: WKInterfaceController { override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } }
gpl-3.0
jpedrosa/sua
Package.swift
1
143
import PackageDescription let package = Package( name: "Sua", dependencies: [ .Package(url: "../csua_module", majorVersion: 0) ] )
apache-2.0
iOSTestApps/CardsAgainst
CardsAgainst/Models/Vote.swift
3
468
// // Vote.swift // CardsAgainst // // Created by JP Simard on 11/6/14. // Copyright (c) 2014 JP Simard. All rights reserved. // import Foundation struct Vote { let votee: Player let voter: Player static func stringFromVoteCount(voteCount: Int) -> String { switch voteCount { case 0: return "no votes" case 1: return "1 vote" default: return "\(voteCount) votes" } } }
mit
RCacheaux/SafeDataSourceKit
SafeDataSourceDevelopment.playground/Contents.swift
1
38516
//: Playground - noun: a place where people can play import UIKit import XCPlayground func - (lhs: Range<Int>, rhs: Int) -> Range<Int> { if lhs.endIndex == 0 { return Range(start: 0, end: 0) } else if lhs.startIndex >= lhs.endIndex - rhs { return Range(start: lhs.startIndex, end: lhs.startIndex) } else { return Range(start: lhs.startIndex, end: lhs.endIndex.advancedBy(-rhs)) } } func + (lhs: Range<Int>, rhs: Int) -> Range<Int> { return Range(start: lhs.startIndex, end: lhs.endIndex.advancedBy(rhs)) } func add(lhs: Range<Int>, rhs: Int) -> Range<Int> { return Range(start: lhs.startIndex, end: lhs.endIndex.advancedBy(rhs)) } //func += (lhs: Range<Int>, rhs: Int) -> Range<Int> { // return Range(start: lhs.startIndex, end: lhs.endIndex.advancedBy(rhs)) //} func >> (lhs: Range<Int>, rhs: Int) -> Range<Int> { return Range(start: lhs.startIndex.advancedBy(rhs), end: lhs.endIndex.advancedBy(rhs)) } func << (lhs: Range<Int>, rhs: Int) -> Range<Int> { return Range(start: lhs.startIndex.advancedBy(-rhs), end: lhs.endIndex.advancedBy(-rhs)) } func shiftAdd(lhs: Range<Int>, rhs: Int) -> Range<Int> { return Range(start: lhs.startIndex.advancedBy(rhs), end: lhs.endIndex.advancedBy(rhs)) } func shiftRemove(lhs: Range<Int>, rhs: Int) -> Range<Int> { return Range(start: lhs.startIndex.advancedBy(-rhs), end: lhs.endIndex.advancedBy(-rhs)) } var g = 0..<0 g = g - 1 var y = 0...10 let a = y.startIndex.advancedBy(1) let b = y.endIndex.advancedBy(1) let z = Range(start: a, end: b) struct Color { let hue: CGFloat let saturation: CGFloat let brightness: CGFloat } extension UIColor { convenience init(color: Color) { self.init(hue: color.hue, saturation: color.saturation, brightness: color.brightness, alpha: 1) } } private enum DataChange<T> { // Section case AppendSection case AppendSections(Int) // Number of sections case InsertSection(Int) // Section Index case InsertSections(NSIndexSet) case DeleteSection(Int) // Section Index case DeleteSections(NSIndexSet) case DeleteLastSection case DeleteSectionsStartingAtIndex(Int) case MoveSection(Int, Int) // Item case AppendItem(T, Int) // Item, Section Index case AppendItems([T], Int) // Items, Section Index case InsertItem(T, NSIndexPath) case InsertItems([T], [NSIndexPath]) case DeleteItem(NSIndexPath) case DeleteItems([NSIndexPath]) case DeleteLastItem(Int) // Section Index case DeleteItemsStartingAtIndexPath(NSIndexPath) // Will delete all items from index path forward for section case MoveItem(NSIndexPath, NSIndexPath) } public class SafeDataSource<T>: NSObject, UICollectionViewDataSource { public typealias CellForItemAtIndexPath = (UICollectionView, T, NSIndexPath) -> UICollectionViewCell let collectionView: UICollectionView var dataSourceItems: [[T]] = [] // Only change this on main thread an coordinate it with batch insertion completion. var items: [[T]] = [] private var pendingChanges: [DataChange<T>] = [] let cellForItemAtIndexPath: CellForItemAtIndexPath let mutateDisplayQueue = SerialOperationQueue() let dataMutationDispatchQueue = dispatch_queue_create("com.rcach.safeDataSourceKit.dataMutation", DISPATCH_QUEUE_SERIAL) // New data structures for latest algorithm // TODO: Validate on insert that it does not already contain the index, // if this happens it means we are trying to delete the same item twice which is an error var adjustedIndexPathsToDelete: [Set<NSIndexPath>] = [] // TODO: This can simply be a set of all index paths to delete, they don't need to be organized by section index in a wrapping array var deletionIndexPathAdjustmentTable: [[Int]] = [] func adjustedDeletionItemIndex(pointInTimeItemIndex: Int, adjustmentTable: [Int]) -> Int { var adjustment = 0 for adj in adjustmentTable { if pointInTimeItemIndex >= adj { adjustment += 1 } } return pointInTimeItemIndex + adjustment } func adjustTableIfNecessaryWithPointInTimeDeletionItemIndex(pointInTimeItemIndex: Int, inout adjustmentTable: [Int]) { // If deleting item above previous deletes, need to offset the below adjustments -1 for (i, adj) in adjustmentTable.enumerate() { if adj > pointInTimeItemIndex { adjustmentTable[i] = adjustmentTable[i] - 1 } } // Add this point in time index to adj table adjustmentTable.append(pointInTimeItemIndex) } // !!!!!!!!! TODO: !!!!!!! Index paths passed into this method are affected by any insertions because the user of this class works off the changelist items, they don't know to filter out insertions when calling delete. func unsafeDeleteItemAtIndexPath(indexPath: NSIndexPath) -> NSIndexPath { let adjIndex = adjustedDeletionItemIndex(indexPath.item, adjustmentTable: deletionIndexPathAdjustmentTable[indexPath.section]) adjustTableIfNecessaryWithPointInTimeDeletionItemIndex(indexPath.item, adjustmentTable: &deletionIndexPathAdjustmentTable[indexPath.section]) let adjIndexPath = NSIndexPath(forItem: adjIndex, inSection: indexPath.section) adjustedIndexPathsToDelete[indexPath.section].insert(adjIndexPath) return adjIndexPath } public convenience init(items: [[T]], collectionView: UICollectionView, cellForItemAtIndexPath: CellForItemAtIndexPath) { self.init(collectionView: collectionView, cellForItemAtIndexPath: cellForItemAtIndexPath) self.dataSourceItems = items self.items = items } public init(collectionView: UICollectionView, cellForItemAtIndexPath: CellForItemAtIndexPath) { self.collectionView = collectionView self.cellForItemAtIndexPath = cellForItemAtIndexPath super.init() self.collectionView.dataSource = self } private func dequeuPendingChangesAndOnComplete(onComplete: ([DataChange<T>], [Set<NSIndexPath>]) -> Void) { // TODO: Think about taking in the queue to call the on complete closure. dispatch_async(dataMutationDispatchQueue) { let pendingChangesToDequeue = self.pendingChanges self.pendingChanges.removeAll(keepCapacity: true) let itemsToDelete = self.adjustedIndexPathsToDelete //: TODO: Figure out how to mutate arrary's set without copy on write occuring: var newEmptyItemsToDelete: [Set<NSIndexPath>] = [] for _ in self.adjustedIndexPathsToDelete { newEmptyItemsToDelete.append(Set<NSIndexPath>()) } self.adjustedIndexPathsToDelete = newEmptyItemsToDelete //: onComplete(pendingChangesToDequeue, itemsToDelete) } } func addApplyOperationIfNeeded() { if let lastOperation = self.mutateDisplayQueue.operations.last { if lastOperation.executing { let applyChangeOp = ApplyDataSourceChangeOperation(safeDataSource: self, collectionView: self.collectionView) self.mutateDisplayQueue.addOperation(applyChangeOp) } } else { let applyChangeOp = ApplyDataSourceChangeOperation(safeDataSource: self, collectionView: self.collectionView) self.mutateDisplayQueue.addOperation(applyChangeOp) } } // External Interface public func appendItem(item: T) { dispatch_async(dataMutationDispatchQueue) { // Automatically creates section 0 if it does not exist already. if self.items.count == 0 { self.unsafeAppendSectionWithItem(item) } else { // self.unsafeAppendItem(item, toSection: 0) // TODO: Remove ObjC msg_send overhead let section = 0 guard section < self.items.count else { return } // TODO: Add more of these validations let startingIndex = self.items[section].count self.pendingChanges.append(.InsertItem(item, NSIndexPath(forItem: startingIndex, inSection: section))) self.items[section].append(item) self.addApplyOperationIfNeeded() } } } public func appendItem(item: T, toSection section: Int) { dispatch_async(dataMutationDispatchQueue) { self.unsafeAppendItem(item, toSection: section) } } @nonobjc @inline(__always) func unsafeAppendItem(item: T, toSection section: Int) { guard section < self.items.count else { return } // TODO: Add more of these validations let startingIndex = self.items[section].count self.pendingChanges.append(.InsertItem(item, NSIndexPath(forItem: startingIndex, inSection: section))) self.items[section].append(item) self.addApplyOperationIfNeeded() } public func appendSectionWithItems(items: [T]) { dispatch_async(dataMutationDispatchQueue) { self.unsafeAppendSectionWithItems(items) } } @nonobjc @inline(__always) func unsafeAppendSectionWithItems(items: [T]) { let newSectionIndex = self.items.count // This must happen first. self.pendingChanges.append(.AppendSection) self.items.append([]) let indexPaths = items.enumerate().map { (index, item) -> NSIndexPath in return NSIndexPath(forItem: index, inSection: newSectionIndex) } self.pendingChanges.append(.InsertItems(items, indexPaths)) self.items[newSectionIndex] = items self.addApplyOperationIfNeeded() } @nonobjc @inline(__always) func unsafeAppendSectionWithItem(item: T) { let newSectionIndex = self.items.count // This must happen first. self.pendingChanges.append(.AppendSection) self.items.append([]) let indexPath = NSIndexPath(forItem: 0, inSection: newSectionIndex) self.pendingChanges.append(.InsertItem(item, indexPath)) self.items[newSectionIndex].append(item) self.addApplyOperationIfNeeded() } // Instead allow consumer to give you a closure that we call and provide current // data state and they can use that state to apply mutations public func insertItemWithClosure(getInsertionIndexPath: ([[T]]) -> (item: T, indexPath: NSIndexPath)?) { dispatch_async(dataMutationDispatchQueue) { guard let insertion = getInsertionIndexPath(self.items) else { return } insertion.indexPath.item self.pendingChanges.append(.InsertItem(insertion.item, insertion.indexPath)) self.items[insertion.indexPath.section].insert(insertion.item, atIndex: insertion.indexPath.item) self.addApplyOperationIfNeeded() } } public func deleteItemWithClosure(getDeletionIndexPath: ([[T]]) -> NSIndexPath?) { dispatch_async(dataMutationDispatchQueue) { guard let indexPath = getDeletionIndexPath(self.items) else { return } let adjIndexPath = self.unsafeDeleteItemAtIndexPath(indexPath) self.pendingChanges.append(.DeleteItem(indexPath)) // TODO: Also store adjIndexPath in enum? self.items[indexPath.section].removeAtIndex(indexPath.item) self.addApplyOperationIfNeeded() } } public func deleteLastItemInSection(sectionIndex: Int) { assertionFailure("deleteLastItemInSection not supported yet.") // dispatch_async(dataMutationDispatchQueue) { // if self.items[sectionIndex].count > 0 { // self.items[sectionIndex].removeLast() // self.pendingChanges.append(.DeleteLastItem(sectionIndex)) // self.addApplyOperationIfNeeded() // } // } } // TODO: Delete items in range: in section: < more performant for large deletions if they are contiguous public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSourceItems[section].count } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = cellForItemAtIndexPath(collectionView, dataSourceItems[indexPath.section][indexPath.row], indexPath) return cell } public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return dataSourceItems.count } // func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView // iOS 9+ // func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool // iOS 9+ // func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) } class SerialOperationQueue: NSOperationQueue { override init() { super.init() maxConcurrentOperationCount = 1 } override func addOperation(op: NSOperation) { if let lastOperation = self.operations.last { if !lastOperation.finished { op.addDependency(lastOperation) } } super.addOperation(op) } } public class AsyncOperation: NSOperation { private var _executing = false private var _finished = false override private(set) public var executing: Bool { get { return _executing } set { willChangeValueForKey("isExecuting") _executing = newValue didChangeValueForKey("isExecuting") } } override private(set) public var finished: Bool { get { return _finished } set { willChangeValueForKey("isFinished") _finished = newValue didChangeValueForKey("isFinished") } } override public var asynchronous: Bool { return true } override public func start() { if cancelled { finished = true return } executing = true autoreleasepool { run() } } func run() { preconditionFailure("AsyncOperation.run() abstract method must be overridden.") } func finishedExecutingOperation() { executing = false finished = true } } /* switch change { case .AppendSection: let x = 1 case .AppendSections(let numberOfSections): // Number of sections let x = 1 case .InsertSection(let sectionIndex): // Section Index let x = 1 case .InsertSections(let indexSet): let x = 1 case .DeleteSection(let sectionIndex): // Section Index let x = 1 case .DeleteSections(let indexSet): let x = 1 case .DeleteLastSection: let x = 1 case .DeleteSectionsStartingAtIndex(let sectionIndex): let x = 1 case .MoveSection(let fromSectionIndex, let toSectionIndex): // Item let x = 1 case .AppendItem(let item, let sectionIndex): // Item, Section Index let x = 1 case .AppendItems(let items, let sectionIndex): // Items, Section Index let x = 1 case .InsertItem(let item, let indexPath): let x = 1 case .InsertItems(let items, let indexPaths): let x = 1 case .DeleteItem(let indexPath): let x = 1 case .DeleteItems(let indexPaths): let x = 1 case .DeleteLastItem(let sectionIndex): // Section Index let x = 1 case .DeleteItemsStartingAtIndexPath(let indexPath): // Will delete all items from index path forward for section let x = 1 case .MoveItem(let fromIndexPath, let toIndexPath): let x = 1 } */ class ApplyDataSourceChangeOperation<T>: AsyncOperation { let safeDataSource: SafeDataSource<T> let collectionView: UICollectionView init(safeDataSource: SafeDataSource<T>, collectionView: UICollectionView) { self.safeDataSource = safeDataSource self.collectionView = collectionView super.init() } override func run() { safeDataSource.dequeuPendingChangesAndOnComplete { changes, indexPathsToDelete in dispatch_async(dispatch_get_main_queue()) { // TODO: Can make this logic more efficient: Have to process deletions first because batch // updates will also apply deletions first so, if we haven't added the item we want to delete yet, // the batch insertion will fail // Got changes, now head on over to collection view // We first apply all additions and then on complete we apply deletions and on complete of deletions we mark operation complete // TODO: Do all this math in a concurrent queue and only get on main queue once set of changes are calculated // Range of existing items in data source array before any changes applied in this op let preDeleteSectionStartingRanges = self.safeDataSource.dataSourceItems.enumerate().map { index, items in return 0..<self.safeDataSource.dataSourceItems[index].count } var sectionAdditions: [Int:Range<Int>] = [:] var sectionInsertions = self.safeDataSource.dataSourceItems.map { _ in return Set<NSIndexPath>() } var sectionDeletions = self.safeDataSource.dataSourceItems.map { _ in return Set<NSIndexPath>() } for change in changes { if case .DeleteItem(let midPointInTimeIndexPath) = change { // C: let indexWithinStartingDataSourceItems = self.itemBatchStartingIndexPath(deletionsUpToThisPoint: sectionDeletions, givenIndexPath: midPointInTimeIndexPath) if preDeleteSectionStartingRanges[midPointInTimeIndexPath.section] ~= indexWithinStartingDataSourceItems.item { // Deleting from existing items sectionDeletions[midPointInTimeIndexPath.section].insert(indexWithinStartingDataSourceItems) } // :C } else if case .DeleteItems(let midPointInTimeIndexPaths) = change { for midPointInTimeIndexPath in midPointInTimeIndexPaths { // C: let indexWithinStartingDataSourceItems = self.itemBatchStartingIndexPath(deletionsUpToThisPoint: sectionDeletions, givenIndexPath: midPointInTimeIndexPath) if preDeleteSectionStartingRanges[midPointInTimeIndexPath.section] ~= indexWithinStartingDataSourceItems.item { // Deleting from existing items sectionDeletions[midPointInTimeIndexPath.section].insert(indexWithinStartingDataSourceItems) } // :C } } } let postDeleteSectionStartingRanges = self.safeDataSource.dataSourceItems.enumerate().map { sectionIndex, items in return 0..<(self.safeDataSource.dataSourceItems[sectionIndex].count - sectionDeletions[sectionIndex].count) } var onGoingExistingDeletes: [[NSIndexPath]] = self.safeDataSource.dataSourceItems.map { _ in return [] } for change in changes { switch change { case .AppendSection: let x = 1 case .AppendSections(let numberOfSections): // Number of sections let x = 1 case .InsertSection(let sectionIndex): // Section Index let x = 1 case .InsertSections(let indexSet): let x = 1 case .DeleteSection(let sectionIndex): // Section Index let x = 1 case .DeleteSections(let indexSet): let x = 1 case .DeleteLastSection: let x = 1 case .DeleteSectionsStartingAtIndex(let sectionIndex): let x = 1 case .MoveSection(let fromSectionIndex, let toSectionIndex): let x = 1 case .AppendItem(_, let sectionIndex): // Item, Section Index let x = 1 // if sectionAdditions[sectionIndex] == nil { // let startingRange = postDeleteSectionStartingRanges[sectionIndex] // sectionAdditions[sectionIndex] = startingRange.endIndex..<startingRange.endIndex // } // if let sectionAdditionsForSection = sectionAdditions[sectionIndex] { // sectionAdditions[sectionIndex] = sectionAdditionsForSection + 1 // } case .AppendItems(let items, let sectionIndex): // Items, Section Index let x = 1 // if sectionAdditions[sectionIndex] == nil { // let startingRange = postDeleteSectionStartingRanges[sectionIndex] // sectionAdditions[sectionIndex] = startingRange.endIndex..<startingRange.endIndex // } // if let sectionAdditionsForSection = sectionAdditions[sectionIndex] { // sectionAdditions[sectionIndex] = sectionAdditionsForSection + items.count // } case .InsertItem(_, let midPointInTimeIndexPath): // TODO: What if this is an insertion into a new section? // A: let indexWithinStartingDataSourceItems = self.itemBatchStartingIndexPath(deletionsUpToThisPoint: onGoingExistingDeletes, givenIndexPath: midPointInTimeIndexPath) if preDeleteSectionStartingRanges[midPointInTimeIndexPath.section] ~= indexWithinStartingDataSourceItems.item { // Inserting into existing items // Now that we know this insertion is within existing items, its not a simple addition, so find this item's index path after all deletes applied: let allDeletions = sectionDeletions let postDeleteIndexPath = self.itemBatchStartingIndexPath(deletionsUpToThisPoint: allDeletions, givenIndexPath: midPointInTimeIndexPath) sectionInsertions[midPointInTimeIndexPath.section].insert(postDeleteIndexPath) if let sectionAdditionsForSection = sectionAdditions[midPointInTimeIndexPath.section] { sectionAdditions[midPointInTimeIndexPath.section] = sectionAdditionsForSection >> 1 } } else { // NOT inserting into existing items if sectionAdditions[midPointInTimeIndexPath.section] == nil { let startingRange = postDeleteSectionStartingRanges[midPointInTimeIndexPath.section] sectionAdditions[midPointInTimeIndexPath.section] = startingRange.endIndex..<startingRange.endIndex } if let sectionAdditionsForSection = sectionAdditions[midPointInTimeIndexPath.section] { sectionAdditions[midPointInTimeIndexPath.section] = sectionAdditionsForSection + 1 // TODO: Can we make this easier by just keeping a count of additions and take the post delete max item in each section and make that the start of the addtions range? } } // :A case .InsertItems(_, let midPointInTimeIndexPaths): for midPointInTimeIndexPath in midPointInTimeIndexPaths { // A: let indexWithinStartingDataSourceItems = self.itemBatchStartingIndexPath(deletionsUpToThisPoint: onGoingExistingDeletes, givenIndexPath: midPointInTimeIndexPath) if preDeleteSectionStartingRanges[midPointInTimeIndexPath.section] ~= indexWithinStartingDataSourceItems.item { // Inserting into existing items // Now that we know this insertion is within existing items, its not a simple addition, so find this item's index path after all deletes applied: let allDeletions = sectionDeletions let postDeleteIndexPath = self.itemBatchStartingIndexPath(deletionsUpToThisPoint: allDeletions, givenIndexPath: midPointInTimeIndexPath) sectionInsertions[midPointInTimeIndexPath.section].insert(postDeleteIndexPath) if let sectionAdditionsForSection = sectionAdditions[midPointInTimeIndexPath.section] { sectionAdditions[midPointInTimeIndexPath.section] = sectionAdditionsForSection >> 1 } } else { // NOT inserting into existing items if sectionAdditions[midPointInTimeIndexPath.section] == nil { let startingRange = postDeleteSectionStartingRanges[midPointInTimeIndexPath.section] sectionAdditions[midPointInTimeIndexPath.section] = startingRange.endIndex..<startingRange.endIndex } if let sectionAdditionsForSection = sectionAdditions[midPointInTimeIndexPath.section] { sectionAdditions[midPointInTimeIndexPath.section] = sectionAdditionsForSection + 1 // TODO: Can we make this easier by just keeping a count of additions and take the post delete max item in each section and make that the start of the addtions range? } } // :A } case .DeleteItem(let indexPath): // B: // This accounts for the fact that the index path given to us is in the context of an array with potentially deleted items. let indexWithinStartingDataSourceItems = self.itemBatchStartingIndexPath(deletionsUpToThisPoint: onGoingExistingDeletes, givenIndexPath: midPointInTimeIndexPath) if preDeleteSectionStartingRanges[indexPath.section] ~= (indexPath.item + onGoingExistingDeletes[indexPath.section].count) { // Deleting from existing items // Do nothing this deletion has already been accounted for, excpet for keeping track onGoingExistingDeletes[indexPath.section].append(indexPath) // TODO: will something reference this index path later if so be careful about index that should be shifted! } else { // NOT deleting from existing items, no deleting from datasource, items never made it to collection view no need to add these items just to delete them if let sectionAdditionsForSection = sectionAdditions[indexPath.section] { sectionAdditions[indexPath.section] = sectionAdditionsForSection - 1 // TODO: Remove addition range if range becomes 0..<0 } else { // This should never occur, this means a delete command was given for an item that hasn't been added yet. We are iterating in the changlist order. assertionFailure("Encountered an addition deletion for an item that has not been added before in the changelist order.") } } // :B case .DeleteItems(let indexPaths): for indexPath in indexPaths { // B: // This accounts for the fact that the index path given to us is in the context of an array with potentially deleted items. if preDeleteSectionStartingRanges[indexPath.section] ~= (indexPath.item + onGoingExistingDeletes[indexPath.section].count) { // Deleting from existing items // Do nothing this deletion has already been accounted for, excpet for keeping track onGoingExistingDeletes[indexPath.section].append(indexPath) } else { // NOT deleting from existing items, no deleting from datasource, items never made it to collection view no need to add these items just to delete them if let sectionAdditionsForSection = sectionAdditions[indexPath.section] { sectionAdditions[indexPath.section] = sectionAdditionsForSection - 1 // TODO: Remove addition range if range becomes 0..<0 } else { // This should never occur, this means a delete command was given for an item that hasn't been added yet. We are iterating in the changlist order. assertionFailure("Encountered an addition deletion for an item that has not been added before in the changelist order.") } } // :B } case .DeleteLastItem: // Section Index assertionFailure("Delete Last Item in Section not implemented yet.") /* if let sectionAdditionsForSection = sectionAdditions[sectionIndex] { // There are additions, just remove from there let x = 1 sectionAdditions[sectionIndex]?.startIndex sectionAdditions[sectionIndex]?.endIndex sectionAdditions[sectionIndex] = sectionAdditionsForSection - 1 if sectionAdditions[sectionIndex]!.startIndex == sectionAdditions[sectionIndex]!.endIndex { sectionAdditions[sectionIndex] = nil } } else if self.safeDataSource.dataSourceItems[sectionIndex].count > 0 { // If there are existing items in this section, remove the last one let x = 1 // Look for deletions at the end of the existing items in this section, and a let candidate = NSIndexPath(forItem: self.safeDataSource.dataSourceItems[sectionIndex].count - 1, inSection: sectionIndex) if sectionDeletions[sectionIndex].count == 0 { sectionDeletions[sectionIndex].insert(candidate) } else { var fromEnd = 1 var foundDelete = false while !foundDelete { let candidate = NSIndexPath(forItem: self.safeDataSource.dataSourceItems[sectionIndex].count - fromEnd, inSection: sectionIndex) if !sectionDeletions[sectionIndex].contains(candidate) { if sectionInsertions[sectionIndex].contains(candidate) { sectionInsertions[sectionIndex].remove(candidate) } sectionDeletions[sectionIndex].insert(candidate) sectionDeletions[sectionIndex].count // TODO: If this results in a deletion of something that is inside the insertion set of index paths, this logic should remove that index path from the insertions index path foundDelete = true } else { let x = 1 fromEnd += 1 } } } } else { print(":-/") } */ case .DeleteItemsStartingAtIndexPath: // Will delete all items from index path forward for section assertionFailure("Delete items starting at index path not implemented yet.") case .MoveItem(let fromIndexPath, let toIndexPath): // TODO: Handle if move is for item that is to be deleted. // >>>> TODO!!!!!! - the + shift should only occur for deletions with item index less than this guys let fromIndexPathInExistingItemRange = preDeleteSectionStartingRanges[fromIndexPath.section] ~= (fro mIndexPath.item + onGoingExistingDeletes[fromIndexPath.section].count) let toIndexPathInExistingItemRange = preDeleteSectionStartingRanges[toIndexPath.section] ~= (toIndexPath.item + onGoingExistingDeletes[toIndexPath.section].count) if fromIndexPathInExistingItemRange && toIndexPathInExistingItemRange { // TODO: Test for if existing with pre delete data structure and shift index paths based on ongoing existingDeletes. // is the move within existing? // then it's a move operation - Need to figure out what the real from index path and to index path are // is there a delete... // is the move going to affect any pending changes within existing items? // The move is within the postDelete existing items, just need to make a move op with theses index paths // Take into account any deletions within the existing items and shift the index paths accordingly } else if !toIndexPathInExistingItemRange && !toIndexPathInExistingItemRange { // is the move within additions? // just need to change the index paths where this will initially get inserted, no move necessary } else { // is the move across additions and existing // I THINK this is just a move operation, need to verify } let x = 1 } } // TODO: Do this with higher order functions var _newIndexPathsToAdd: [NSIndexPath] = [] for (sectionIndex, sa) in sectionAdditions { sa for a in sa { _newIndexPathsToAdd.append(NSIndexPath(forItem: a, inSection: sectionIndex)) } } for insertions in sectionInsertions { for indexPath in insertions { _newIndexPathsToAdd.append(indexPath) } } var _newIndexPathsToDelete: [NSIndexPath] = [] for deletions in sectionDeletions { for indexPath in deletions { print("Will Delete: \(indexPath.section):\(indexPath.item)") _newIndexPathsToDelete.append(indexPath) } } self.collectionView.performBatchUpdates({ // Perform changes var indexPathsToAdd: [NSIndexPath] = [] for change in changes { if case .AppendSection = change { let newSectionIndex = self.safeDataSource.dataSourceItems.count self.safeDataSource.dataSourceItems.append([]) self.collectionView.insertSections(NSIndexSet(index: newSectionIndex)) } else if case .InsertItem(let item, let indexPath) = change { print(indexPath.item) indexPathsToAdd.append(indexPath) // TODO: Validate that item's index path matches index in array below: self.safeDataSource.dataSourceItems[indexPath.section].insert(item, atIndex: indexPath.item) } else if case .InsertItems(let items, let newIndexPaths) = change { indexPathsToAdd += newIndexPaths for (index, item) in items.enumerate() { let indexPath = newIndexPaths[index] self.safeDataSource.dataSourceItems[indexPath.section].insert(item, atIndex: indexPath.item) } } else if case .DeleteItem(let indexPath) = change { self.safeDataSource.dataSourceItems[indexPath.section].removeAtIndex(indexPath.item) } else if case .DeleteLastItem(let sectionIndex) = change { if self.safeDataSource.dataSourceItems[sectionIndex].count > 0 { self.safeDataSource.dataSourceItems[sectionIndex].removeLast() } } } print("-") if _newIndexPathsToAdd.count > 0 { self.collectionView.insertItemsAtIndexPaths(_newIndexPathsToAdd) } if _newIndexPathsToDelete.count > 0 { self.collectionView.deleteItemsAtIndexPaths(_newIndexPathsToDelete) } // Plus reload operations // Plus move operations }) { completed in self.finishedExecutingOperation() } } } } @nonobjc func itemBatchStartingIndexPath(deletionsUpToThisPoint deletionsUpToThisPoint: [Set<NSIndexPath>], givenIndexPath: NSIndexPath) -> NSIndexPath { var offsetCount = 0 // TODO: Use fancy higher order funcs if possible let deletions = deletionsUpToThisPoint[givenIndexPath.section] for deletion in deletions { if deletion.item < givenIndexPath.item { // TODO: Think more about whether this should be <= offsetCount += 1 } } return NSIndexPath(forRow: givenIndexPath.item + offsetCount, inSection: givenIndexPath.section) } @nonobjc func itemBatchStartingIndexPath(deletionsUpToThisPoint deletionsUpToThisPoint: [[NSIndexPath]], givenIndexPath: NSIndexPath) -> NSIndexPath { var offsetCount = 0 // TODO: Use fancy higher order funcs if possible let deletions = deletionsUpToThisPoint[givenIndexPath.section] for deletion in deletions { if deletion.item < givenIndexPath.item { // TODO: Think more about whether this should be <= offsetCount += 1 } } return NSIndexPath(forRow: givenIndexPath.item + offsetCount, inSection: givenIndexPath.section) } } let cellForItem = { (collectionView: UICollectionView, item: Color, indexPath: NSIndexPath) -> UICollectionViewCell in let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) cell.backgroundColor = UIColor(color: item) return cell } class InteractionHandler: NSObject { let safeDataSource: SafeDataSource<Color> init(safeDataSource: SafeDataSource<Color>) { self.safeDataSource = safeDataSource super.init() } func handleTap() { safeDataSource.appendItem(Color(hue: 0.5, saturation: 1.0, brightness: 0.8)) } } let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSizeMake(10, 10) let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout) let safeDataSource = SafeDataSource<Color>(items: [[]], collectionView: collectionView, cellForItemAtIndexPath: cellForItem) collectionView.frame = CGRectMake(0, 0, 500, 1000) collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell") XCPlaygroundPage.currentPage.liveView = collectionView XCPlaygroundPage.currentPage.needsIndefiniteExecution = true let interactionHandler = InteractionHandler(safeDataSource: safeDataSource) let tgr = UITapGestureRecognizer(target: interactionHandler, action: "handleTap") collectionView.addGestureRecognizer(tgr) dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { for _ in (0...1000) { interactionHandler.handleTap() } interactionHandler.safeDataSource.insertItemWithClosure { colors in print("Insert item") if colors.count > 0 { if colors[0].count > 10 { colors[0].count - 8 let indexPath = NSIndexPath(forItem: 4, inSection: 0) indexPath.item return (Color(hue: 0.1, saturation: 1.0, brightness: 0.9), indexPath) } } return nil } for _ in (0...2) { // TODO: Try (0...1) and this will crash, support multiple consecutive deletes interactionHandler.safeDataSource.deleteItemWithClosure { colors in print("Delete item: loop") if colors.count > 0 { if colors[0].count > 10 { return NSIndexPath(forItem: colors[0].count - 2, inSection: 0) } } return nil } } interactionHandler.safeDataSource.deleteItemWithClosure { colors in print("Delete item: last") return NSIndexPath(forItem: 0, inSection: 0) } // interactionHandler.safeDataSource.deleteLastItemInSection(0) // interactionHandler.safeDataSource.deleteLastItemInSection(0) // interactionHandler.safeDataSource.deleteLastItemInSection(0) // interactionHandler.safeDataSource.deleteLastItemInSection(0) // interactionHandler.safeDataSource.deleteLastItemInSection(0) // interactionHandler.safeDataSource.deleteLastItemInSection(0) // interactionHandler.safeDataSource.deleteLastItemInSection(0) // interactionHandler.safeDataSource.deleteLastItemInSection(0) // interactionHandler.safeDataSource.deleteLastItemInSection(0) // interactionHandler.safeDataSource.deleteLastItemInSection(0) // interactionHandler.safeDataSource.deleteLastItemInSection(0) // interactionHandler.safeDataSource.deleteLastItemInSection(0) // interactionHandler.safeDataSource.deleteLastItemInSection(0) // interactionHandler.safeDataSource.deleteLastItemInSection(0) // interactionHandler.safeDataSource.deleteLastItemInSection(0) // TODO: uncomment and support this use case }
apache-2.0
realm/SwiftLint
Source/SwiftLintFramework/Rules/Lint/UnusedImportRuleExamples.swift
1
5849
struct UnusedImportRuleExamples { static let nonTriggeringExamples = [ Example(""" import Dispatch // This is used dispatchMain() """), Example(""" @testable import Dispatch dispatchMain() """), Example(""" import Foundation @objc class A {} """), Example(""" import UnknownModule func foo(error: Swift.Error) {} """), Example(""" import Foundation import ObjectiveC let 👨‍👩‍👧‍👦 = #selector(NSArray.contains(_:)) 👨‍👩‍👧‍👦 == 👨‍👩‍👧‍👦 """) ] static let triggeringExamples = [ Example(""" ↓import Dispatch struct A { static func dispatchMain() {} } A.dispatchMain() """), Example(""" ↓import Foundation // This is unused struct A { static func dispatchMain() {} } A.dispatchMain() ↓import Dispatch """), Example(""" ↓import Foundation dispatchMain() """), Example(""" ↓import Foundation // @objc class A {} """), Example(""" ↓import Foundation import UnknownModule func foo(error: Swift.Error) {} """), Example(""" ↓import Swift ↓import SwiftShims func foo(error: Swift.Error) {} """) ] static let corrections = [ Example(""" ↓import Dispatch struct A { static func dispatchMain() {} } A.dispatchMain() """): Example(""" struct A { static func dispatchMain() {} } A.dispatchMain() """), Example(""" ↓import Foundation // This is unused struct A { static func dispatchMain() {} } A.dispatchMain() ↓import Dispatch """): Example(""" struct A { static func dispatchMain() {} } A.dispatchMain() """), Example(""" ↓import Foundation dispatchMain() """): Example(""" dispatchMain() """), Example(""" ↓@testable import Foundation import Dispatch dispatchMain() """): Example(""" import Dispatch dispatchMain() """), Example(""" ↓@_exported import Foundation import Dispatch dispatchMain() """): Example(""" import Dispatch dispatchMain() """), Example(""" ↓import Foundation // @objc class A {} """): Example(""" // @objc class A {} """), Example(""" @testable import Foundation ↓import Dispatch @objc class A {} """): Example(""" @testable import Foundation @objc class A {} """), Example(""" @testable import Foundation ↓@testable import Dispatch @objc class A {} """): Example(""" @testable import Foundation @objc class A {} """), Example(""" ↓↓import Foundation typealias Foo = CFArray """, configuration: [ "require_explicit_imports": true, "allowed_transitive_imports": [ [ "module": "Foundation", "allowed_transitive_imports": ["CoreFoundation"] ] ] ], testMultiByteOffsets: false, testOnLinux: false): Example(""" import CoreFoundation typealias Foo = CFArray """), Example(""" ↓↓import Foundation typealias Foo = CFData """, configuration: [ "require_explicit_imports": true ], testMultiByteOffsets: false, testOnLinux: false): Example(""" import CoreFoundation typealias Foo = CFData """), Example(""" import Foundation typealias Foo = CFData @objc class A {} """, configuration: [ "require_explicit_imports": true, "allowed_transitive_imports": [ [ "module": "Foundation", "allowed_transitive_imports": ["CoreFoundation"] ] ] ]): Example(""" import Foundation typealias Foo = CFData @objc class A {} """), Example(""" ↓import Foundation typealias Bar = CFData @objc class A {} """, configuration: [ "require_explicit_imports": true ], testMultiByteOffsets: false, testOnLinux: false): Example(""" import CoreFoundation import Foundation typealias Bar = CFData @objc class A {} """), Example(""" import Foundation func bar() {} """, configuration: [ "always_keep_imports": ["Foundation"] ]): Example(""" import Foundation func bar() {} """), Example(""" ↓import Swift ↓import SwiftShims func foo(error: Swift.Error) {} """): Example(""" func foo(error: Swift.Error) {} """) ] }
mit
kostiakoval/SpeedLog
Tests/SpeedLogTests.swift
1
1676
// // SpeedLogTests.swift // SpeedLogTests // // Created by Kostiantyn Koval on 20/11/15. // Copyright © 2015 Kostiantyn Koval. All rights reserved. // import XCTest @testable import SpeedLog class SpeedLogTests: XCTestCase { func testEmptyPrefix() { let prefix = logForMode(.None) XCTAssertEqual(prefix, "") } func testFilePrefix() { let prefix = logForMode(.FileName) XCTAssertEqual(prefix, "File.: ") //FIXME: remove "." from string } func testFuncPrefix() { let prefix = logForMode(.FuncName) XCTAssertEqual(prefix, "FuncA: ") } func testLinePrefix() { let prefix = logForMode(.Line) XCTAssertEqual(prefix, "[10]: ") } func testDatePrefix() { let prefix = logForMode(.Date) XCTAssertEqual(prefix, "2015-01-10 06:44:43.060: ") } func testFullCodeLocationPrefix() { let prefix = logForMode(.FullCodeLocation) XCTAssertEqual(prefix, "File.FuncA[10]: ") } func testAllOptionsPrefix() { let prefix = logForMode(.AllOptions) XCTAssertEqual(prefix, "2015-01-10 06:44:43.060 File.FuncA[10]: ") //FIXME: add space between date and file } } // MARK: - Helpers extension SpeedLogTests { func logForMode(_ mode: LogMode) -> String { SpeedLog.mode = mode return SpeedLog.modePrefix(date, file:"File", function: "FuncA", line: 10) } var date: Date { var components = DateComponents() components.year = 2015 components.month = 1 components.day = 10 components.hour = 6 components.minute = 44 components.second = 43 components.nanosecond = 60000000 //100000 NSEC_PER_SEC return Calendar.current.date(from: components)! } }
mit
lvsti/Ilion
Ilion/StringsFileParser.swift
1
4098
// // StringsFileParser.swift // Ilion // // Created by Tamas Lustyik on 2017. 05. 19.. // Copyright © 2017. Tamas Lustyik. All rights reserved. // import Foundation struct StringsFileEntry { let keyRange: NSRange let valueRange: NSRange let commentRange: NSRange? } struct StringsFile { let content: NSString let encoding: String.Encoding let entries: [LocKey: StringsFileEntry] func value(for key: LocKey) -> String? { guard let valueRange = entries[key]?.valueRange else { return nil } return content.substring(with: valueRange) } func comment(for key: LocKey) -> String? { guard let commentRange = entries[key]?.commentRange else { return nil } return content.substring(with: commentRange) } } class StringsFileParser { private static let stringsRegex: NSRegularExpression = { let comment = "(\\/\\*(?:[^*]|[\\r\\n]|(?:\\*+(?:[^*\\/]|[\\r\\n])))*\\*+\\/.*|\\/\\/.*)?" let lineBreak = "[\\r\\n][\\t ]*" let key = "\"((?:.|[\\r\\n])+?)(?<!\\\\)\"" let assignment = "\\s*=\\s*" let value = "\"((?:.|[\\r\\n])*?)(?<!\\\\)\"" let trailing = "\\s*;" return try! NSRegularExpression(pattern: comment + lineBreak + key + assignment + value + trailing, options: []) }() func readStringsFile(at path: String) -> StringsFile? { var encoding: String.Encoding = .utf8 guard let content = try? String(contentsOfFile: path, usedEncoding: &encoding) else { return nil } var entries: [LocKey: StringsFileEntry] = [:] let matches = StringsFileParser.stringsRegex.matches(in: content, options: [], range: NSRange(location: 0, length: content.length)) for match in matches { let commentRange: NSRange? let range = match.range(at: 1) if range.location != NSNotFound { let rawComment = (content as NSString).substring(with: range) let slackChars = CharacterSet(charactersIn: "/*").union(.whitespaces) let comment = rawComment.trimmingCharacters(in: slackChars) if !comment.isEmpty { commentRange = NSRange(location: range.location + (rawComment as NSString).range(of: comment).location, length: comment.length) } else { commentRange = nil } } else { commentRange = nil } let entry = StringsFileEntry(keyRange: match.range(at: 2), valueRange: match.range(at: 3), commentRange: commentRange) let key = (content as NSString).substring(with: entry.keyRange) entries[key] = entry } return StringsFile(content: content as NSString, encoding: encoding, entries: entries) } func readStringsDictFile(at path: String) -> [String: LocalizedFormat] { guard let stringsDict = NSDictionary(contentsOfFile: path) as? [String: Any] else { return [:] } let formatPairs: [(String, LocalizedFormat)]? = try? stringsDict .map { (key, value) in guard let config = value as? [String: Any], let format = try? LocalizedFormat(config: config) else { throw StringsDictParseError.invalidFormat } return (key, format) } if let formatPairs = formatPairs { return Dictionary(pairs: formatPairs) } return [:] } }
mit
SusanDoggie/Doggie
Sources/DoggieMath/Accelerate/Move.swift
1
4202
// // Move.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. // @inlinable @inline(__always) public func Move<T>(_ count: Int, _ input: UnsafePointer<T>, _ in_stride: Int, _ output: UnsafeMutablePointer<T>, _ out_stride: Int) { var input = input var output = output for _ in 0..<count { output.pointee = input.pointee input += in_stride output += out_stride } } @inlinable @inline(__always) public func Move<T: FloatingPoint>(_ count: Int, _ real: UnsafePointer<T>, _ imag: UnsafePointer<T>, _ in_stride: Int, _ _real: UnsafeMutablePointer<T>, _ _imag: UnsafeMutablePointer<T>, _ out_stride: Int) { var real = real var imag = imag var _real = _real var _imag = _imag for _ in 0..<count { _real.pointee = real.pointee _imag.pointee = imag.pointee real += in_stride imag += in_stride _real += out_stride _imag += out_stride } } @inlinable @inline(__always) public func Swap<T>(_ count: Int, _ left: UnsafeMutablePointer<T>, _ l_stride: Int, _ right: UnsafeMutablePointer<T>, _ r_stride: Int) { var left = left var right = right for _ in 0..<count { (left.pointee, right.pointee) = (right.pointee, left.pointee) left += l_stride right += r_stride } } @inlinable @inline(__always) public func Swap<T: FloatingPoint>(_ count: Int, _ lreal: UnsafeMutablePointer<T>, _ limag: UnsafeMutablePointer<T>, _ l_stride: Int, _ rreal: UnsafeMutablePointer<T>, _ rimag: UnsafeMutablePointer<T>, _ r_stride: Int) { var lreal = lreal var limag = limag var rreal = rreal var rimag = rimag for _ in 0..<count { (lreal.pointee, rreal.pointee) = (rreal.pointee, lreal.pointee) (limag.pointee, rimag.pointee) = (rimag.pointee, limag.pointee) lreal += l_stride limag += l_stride rreal += r_stride rimag += r_stride } } @inlinable @inline(__always) public func Transpose<T>(_ column: Int, _ row: Int, _ input: UnsafePointer<T>, _ in_stride: Int, _ output: UnsafeMutablePointer<T>, _ out_stride: Int) { var input = input var output = output let _in_stride = in_stride * column let _out_stride = out_stride * row for _ in 0..<column { Move(row, input, _in_stride, output, out_stride) input += in_stride output += _out_stride } } @inlinable @inline(__always) public func Transpose<T: FloatingPoint>(_ column: Int, _ row: Int, _ real: UnsafePointer<T>, _ imag: UnsafePointer<T>, _ in_stride: Int, _ _real: UnsafeMutablePointer<T>, _ _imag: UnsafeMutablePointer<T>, _ out_stride: Int) { var real = real var imag = imag var _real = _real var _imag = _imag let _in_stride = in_stride * column let _out_stride = out_stride * row for _ in 0..<column { Move(row, real, imag, _in_stride, _real, _imag, out_stride) real += in_stride imag += in_stride _real += _out_stride _imag += _out_stride } }
mit
navermaps/maps.ios
NMapSampleSwift/NMapSampleSwift/ReverseGeocoderViewController.swift
1
5313
// // GeocoderViewController.swift // NMapSampleSwift // // Created by Junggyun Ahn on 2016. 11. 15.. // Copyright © 2016년 Naver. All rights reserved. // import UIKit class ReverseGeocoderViewController: UIViewController, NMapViewDelegate, NMapPOIdataOverlayDelegate, MMapReverseGeocoderDelegate { var mapView: NMapView? override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.isTranslucent = false mapView = NMapView(frame: self.view.frame) if let mapView = mapView { // set the delegate for map view mapView.delegate = self mapView.reverseGeocoderDelegate = self // set the application api key for Open MapViewer Library mapView.setClientId("YOUR CLIENT ID") mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(mapView) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() mapView?.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) mapView?.viewWillAppear() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) mapView?.viewDidAppear() requestAddressByCoordination(NGeoPoint(longitude: 126.978371, latitude: 37.5666091)) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) mapView?.viewWillDisappear() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) mapView?.viewDidDisappear() } // MARK: - NMapViewDelegate Methods open func onMapView(_ mapView: NMapView!, initHandler error: NMapError!) { if (error == nil) { // success // set map center and level mapView.setMapCenter(NGeoPoint(longitude:126.978371, latitude:37.5666091), atLevel:11) // set for retina display mapView.setMapEnlarged(true, mapHD: true) // set map mode : vector/satelite/hybrid mapView.mapViewMode = .vector } else { // fail print("onMapView:initHandler: \(error.description)") } } open func onMapView(_ mapView: NMapView!, touchesEnded touches: Set<AnyHashable>!, with event: UIEvent!) { if let touch = event.allTouches?.first { // Get the specific point that was touched let scrPoint = touch.location(in: mapView) print("scrPoint: \(scrPoint)") print("to: \(mapView.fromPoint(scrPoint))") requestAddressByCoordination(mapView.fromPoint(scrPoint)) } } // MARK: - NMapPOIdataOverlayDelegate Methods open func onMapOverlay(_ poiDataOverlay: NMapPOIdataOverlay!, imageForOverlayItem poiItem: NMapPOIitem!, selected: Bool) -> UIImage! { return NMapViewResources.imageWithType(poiItem.poiFlagType, selected: selected); } open func onMapOverlay(_ poiDataOverlay: NMapPOIdataOverlay!, anchorPointWithType poiFlagType: NMapPOIflagType) -> CGPoint { return NMapViewResources.anchorPoint(withType: poiFlagType) } open func onMapOverlay(_ poiDataOverlay: NMapPOIdataOverlay!, calloutOffsetWithType poiFlagType: NMapPOIflagType) -> CGPoint { return CGPoint.zero } open func onMapOverlay(_ poiDataOverlay: NMapPOIdataOverlay!, imageForCalloutOverlayItem poiItem: NMapPOIitem!, constraintSize: CGSize, selected: Bool, imageForCalloutRightAccessory: UIImage!, calloutPosition: UnsafeMutablePointer<CGPoint>!, calloutHit calloutHitRect: UnsafeMutablePointer<CGRect>!) -> UIImage! { return nil } // MARK: - MMapReverseGeocoderDelegate Methods open func location(_ location: NGeoPoint, didFind placemark: NMapPlacemark!) { let address = placemark.address self.title = address let alert = UIAlertController(title: "ReverseGeocoder", message: address, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } open func location(_ location: NGeoPoint, didFailWithError error: NMapError!) { print("location:(\(location.longitude), \(location.latitude)) didFailWithError: \(error.description)") } // MARK: - func requestAddressByCoordination(_ point: NGeoPoint) { mapView?.findPlacemark(atLocation: point) setMarker(point) } let UserFlagType: NMapPOIflagType = NMapPOIflagTypeReserved + 1 func setMarker(_ point: NGeoPoint) { clearOverlay() if let mapOverlayManager = mapView?.mapOverlayManager { // create POI data overlay if let poiDataOverlay = mapOverlayManager.newPOIdataOverlay() { poiDataOverlay.initPOIdata(1) poiDataOverlay.addPOIitem(atLocation: point, title: "마커 1", type: UserFlagType, iconIndex: 0, with: nil) poiDataOverlay.endPOIdata() } } } func clearOverlay() { if let mapOverlayManager = mapView?.mapOverlayManager { mapOverlayManager.clearOverlay() } } }
apache-2.0
ubi-naist/SenStick
ios/Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/DFUServiceInitiator.swift
4
12696
/* * Copyright (c) 2016, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder 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 CoreBluetooth /** The DFUServiceInitiator object should be used to send a firmware update to a remote BLE target compatible with the Nordic Semiconductor's DFU (Device Firmware Update). A `delegate`, `progressDelegate` and `logger` may be specified in order to receive status information. */ @objc public class DFUServiceInitiator : NSObject { //MARK: - Internal variables internal let centralManager : CBCentralManager internal let target : CBPeripheral internal var file : DFUFirmware? //MARK: - Public variables /** The service delegate is an object that will be notified about state changes of the DFU Service. Setting it is optional but recommended. */ public weak var delegate: DFUServiceDelegate? /** An optional progress delegate will be called only during upload. It notifies about current upload percentage and speed. */ public weak var progressDelegate: DFUProgressDelegate? /** The logger is an object that should print given messages to the user. It is optional. */ public weak var logger: LoggerDelegate? /** The selector object is used when the device needs to disconnect and start advertising with a different address to avodi caching problems, for example after switching to the Bootloader mode, or during sending a firmware containing a Softdevice (or Softdevice and Bootloader) and the Application. After flashing the first part (containing the Softdevice), the device restarts in the DFU Bootloader mode and may (since SDK 8.0.0) start advertising with an address incremented by 1. The peripheral specified in the `init` may no longer be used as there is no device advertising with its address. The DFU Service will scan for a new device and connect to the first device returned by the selector. The default selecter returns the first device with the required DFU Service UUID in the advertising packet (Secure or Legacy DFU Service UUID). Ignore this property if not updating Softdevice and Application from one ZIP file or your */ public var peripheralSelector: DFUPeripheralSelectorDelegate /** The number of packets of firmware data to be received by the DFU target before sending a new Packet Receipt Notification. If this value is 0, the packet receipt notification will be disabled by the DFU target. Default value is 12. Higher values (~20+), or disabling it, may speed up the upload process, but also cause a buffer overflow and hang the Bluetooth adapter. Maximum verified values were 29 for iPhone 6 Plus or 22 for iPhone 7, both iOS 10.1. */ public var packetReceiptNotificationParameter: UInt16 = 12 /** **Legacy DFU only.** Setting this property to true will prevent from jumping to the DFU Bootloader mode in case there is no DFU Version characteristic. Use it if the DFU operation can be handled by your device running in the application mode. If the DFU Version characteristic exists, the information whether to begin DFU operation, or jump to bootloader, is taken from the characteristic's value. The value returned equal to 0x0100 (read as: minor=1, major=0, or version 0.1) means that the device is in the application mode and buttonless jump to DFU Bootloader is supported. Currently, the following values of the DFU Version characteristic are supported: **No DFU Version characteristic** - one of the first implementations of DFU Service. The device may support only Application update (version from SDK 4.3.0), may support Soft Device, Bootloader and Application update but without buttonless jump to bootloader (SDK 6.0.0) or with buttonless jump (SDK 6.1.0). The DFU Library determines whether the device is in application mode or in DFU Bootloader mode by counting number of services: if no DFU Service found - device is in app mode and does not support buttonless jump, if the DFU Service is the only service found (except General Access and General Attribute services) - it assumes it is in DFU Bootloader mode and may start DFU immediately, if there is at least one service except DFU Service - the device is in application mode and supports buttonless jump. In the lase case, you want to perform DFU operation without jumping - call the setForceDfu(force:Bool) method with parameter equal to true. **0.1** - Device is in a mode that supports buttonless jump to the DFU Bootloader **0.5** - Device can handle DFU operation. Extended Init packet is required. Bond information is lost in the bootloader mode and after updating an app. Released in SDK 7.0.0. **0.6** - Bond information is kept in bootloader mode and may be kept after updating application (DFU Bootloader must be configured to preserve the bond information). **0.7** - The SHA-256 firmware hash is used in the Extended Init Packet instead of CRC-16. This feature is transparent for the DFU Service. **0.8** - The Extended Init Packet is signed using the private key. The bootloader, using the public key, is able to verify the content. Released in SDK 9.0.0 as experimental feature. Caution! The firmware type (Application, Bootloader, SoftDevice or SoftDevice+Bootloader) is not encrypted as it is not a part of the Extended Init Packet. A change in the protocol will be required to fix this issue. By default the DFU Library will try to switch the device to the DFU Bootloader mode if it finds more services then one (DFU Service). It assumes it is already in the bootloader mode if the only service found is the DFU Service. Setting the forceDfu to true (YES) will prevent from jumping in these both cases. */ public var forceDfu = false /** Set this flag to true to enable experimental buttonless feature in Secure DFU. When the experimental Buttonless DFU Service is found on a device, the service will use it to switch the device to the bootloader mode, connect to it in that mode and proceed with DFU. **Please, read the information below before setting it to true.** In the SDK 12.x the Buttonless DFU feature for Secure DFU was experimental. It is NOT recommended to use it: it was not properly tested, had implementation bugs (e.g. https://devzone.nordicsemi.com/question/100609/sdk-12-bootloader-erased-after-programming/) and does not required encryption and therefore may lead to DOS attack (anyone can use it to switch the device to bootloader mode). However, as there is no other way to trigger bootloader mode on devices without a button, this DFU Library supports this service, but the feature must be explicitly enabled here. Be aware, that setting this flag to false will no protect your devices from this kind of attacks, as an attacker may use another app for that purpose. To be sure your device is secure remove this experimental service from your device. Spec: Buttonless DFU Service UUID: 8E400001-F315-4F60-9FB8-838830DAEA50 Buttonless DFU characteristic UUID: 8E400001-F315-4F60-9FB8-838830DAEA50 (the same) Enter Bootloader Op Code: 0x01 Correct return value: 0x20-01-01 , where: 0x20 - Response Op Code 0x01 - Request Code 0x01 - Success The device should disconnect and restart in DFU mode after sending the notification. In SDK 13 this issue will be fixed by a proper implementation (bonding required, passing bond information to the bootloader, encryption, well tested). It is recommended to use this new service when SDK 13 (or later) is out. TODO: fix the docs when SDK 13 is out. */ public var enableUnsafeExperimentalButtonlessServiceInSecureDfu = false //MARK: - Public API /** Creates the DFUServiceInitializer that will allow to send an update to the given peripheral. The peripheral should be disconnected prior to calling start() method. The DFU service will automatically connect to the device, check if it has required DFU service (return a delegate callback if does not have such), jump to the DFU Bootloader mode if necessary and perform the DFU. Proper delegate methods will be called during the process. - parameter centralManager: manager that will be used to connect to the peripheral - parameter target: the DFU target peripheral - returns: the initiator instance - seeAlso: peripheralSelector property - a selector used when scanning for a device in DFU Bootloader mode in case you want to update a Softdevice and Application from a single ZIP Distribution Packet. */ public init(centralManager: CBCentralManager, target: CBPeripheral) { self.centralManager = centralManager // Just to be sure that manager is not scanning self.centralManager.stopScan() self.target = target // Default peripheral selector will choose the service UUID as a filter self.peripheralSelector = DFUPeripheralSelector() super.init() } /** Sets the file with the firmware. The file must be specified before calling `start()` method, and must not be nil. - parameter file: The firmware wrapper object - returns: the initiator instance to allow chain use */ public func with(firmware file: DFUFirmware) -> DFUServiceInitiator { self.file = file return self } /** Starts sending the specified firmware to the DFU target. When started, the service will automatically connect to the target, switch to DFU Bootloader mode (if necessary), and send all the content of the specified firmware file in one or two connections. Two connections will be used if a ZIP file contains a Soft Device and/or Bootloader and an Application. First the Soft Device and/or Bootloader will be transferred, then the service will disconnect, reconnect to the (new) Bootloader again and send the Application (unless the target supports receiving all files in a single connection). The current version of the DFU Bootloader, due to memory limitations, may receive together only a Softdevice and Bootloader. - returns: A DFUServiceController object that can be used to control the DFU operation. */ public func start() -> DFUServiceController? { // The firmware file must be specified before calling `start()` if file == nil { delegate?.dfuError(.fileNotSpecified, didOccurWithMessage: "Firmare not specified") return nil } let controller = DFUServiceController() let selector = DFUServiceSelector(initiator: self, controller: controller) controller.executor = selector selector.start() return controller } }
mit
SusanDoggie/Doggie
Sources/DoggieGraphics/ApplePlatform/Graphic/CGShading.swift
1
5273
// // CGShading.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. // #if canImport(CoreGraphics) public func CGFunctionCreate( version: UInt32, domainDimension: Int, domain: UnsafePointer<CGFloat>?, rangeDimension: Int, range: UnsafePointer<CGFloat>?, callbacks: @escaping (UnsafePointer<CGFloat>, UnsafeMutablePointer<CGFloat>) -> Void ) -> CGFunction? { typealias CGFunctionCallback = (UnsafePointer<CGFloat>, UnsafeMutablePointer<CGFloat>) -> Void let info = UnsafeMutablePointer<CGFunctionCallback>.allocate(capacity: 1) info.initialize(to: callbacks) let callback = CGFunctionCallbacks(version: version, evaluate: { (info, inputs, ouputs) in guard let callbacks = info?.assumingMemoryBound(to: CGFunctionCallback.self).pointee else { return } callbacks(inputs, ouputs) }, releaseInfo: { info in guard let info = info?.assumingMemoryBound(to: CGFunctionCallback.self) else { return } info.deinitialize(count: 1) info.deallocate() }) return CGFunction(info: info, domainDimension: domainDimension, domain: domain, rangeDimension: rangeDimension, range: range, callbacks: [callback]) } public func CGShadingCreate(axialSpace space: CGColorSpace, start: CGPoint, end: CGPoint, extendStart: Bool, extendEnd: Bool, callbacks: @escaping (CGFloat, UnsafeMutableBufferPointer<CGFloat>) -> Void) -> CGShading? { let rangeDimension = space.numberOfComponents + 1 guard let function = CGFunctionCreate( version: 0, domainDimension: 1, domain: [0, 1], rangeDimension: rangeDimension, range: nil, callbacks: { callbacks($0.pointee, UnsafeMutableBufferPointer(start: $1, count: rangeDimension)) } ) else { return nil } return CGShading(axialSpace: space, start: start, end: end, function: function, extendStart: extendStart, extendEnd: extendEnd) } public func CGShadingCreate(radialSpace space: CGColorSpace, start: CGPoint, startRadius: CGFloat, end: CGPoint, endRadius: CGFloat, extendStart: Bool, extendEnd: Bool, callbacks: @escaping (CGFloat, UnsafeMutableBufferPointer<CGFloat>) -> Void) -> CGShading? { let rangeDimension = space.numberOfComponents + 1 guard let function = CGFunctionCreate( version: 0, domainDimension: 1, domain: [0, 1], rangeDimension: rangeDimension, range: nil, callbacks: { callbacks($0.pointee, UnsafeMutableBufferPointer(start: $1, count: rangeDimension)) } ) else { return nil } return CGShading(radialSpace: space, start: start, startRadius: startRadius, end: end, endRadius: endRadius, function: function, extendStart: extendStart, extendEnd: extendEnd) } extension CGContext { public func drawLinearGradient(colorSpace: CGColorSpace, start: CGPoint, end: CGPoint, options: CGGradientDrawingOptions, callbacks: @escaping (CGFloat, UnsafeMutableBufferPointer<CGFloat>) -> Void) { guard let shading = CGShadingCreate( axialSpace: colorSpace, start: start, end: end, extendStart: options.contains(.drawsBeforeStartLocation), extendEnd: options.contains(.drawsAfterEndLocation), callbacks: callbacks ) else { return } self.drawShading(shading) } public func drawRadialGradient(colorSpace: CGColorSpace, start: CGPoint, startRadius: CGFloat, end: CGPoint, endRadius: CGFloat, options: CGGradientDrawingOptions, callbacks: @escaping (CGFloat, UnsafeMutableBufferPointer<CGFloat>) -> Void) { guard let shading = CGShadingCreate( radialSpace: colorSpace, start: start, startRadius: startRadius, end: end, endRadius: endRadius, extendStart: options.contains(.drawsBeforeStartLocation), extendEnd: options.contains(.drawsAfterEndLocation), callbacks: callbacks ) else { return } self.drawShading(shading) } } #endif
mit
gabriel-kozma/swift-mask-textfield
Demo/SwiftMaskTextFieldDemo/AppDelegate.swift
1
2189
// // AppDelegate.swift // SwiftMaskTextFieldDemo // // Created by Telematics on 12/28/16. // Copyright © 2016 GabrielMackoz. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
itsthejb/Xcode-Templates
File Templates/Scaffolding/Swift Extension.xctemplate/Extension/___FILEBASENAME___.swift
1
193
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ // import UIKit extension ___VARIABLE_categoryClass:identifier___ { }
mit
natestedman/LayoutModules
LayoutModules/LayoutModuleType.swift
1
6266
// LayoutModules // Written in 2015 by Nate Stedman <nate@natestedman.com> // // To the extent possible under law, the author(s) have dedicated all copyright and // related and neighboring rights to this software to the public domain worldwide. // This software is distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with // this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. import UIKit /// A base type for layout modules. public protocol LayoutModuleType { // MARK: - Layout /** Performs layout for a section. - parameter attributes: The array of attributes to update. - parameter origin: The origin of the module. - parameter majorAxis: The major axis for the layout. - parameter minorDimension: The minor, or non-scrolling, dimension of the module. - returns: A layout result for the section, including the layout attributes for each item, and the new initial major direction offset for the next section. */ func layoutAttributesWith(count count: Int, origin: Point, majorAxis: Axis, minorDimension: CGFloat) -> LayoutResult // MARK: - Initial & Final Layout Attributes /** Provides the initial layout attributes for an appearing item. - parameter indexPath: The index path of the appearing item. - parameter attributes: The layout attributes of the appearing item. - returns: A layout attributes value, or `nil`. */ func initialLayoutAttributesFor(indexPath: NSIndexPath, attributes: LayoutAttributes) -> LayoutAttributes? /** Provides the final layout attributes for an disappearing item. - parameter indexPath: The index path of the disappearing item. - parameter attributes: The layout attributes of the disappearing item. - returns: A layout attributes value, or `nil`. */ func finalLayoutAttributesFor(indexPath: NSIndexPath, attributes: LayoutAttributes) -> LayoutAttributes? } extension LayoutModuleType { // MARK: - Default Implementations for Initial & Final Layout Attributes /// The default implementation returns `nil`. public func initialLayoutAttributesFor(indexPath: NSIndexPath, attributes: LayoutAttributes) -> LayoutAttributes? { return nil } /// The default implementation returns `nil`. public func finalLayoutAttributesFor(indexPath: NSIndexPath, attributes: LayoutAttributes) -> LayoutAttributes? { return nil } } extension LayoutModuleType { // MARK: - Adding Initial & Final Layout Attributes /** Creates a layout module that overrides the initial transition behavior of the receiver. - parameter transition: A function that produces initial layout attributes. */ public func withInitialTransition(transition: LayoutModule.TransitionLayout) -> LayoutModule { return LayoutModule( layout: layoutAttributesWith, initialLayout: transition, finalLayout: finalLayoutAttributesFor ) } /** Creates a layout module that overrides the final transition behavior of the receiver. - parameter transition: A function that produces final layout attributes. */ public func withFinalTransition(transition: LayoutModule.TransitionLayout) -> LayoutModule { return LayoutModule( layout: layoutAttributesWith, initialLayout: initialLayoutAttributesFor, finalLayout: transition ) } } extension LayoutModuleType { // MARK: - Insets /** Produces a new layout module by insetting the layout module. All parameters are optional. If a parameter is omitted, that edge will not be inset. - parameter minMajor: Insets from the minimum end of the major axis. - parameter maxMajor: Insets from the maximum end of the major axis. - parameter minMinor: Insets from the minimum end of the minor axis. - parameter maxMinor: Insets from the maximum end of the minor axis. - returns: A new layout module, derived from the module this function was called on. */ public func inset(minMajor minMajor: CGFloat = 0, maxMajor: CGFloat = 0, minMinor: CGFloat = 0, maxMinor: CGFloat = 0) -> LayoutModule { return LayoutModule { count, origin, majorAxis, minorDimension in let insetOrigin = Point(major: origin.major + minMajor, minor: origin.minor + minMinor) let insetMinorDimension = minorDimension - minMinor - maxMinor let result = self.layoutAttributesWith( count: count, origin: insetOrigin, majorAxis: majorAxis, minorDimension: insetMinorDimension ) return LayoutResult(layoutAttributes: result.layoutAttributes, finalOffset: result.finalOffset + maxMajor) } } /** Produces a new layout module by insetting the layout module equally in all directions. - parameter inset: The amount to inset. - returns: A new layout module, derived from the module this function was called on. */ public func inset(inset: CGFloat) -> LayoutModule { return self.inset(minMajor: inset, maxMajor: inset, minMinor: inset, maxMinor: inset) } } extension LayoutModuleType { // MARK: - Transforms /** Produces a new layout module by translating the layout module. - parameter major: The major direction translation. - parameter minor: The minor direction translation. - returns: A new layout module, derived from the module this function was called on. */ public func translate(major major: CGFloat = 0, minor: CGFloat = 0) -> LayoutModule { return LayoutModule { count, origin, majorAxis, minorDimension in self.layoutAttributesWith( count: count, origin: Point(major: origin.major + major, minor: origin.minor + minor), majorAxis: majorAxis, minorDimension: minorDimension ) } } }
cc0-1.0
doronkatz/firefox-ios
Sync/SyncStateMachine.swift
2
39729
/* 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 Account import XCGLogger import Deferred private let log = Logger.syncLogger private let StorageVersionCurrent = 5 // Names of collections for which a synchronizer is implemented locally. private let LocalEngines: [String] = [ "bookmarks", "clients", "history", "passwords", "tabs", ] // Names of collections which will appear in a default meta/global produced locally. // Map collection name to engine version. See http://docs.services.mozilla.com/sync/objectformats.html. private let DefaultEngines: [String: Int] = [ "bookmarks": BookmarksStorageVersion, "clients": ClientsStorageVersion, "history": HistoryStorageVersion, "passwords": PasswordsStorageVersion, "tabs": TabsStorageVersion, // We opt-in to syncing collections we don't know about, since no client offers to sync non-enabled, // non-declined engines yet. See Bug 969669. "forms": 1, "addons": 1, "prefs": 2, ] // Names of collections which will appear as declined in a default // meta/global produced locally. private let DefaultDeclined: [String] = [String]() // public for testing. public func createMetaGlobalWithEngineConfiguration(_ engineConfiguration: EngineConfiguration) -> MetaGlobal { var engines: [String: EngineMeta] = [:] for engine in engineConfiguration.enabled { // We take this device's version, or, if we don't know the correct version, 0. Another client should recognize // the engine, see an old version, wipe and start again. // TODO: this client does not yet do this wipe-and-update itself! let version = DefaultEngines[engine] ?? 0 engines[engine] = EngineMeta(version: version, syncID: Bytes.generateGUID()) } return MetaGlobal(syncID: Bytes.generateGUID(), storageVersion: StorageVersionCurrent, engines: engines, declined: engineConfiguration.declined) } public func createMetaGlobal() -> MetaGlobal { let engineConfiguration = EngineConfiguration(enabled: Array(DefaultEngines.keys), declined: DefaultDeclined) return createMetaGlobalWithEngineConfiguration(engineConfiguration) } public typealias TokenSource = () -> Deferred<Maybe<TokenServerToken>> public typealias ReadyDeferred = Deferred<Maybe<Ready>> // See docs in docs/sync.md. // You might be wondering why this doesn't have a Sync15StorageClient like FxALoginStateMachine // does. Well, such a client is pinned to a particular server, and this state machine must // acknowledge that a Sync client occasionally must migrate between two servers, preserving // some state from the last. // The resultant 'Ready' will be able to provide a suitably initialized storage client. open class SyncStateMachine { // The keys are used as a set, to prevent cycles in the state machine. var stateLabelsSeen = [SyncStateLabel: Bool]() var stateLabelSequence = [SyncStateLabel]() let stateLabelsAllowed: Set<SyncStateLabel> let scratchpadPrefs: Prefs /// Use this set of states to constrain the state machine to attempt the barest /// minimum to get to Ready. This is suitable for extension uses. If it is not possible, /// then no destructive or expensive actions are taken (e.g. total HTTP requests, /// duration, records processed, database writes, fsyncs, blanking any local collections) public static let OptimisticStates = Set(SyncStateLabel.optimisticValues) /// The default set of states that the state machine is allowed to use. public static let AllStates = Set(SyncStateLabel.allValues) public init(prefs: Prefs, allowingStates labels: Set<SyncStateLabel> = SyncStateMachine.AllStates) { self.scratchpadPrefs = prefs.branch("scratchpad") self.stateLabelsAllowed = labels } open class func clearStateFromPrefs(_ prefs: Prefs) { log.debug("Clearing all Sync prefs.") Scratchpad.clearFromPrefs(prefs.branch("scratchpad")) // XXX this is convoluted. prefs.clearAll() } fileprivate func advanceFromState(_ state: SyncState) -> ReadyDeferred { log.info("advanceFromState: \(state.label)") // Record visibility before taking any action. let labelAlreadySeen = self.stateLabelsSeen.updateValue(true, forKey: state.label) != nil stateLabelSequence.append(state.label) if let ready = state as? Ready { // Sweet, we made it! return deferMaybe(ready) } // Cycles are not necessarily a problem, but seeing the same (recoverable) error condition is a problem. if state is RecoverableSyncState && labelAlreadySeen { return deferMaybe(StateMachineCycleError()) } guard stateLabelsAllowed.contains(state.label) else { return deferMaybe(DisallowedStateError(state.label, allowedStates: stateLabelsAllowed)) } return state.advance() >>== self.advanceFromState } open func toReady(_ authState: SyncAuthState) -> ReadyDeferred { let token = authState.token(Date.now(), canBeExpired: false) return chainDeferred(token, f: { (token, kB) in log.debug("Got token from auth state.") if Logger.logPII { log.debug("Server is \(token.api_endpoint).") } let prior = Scratchpad.restoreFromPrefs(self.scratchpadPrefs, syncKeyBundle: KeyBundle.fromKB(kB)) if prior == nil { log.info("No persisted Sync state. Starting over.") } var scratchpad = prior ?? Scratchpad(b: KeyBundle.fromKB(kB), persistingTo: self.scratchpadPrefs) // Take the scratchpad and add the hashedUID from the token let b = Scratchpad.Builder(p: scratchpad) b.hashedUID = token.hashedFxAUID scratchpad = b.build() log.info("Advancing to InitialWithLiveToken.") let state = InitialWithLiveToken(scratchpad: scratchpad, token: token) // Start with fresh visibility data. self.stateLabelsSeen = [:] self.stateLabelSequence = [] return self.advanceFromState(state) }) } } public enum SyncStateLabel: String { case Stub = "STUB" // For 'abstract' base classes. case InitialWithExpiredToken = "initialWithExpiredToken" case InitialWithExpiredTokenAndInfo = "initialWithExpiredTokenAndInfo" case InitialWithLiveToken = "initialWithLiveToken" case InitialWithLiveTokenAndInfo = "initialWithLiveTokenAndInfo" case ResolveMetaGlobalVersion = "resolveMetaGlobalVersion" case ResolveMetaGlobalContent = "resolveMetaGlobalContent" case NeedsFreshMetaGlobal = "needsFreshMetaGlobal" case NewMetaGlobal = "newMetaGlobal" case HasMetaGlobal = "hasMetaGlobal" case NeedsFreshCryptoKeys = "needsFreshCryptoKeys" case HasFreshCryptoKeys = "hasFreshCryptoKeys" case Ready = "ready" case FreshStartRequired = "freshStartRequired" // Go around again... once only, perhaps. case ServerConfigurationRequired = "serverConfigurationRequired" case ChangedServer = "changedServer" case MissingMetaGlobal = "missingMetaGlobal" case MissingCryptoKeys = "missingCryptoKeys" case MalformedCryptoKeys = "malformedCryptoKeys" case SyncIDChanged = "syncIDChanged" case RemoteUpgradeRequired = "remoteUpgradeRequired" case ClientUpgradeRequired = "clientUpgradeRequired" static let allValues: [SyncStateLabel] = [ InitialWithExpiredToken, InitialWithExpiredTokenAndInfo, InitialWithLiveToken, InitialWithLiveTokenAndInfo, NeedsFreshMetaGlobal, ResolveMetaGlobalVersion, ResolveMetaGlobalContent, NewMetaGlobal, HasMetaGlobal, NeedsFreshCryptoKeys, HasFreshCryptoKeys, Ready, FreshStartRequired, ServerConfigurationRequired, ChangedServer, MissingMetaGlobal, MissingCryptoKeys, MalformedCryptoKeys, SyncIDChanged, RemoteUpgradeRequired, ClientUpgradeRequired, ] // This is the list of states needed to get to Ready, or failing. // This is useful in circumstances where it is important to conserve time and/or battery, and failure // to timely sync is acceptable. static let optimisticValues: [SyncStateLabel] = [ InitialWithLiveToken, InitialWithLiveTokenAndInfo, HasMetaGlobal, HasFreshCryptoKeys, Ready, ] } /** * States in this state machine all implement SyncState. * * States are either successful main-flow states, or (recoverable) error states. * Errors that aren't recoverable are simply errors. * Main-flow states flow one to one. * * (Terminal failure states might be introduced at some point.) * * Multiple error states (but typically only one) can arise from each main state transition. * For example, parsing meta/global can result in a number of different non-routine situations. * * For these reasons, and the lack of useful ADTs in Swift, we model the main flow as * the success branch of a Result, and the recovery flows as a part of the failure branch. * * We could just as easily use a ternary Either-style operator, but thanks to Swift's * optional-cast-let it's no saving to do so. * * Because of the lack of type system support, all RecoverableSyncStates must have the same * signature. That signature implies a possibly multi-state transition; individual states * will have richer type signatures. */ public protocol SyncState { var label: SyncStateLabel { get } func advance() -> Deferred<Maybe<SyncState>> } /* * Base classes to avoid repeating initializers all over the place. */ open class BaseSyncState: SyncState { open var label: SyncStateLabel { return SyncStateLabel.Stub } open let client: Sync15StorageClient! let token: TokenServerToken // Maybe expired. var scratchpad: Scratchpad // TODO: 304 for i/c. open func getInfoCollections() -> Deferred<Maybe<InfoCollections>> { return chain(self.client.getInfoCollections(), f: { return $0.value }) } public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) { self.scratchpad = scratchpad self.token = token self.client = client log.info("Inited \(self.label.rawValue)") } open func synchronizer<T: Synchronizer>(_ synchronizerClass: T.Type, delegate: SyncDelegate, prefs: Prefs) -> T { return T(scratchpad: self.scratchpad, delegate: delegate, basePrefs: prefs) } // This isn't a convenience initializer 'cos subclasses can't call convenience initializers. public init(scratchpad: Scratchpad, token: TokenServerToken) { let workQueue = DispatchQueue.global() let resultQueue = DispatchQueue.main let backoff = scratchpad.backoffStorage let client = Sync15StorageClient(token: token, workQueue: workQueue, resultQueue: resultQueue, backoff: backoff) self.scratchpad = scratchpad self.token = token self.client = client log.info("Inited \(self.label.rawValue)") } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(StubStateError()) } } open class BaseSyncStateWithInfo: BaseSyncState { open let info: InfoCollections init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.info = info super.init(client: client, scratchpad: scratchpad, token: token) } init(scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.info = info super.init(scratchpad: scratchpad, token: token) } } /* * Error types. */ public protocol SyncError: MaybeErrorType, SyncPingFailureFormattable {} extension SyncError { public var failureReasonName: SyncPingFailureReasonName { return .unexpectedError } } open class UnknownError: SyncError { open var description: String { return "Unknown error." } } open class StateMachineCycleError: SyncError { open var description: String { return "The Sync state machine encountered a cycle. This is a coding error." } } open class CouldNotFetchMetaGlobalError: SyncError { open var description: String { return "Could not fetch meta/global." } } open class CouldNotFetchKeysError: SyncError { open var description: String { return "Could not fetch crypto/keys." } } open class StubStateError: SyncError { open var description: String { return "Unexpectedly reached a stub state. This is a coding error." } } open class ClientUpgradeRequiredError: SyncError { let targetStorageVersion: Int public init(target: Int) { self.targetStorageVersion = target } open var description: String { return "Client upgrade required to work with storage version \(self.targetStorageVersion)." } } open class InvalidKeysError: SyncError { let keys: Keys public init(_ keys: Keys) { self.keys = keys } open var description: String { return "Downloaded crypto/keys, but couldn't parse them." } } open class DisallowedStateError: SyncError { let state: SyncStateLabel let allowedStates: Set<SyncStateLabel> public init(_ state: SyncStateLabel, allowedStates: Set<SyncStateLabel>) { self.state = state self.allowedStates = allowedStates } open var description: String { return "Sync state machine reached \(String(describing: state)) state, which is disallowed. Legal states are: \(String(describing: allowedStates))" } } /** * Error states. These are errors that can be recovered from by taking actions. We use RecoverableSyncState as a * sentinel: if we see the same recoverable state twice, we bail out and complain that we've seen a cycle. (Seeing * some states -- principally initial states -- twice is fine.) */ public protocol RecoverableSyncState: SyncState { } /** * Recovery: discard our local timestamps and sync states; discard caches. * Be prepared to handle a conflict between our selected engines and the new * server's meta/global; if an engine is selected locally but not declined * remotely, then we'll need to upload a new meta/global and sync that engine. */ open class ChangedServerError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.ChangedServer } let newToken: TokenServerToken let newScratchpad: Scratchpad public init(scratchpad: Scratchpad, token: TokenServerToken) { self.newToken = token self.newScratchpad = Scratchpad(b: scratchpad.syncKeyBundle, persistingTo: scratchpad.prefs) } open func advance() -> Deferred<Maybe<SyncState>> { // TODO: mutate local storage to allow for a fresh start. let state = InitialWithLiveToken(scratchpad: newScratchpad.checkpoint(), token: newToken) return deferMaybe(state) } } /** * Recovery: same as for changed server, but no need to upload a new meta/global. */ open class SyncIDChangedError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.SyncIDChanged } fileprivate let previousState: BaseSyncStateWithInfo fileprivate let newMetaGlobal: Fetched<MetaGlobal> public init(previousState: BaseSyncStateWithInfo, newMetaGlobal: Fetched<MetaGlobal>) { self.previousState = previousState self.newMetaGlobal = newMetaGlobal } open func advance() -> Deferred<Maybe<SyncState>> { // TODO: mutate local storage to allow for a fresh start. let s = self.previousState.scratchpad.evolve().setGlobal(self.newMetaGlobal).setKeys(nil).build().checkpoint() let state = HasMetaGlobal(client: self.previousState.client, scratchpad: s, token: self.previousState.token, info: self.previousState.info) return deferMaybe(state) } } /** * Recovery: configure the server. */ open class ServerConfigurationRequiredError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.ServerConfigurationRequired } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { let client = self.previousState.client! let s = self.previousState.scratchpad.evolve() .setGlobal(nil) .addLocalCommandsFromKeys(nil) .setKeys(nil) .build().checkpoint() // Upload a new meta/global ... let metaGlobal: MetaGlobal if let oldEngineConfiguration = s.engineConfiguration { metaGlobal = createMetaGlobalWithEngineConfiguration(oldEngineConfiguration) } else { metaGlobal = createMetaGlobal() } return client.uploadMetaGlobal(metaGlobal, ifUnmodifiedSince: nil) // ... and a new crypto/keys. >>> { return client.uploadCryptoKeys(Keys.random(), withSyncKeyBundle: s.syncKeyBundle, ifUnmodifiedSince: nil) } >>> { return deferMaybe(InitialWithLiveToken(client: client, scratchpad: s, token: self.previousState.token)) } } } /** * Recovery: wipe the server (perhaps unnecessarily) and proceed to configure the server. */ open class FreshStartRequiredError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.FreshStartRequired } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { let client = self.previousState.client! return client.wipeStorage() >>> { return deferMaybe(ServerConfigurationRequiredError(previousState: self.previousState)) } } } open class MissingMetaGlobalError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.MissingMetaGlobal } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(FreshStartRequiredError(previousState: self.previousState)) } } open class MissingCryptoKeysError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.MissingCryptoKeys } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(FreshStartRequiredError(previousState: self.previousState)) } } open class RemoteUpgradeRequired: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.RemoteUpgradeRequired } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(FreshStartRequiredError(previousState: self.previousState)) } } open class ClientUpgradeRequired: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.ClientUpgradeRequired } fileprivate let previousState: BaseSyncStateWithInfo let targetStorageVersion: Int public init(previousState: BaseSyncStateWithInfo, target: Int) { self.previousState = previousState self.targetStorageVersion = target } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(ClientUpgradeRequiredError(target: self.targetStorageVersion)) } } /* * Non-error states. */ open class InitialWithLiveToken: BaseSyncState { open override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveToken } // This looks totally redundant, but try taking it out, I dare you. public override init(scratchpad: Scratchpad, token: TokenServerToken) { super.init(scratchpad: scratchpad, token: token) } // This looks totally redundant, but try taking it out, I dare you. public override init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) { super.init(client: client, scratchpad: scratchpad, token: token) } func advanceWithInfo(_ info: InfoCollections) -> SyncState { return InitialWithLiveTokenAndInfo(scratchpad: self.scratchpad, token: self.token, info: info) } override open func advance() -> Deferred<Maybe<SyncState>> { return chain(getInfoCollections(), f: self.advanceWithInfo) } } /** * Each time we fetch a new meta/global, we need to reconcile it with our * current state. * * It might be identical to our current meta/global, in which case we can short-circuit. * * We might have no previous meta/global at all, in which case this state * simply configures local storage to be ready to sync according to the * supplied meta/global. (Not necessarily datatype elections: those will be per-device.) * * Or it might be different. In this case the previous m/g and our local user preferences * are compared to the new, resulting in some actions and a final state. * * This states are similar in purpose to GlobalSession.processMetaGlobal in Android Sync. */ open class ResolveMetaGlobalVersion: BaseSyncStateWithInfo { let fetched: Fetched<MetaGlobal> init(fetched: Fetched<MetaGlobal>, client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.fetched = fetched super.init(client: client, scratchpad: scratchpad, token: token, info: info) } open override var label: SyncStateLabel { return SyncStateLabel.ResolveMetaGlobalVersion } class func fromState(_ state: BaseSyncStateWithInfo, fetched: Fetched<MetaGlobal>) -> ResolveMetaGlobalVersion { return ResolveMetaGlobalVersion(fetched: fetched, client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } override open func advance() -> Deferred<Maybe<SyncState>> { // First: check storage version. let v = fetched.value.storageVersion if v > StorageVersionCurrent { // New storage version? Uh-oh. No recovery possible here. log.info("Client upgrade required for storage version \(v)") return deferMaybe(ClientUpgradeRequired(previousState: self, target: v)) } if v < StorageVersionCurrent { // Old storage version? Uh-oh. Wipe and upload both meta/global and crypto/keys. log.info("Server storage version \(v) is outdated.") return deferMaybe(RemoteUpgradeRequired(previousState: self)) } return deferMaybe(ResolveMetaGlobalContent.fromState(self, fetched: self.fetched)) } } open class ResolveMetaGlobalContent: BaseSyncStateWithInfo { let fetched: Fetched<MetaGlobal> init(fetched: Fetched<MetaGlobal>, client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.fetched = fetched super.init(client: client, scratchpad: scratchpad, token: token, info: info) } open override var label: SyncStateLabel { return SyncStateLabel.ResolveMetaGlobalContent } class func fromState(_ state: BaseSyncStateWithInfo, fetched: Fetched<MetaGlobal>) -> ResolveMetaGlobalContent { return ResolveMetaGlobalContent(fetched: fetched, client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } override open func advance() -> Deferred<Maybe<SyncState>> { // Check global syncID and contents. if let previous = self.scratchpad.global?.value { // Do checks that only apply when we're coming from a previous meta/global. if previous.syncID != fetched.value.syncID { log.info("Remote global sync ID has changed. Dropping keys and resetting all local collections.") let s = self.scratchpad.freshStartWithGlobal(fetched).checkpoint() return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s)) } let b = self.scratchpad.evolve() .setGlobal(fetched) // We always adopt the upstream meta/global record. let previousEngines = Set(previous.engines.keys) let remoteEngines = Set(fetched.value.engines.keys) for engine in previousEngines.subtracting(remoteEngines) { log.info("Remote meta/global disabled previously enabled engine \(engine).") b.localCommands.insert(.disableEngine(engine: engine)) } for engine in remoteEngines.subtracting(previousEngines) { log.info("Remote meta/global enabled previously disabled engine \(engine).") b.localCommands.insert(.enableEngine(engine: engine)) } for engine in remoteEngines.intersection(previousEngines) { let remoteEngine = fetched.value.engines[engine]! let previousEngine = previous.engines[engine]! if previousEngine.syncID != remoteEngine.syncID { log.info("Remote sync ID for \(engine) has changed. Resetting local.") b.localCommands.insert(.resetEngine(engine: engine)) } } let s = b.build().checkpoint() return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s)) } // No previous meta/global. Adopt the new meta/global. let s = self.scratchpad.freshStartWithGlobal(fetched).checkpoint() return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s)) } } private func processFailure(_ failure: MaybeErrorType?) -> MaybeErrorType { if let failure = failure as? ServerInBackoffError { log.warning("Server in backoff. Bailing out. \(failure.description)") return failure } // TODO: backoff etc. for all of these. if let failure = failure as? ServerError<HTTPURLResponse> { // Be passive. log.error("Server error. Bailing out. \(failure.description)") return failure } if let failure = failure as? BadRequestError<HTTPURLResponse> { // Uh oh. log.error("Bad request. Bailing out. \(failure.description)") return failure } log.error("Unexpected failure. \(failure?.description ?? "nil")") return failure ?? UnknownError() } open class InitialWithLiveTokenAndInfo: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveTokenAndInfo } // This method basically hops over HasMetaGlobal, because it's not a state // that we expect consumers to know about. override open func advance() -> Deferred<Maybe<SyncState>> { // Either m/g and c/k are in our local cache, and they're up-to-date with i/c, // or we need to fetch them. // Cached and not changed in i/c? Use that. // This check would be inaccurate if any other fields were stored in meta/; this // has been the case in the past, with the Sync 1.1 migration indicator. if let global = self.scratchpad.global { if let metaModified = self.info.modified("meta") { // We check the last time we fetched the record, and that can be // later than the collection timestamp. All we care about here is if the // server might have a newer record. if global.timestamp >= metaModified { log.debug("Cached meta/global fetched at \(global.timestamp), newer than server modified \(metaModified). Using cached meta/global.") // Strictly speaking we can avoid fetching if this condition is not true, // but if meta/ is modified for a different reason -- store timestamps // for the last collection fetch. This will do for now. return deferMaybe(HasMetaGlobal.fromState(self)) } log.info("Cached meta/global fetched at \(global.timestamp) older than server modified \(metaModified). Fetching fresh meta/global.") } else { // No known modified time for meta/. That means the server has no meta/global. // Drop our cached value and fall through; we'll try to fetch, fail, and // go through the usual failure flow. log.warning("Local meta/global fetched at \(global.timestamp) found, but no meta collection on server. Dropping cached meta/global.") // If we bail because we've been overly optimistic, then we nil out the current (broken) // meta/global. Next time around, we end up in the "No cached meta/global found" branch. self.scratchpad = self.scratchpad.evolve().setGlobal(nil).setKeys(nil).build().checkpoint() } } else { log.debug("No cached meta/global found. Fetching fresh meta/global.") } return deferMaybe(NeedsFreshMetaGlobal.fromState(self)) } } /* * We've reached NeedsFreshMetaGlobal somehow, but we haven't yet done anything about it * (e.g. fetch a new one with GET /storage/meta/global ). * * If we don't want to hit the network (e.g. from an extension), we should stop if we get to this state. */ open class NeedsFreshMetaGlobal: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.NeedsFreshMetaGlobal } class func fromState(_ state: BaseSyncStateWithInfo) -> NeedsFreshMetaGlobal { return NeedsFreshMetaGlobal(client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } override open func advance() -> Deferred<Maybe<SyncState>> { // Fetch. return self.client.getMetaGlobal().bind { result in if let resp = result.successValue { // We use the server's timestamp, rather than the record's modified field. // Either can be made to work, but the latter has suffered from bugs: see Bug 1210625. let fetched = Fetched(value: resp.value, timestamp: resp.metadata.timestampMilliseconds) return deferMaybe(ResolveMetaGlobalVersion.fromState(self, fetched: fetched)) } if let _ = result.failureValue as? NotFound<HTTPURLResponse> { // OK, this is easy. // This state is responsible for creating the new m/g, uploading it, and // restarting with a clean scratchpad. return deferMaybe(MissingMetaGlobalError(previousState: self)) } // Otherwise, we have a failure state. Die on the sword! return deferMaybe(processFailure(result.failureValue)) } } } open class HasMetaGlobal: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.HasMetaGlobal } class func fromState(_ state: BaseSyncStateWithInfo) -> HasMetaGlobal { return HasMetaGlobal(client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad) -> HasMetaGlobal { return HasMetaGlobal(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info) } override open func advance() -> Deferred<Maybe<SyncState>> { // Check if crypto/keys is fresh in the cache already. if let keys = self.scratchpad.keys, keys.value.valid { if let cryptoModified = self.info.modified("crypto") { // Both of these are server timestamps. If the record we stored was fetched after the last time the record was modified, as represented by the "crypto" entry in info/collections, and we're fetching from the // same server, then the record must be identical, and we can use it directly. If are ever additional records in the crypto collection, this will fetch keys too frequently. In that case, we should use X-I-U-S and expect some 304 responses. if keys.timestamp >= cryptoModified { log.debug("Cached keys fetched at \(keys.timestamp), newer than server modified \(cryptoModified). Using cached keys.") return deferMaybe(HasFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, collectionKeys: keys.value)) } // The server timestamp is newer, so there might be new keys. // Re-fetch keys and check to see if the actual contents differ. // If the keys are the same, we can ignore this change. If they differ, // we need to re-sync any collection whose keys just changed. log.info("Cached keys fetched at \(keys.timestamp) older than server modified \(cryptoModified). Fetching fresh keys.") return deferMaybe(NeedsFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, staleCollectionKeys: keys.value)) } else { // No known modified time for crypto/. That likely means the server has no keys. // Drop our cached value and fall through; we'll try to fetch, fail, and // go through the usual failure flow. log.warning("Local keys fetched at \(keys.timestamp) found, but no crypto collection on server. Dropping cached keys.") self.scratchpad = self.scratchpad.evolve().setKeys(nil).build().checkpoint() } } else { log.debug("No cached keys found. Fetching fresh keys.") } return deferMaybe(NeedsFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, staleCollectionKeys: nil)) } } open class NeedsFreshCryptoKeys: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.NeedsFreshCryptoKeys } let staleCollectionKeys: Keys? class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad, staleCollectionKeys: Keys?) -> NeedsFreshCryptoKeys { return NeedsFreshCryptoKeys(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info, keys: staleCollectionKeys) } public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys?) { self.staleCollectionKeys = keys super.init(client: client, scratchpad: scratchpad, token: token, info: info) } override open func advance() -> Deferred<Maybe<SyncState>> { // Fetch crypto/keys. return self.client.getCryptoKeys(self.scratchpad.syncKeyBundle, ifUnmodifiedSince: nil).bind { result in if let resp = result.successValue { let collectionKeys = Keys(payload: resp.value.payload) if !collectionKeys.valid { log.error("Unexpectedly invalid crypto/keys during a successful fetch.") return Deferred(value: Maybe(failure: InvalidKeysError(collectionKeys))) } let fetched = Fetched(value: collectionKeys, timestamp: resp.metadata.timestampMilliseconds) let s = self.scratchpad.evolve() .addLocalCommandsFromKeys(fetched) .setKeys(fetched) .build().checkpoint() return deferMaybe(HasFreshCryptoKeys.fromState(self, scratchpad: s, collectionKeys: collectionKeys)) } if let _ = result.failureValue as? NotFound<HTTPURLResponse> { // No crypto/keys? We can handle this. Wipe and upload both meta/global and crypto/keys. return deferMaybe(MissingCryptoKeysError(previousState: self)) } // Otherwise, we have a failure state. return deferMaybe(processFailure(result.failureValue)) } } } open class HasFreshCryptoKeys: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.HasFreshCryptoKeys } let collectionKeys: Keys class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad, collectionKeys: Keys) -> HasFreshCryptoKeys { return HasFreshCryptoKeys(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info, keys: collectionKeys) } public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys) { self.collectionKeys = keys super.init(client: client, scratchpad: scratchpad, token: token, info: info) } override open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(Ready(client: self.client, scratchpad: self.scratchpad, token: self.token, info: self.info, keys: self.collectionKeys)) } } public protocol EngineStateChanges { func collectionsThatNeedLocalReset() -> [String] func enginesEnabled() -> [String] func enginesDisabled() -> [String] func clearLocalCommands() } open class Ready: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.Ready } let collectionKeys: Keys public var hashedFxADeviceID: String { return (scratchpad.fxaDeviceId + token.hashedFxAUID).sha256.hexEncodedString } public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys) { self.collectionKeys = keys super.init(client: client, scratchpad: scratchpad, token: token, info: info) } } extension Ready: EngineStateChanges { public func collectionsThatNeedLocalReset() -> [String] { var needReset: Set<String> = Set() for command in self.scratchpad.localCommands { switch command { case let .resetAllEngines(except: except): needReset.formUnion(Set(LocalEngines).subtracting(except)) case let .resetEngine(engine): needReset.insert(engine) case .enableEngine, .disableEngine: break } } return Array(needReset).sorted() } public func enginesEnabled() -> [String] { var engines: Set<String> = Set() for command in self.scratchpad.localCommands { switch command { case let .enableEngine(engine): engines.insert(engine) default: break } } return Array(engines).sorted() } public func enginesDisabled() -> [String] { var engines: Set<String> = Set() for command in self.scratchpad.localCommands { switch command { case let .disableEngine(engine): engines.insert(engine) default: break } } return Array(engines).sorted() } public func clearLocalCommands() { self.scratchpad = self.scratchpad.evolve().clearLocalCommands().build().checkpoint() } }
mpl-2.0
Alecrim/AlecrimCoreData
Sources/Fetch Request Controller/FetchRequestController.swift
1
9778
// // FetchRequestController.swift // AlecrimCoreData // // Created by Vanderlei Martinelli on 11/03/18. // Copyright © 2018 Alecrim. All rights reserved. // import Foundation import CoreData // // we cannot inherit from `NSFetchedResultsController` here because the error: // "inheritance from a generic Objective-C class 'NSFetchedResultsController' must bind type parameters of // 'NSFetchedResultsController' to specific concrete types" // and // `FetchRequestController<Entity: ManagedObject>: NSFetchedResultsController<NSFetchRequestResult>` will not work for us // (curiously the "rawValue" inside our class is accepted to be `NSFetchedResultsController<Entity>`) // // MARK: - public final class FetchRequestController<Entity: ManagedObject> { // MARK: - public let fetchRequest: FetchRequest<Entity> public let rawValue: NSFetchedResultsController<Entity> internal let rawValueDelegate: FetchedResultsControllerDelegate<Entity> fileprivate let initialPredicate: Predicate<Entity>? fileprivate let initialSortDescriptors: [SortDescriptor<Entity>]? private var didPerformFetch = false // MARK: - public convenience init<Value>(query: Query<Entity>, sectionName sectionNameKeyPathClosure: @autoclosure () -> KeyPath<Entity, Value>, cacheName: String? = nil) { let sectionNameKeyPath = sectionNameKeyPathClosure().pathString self.init(fetchRequest: query.fetchRequest, context: query.context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) } public convenience init(query: Query<Entity>, sectionNameKeyPath: String? = nil, cacheName: String? = nil) { self.init(fetchRequest: query.fetchRequest, context: query.context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) } public convenience init<Value>(fetchRequest: FetchRequest<Entity>, context: ManagedObjectContext, sectionName sectionNameKeyPathClosure: @autoclosure () -> KeyPath<Entity, Value>, cacheName: String? = nil) { let sectionNameKeyPath = sectionNameKeyPathClosure().pathString self.init(fetchRequest: fetchRequest, context: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) } public init(fetchRequest: FetchRequest<Entity>, context: ManagedObjectContext, sectionNameKeyPath: String? = nil, cacheName: String? = nil) { self.fetchRequest = fetchRequest self.rawValue = NSFetchedResultsController(fetchRequest: fetchRequest.toRaw() as NSFetchRequest<Entity>, managedObjectContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) self.rawValueDelegate = FetchedResultsControllerDelegate<Entity>() self.initialPredicate = fetchRequest.predicate self.initialSortDescriptors = fetchRequest.sortDescriptors // self.rawValue.delegate = self.rawValueDelegate } // MARK: - public func performFetch() { try! self.rawValue.performFetch() self.didPerformFetch = true } public func performFetchIfNeeded() { if !self.didPerformFetch { try! self.rawValue.performFetch() self.didPerformFetch = true } } } // MARK: - extension FetchRequestController { public var fetchedObjects: [Entity]? { self.performFetchIfNeeded() return self.rawValue.fetchedObjects } public func object(at indexPath: IndexPath) -> Entity { self.performFetchIfNeeded() return self.rawValue.object(at: indexPath) } public func indexPath(for object: Entity) -> IndexPath? { self.performFetchIfNeeded() return self.rawValue.indexPath(forObject: object) } } extension FetchRequestController { public func numberOfSections() -> Int { self.performFetchIfNeeded() return self.sections.count } public func numberOfObjects(inSection section: Int) -> Int { self.performFetchIfNeeded() return self.sections[section].numberOfObjects } } extension FetchRequestController { public var sections: [FetchedResultsSectionInfo<Entity>] { self.performFetchIfNeeded() guard let result = self.rawValue.sections?.map({ FetchedResultsSectionInfo<Entity>(rawValue: $0) }) else { fatalError("performFetch: hasn't been called.") } return result } public func section(forSectionIndexTitle title: String, at sectionIndex: Int) -> Int { self.performFetchIfNeeded() return self.rawValue.section(forSectionIndexTitle: title, at: sectionIndex) } } extension FetchRequestController { public func sectionIndexTitle(forSectionName sectionName: String) -> String? { self.performFetchIfNeeded() return self.rawValue.sectionIndexTitle(forSectionName: sectionName) } public var sectionIndexTitles: [String] { self.performFetchIfNeeded() return self.rawValue.sectionIndexTitles } } // MARK: - extension FetchRequestController { public func refresh(using predicate: Predicate<Entity>?, keepOriginalPredicate: Bool) { self.assignPredicate(predicate, keepOriginalPredicate: keepOriginalPredicate) self.refresh() } public func refresh(using rawValue: NSPredicate, keepOriginalPredicate: Bool) { self.assignPredicate(Predicate<Entity>(rawValue: rawValue), keepOriginalPredicate: keepOriginalPredicate) self.refresh() } public func refresh(using sortDescriptors: [SortDescriptor<Entity>]?, keepOriginalSortDescriptors: Bool) { self.assignSortDescriptors(sortDescriptors, keepOriginalSortDescriptors: keepOriginalSortDescriptors) self.refresh() } public func refresh(using rawValues: [NSSortDescriptor], keepOriginalSortDescriptors: Bool) { self.assignSortDescriptors(rawValues.map({ SortDescriptor<Entity>(rawValue: $0) }), keepOriginalSortDescriptors: keepOriginalSortDescriptors) self.refresh() } public func refresh(using predicate: Predicate<Entity>?, sortDescriptors: [SortDescriptor<Entity>]?, keepOriginalPredicate: Bool, keepOriginalSortDescriptors: Bool) { self.assignPredicate(predicate, keepOriginalPredicate: keepOriginalPredicate) self.assignSortDescriptors(sortDescriptors, keepOriginalSortDescriptors: keepOriginalSortDescriptors) self.refresh() } public func refresh(using predicateRawValue: NSPredicate, sortDescriptors sortDescriptorRawValues: [NSSortDescriptor], keepOriginalPredicate: Bool, keepOriginalSortDescriptors: Bool) { self.assignPredicate(Predicate<Entity>(rawValue: predicateRawValue), keepOriginalPredicate: keepOriginalPredicate) self.assignSortDescriptors(sortDescriptorRawValues.map({ SortDescriptor<Entity>(rawValue: $0) }), keepOriginalSortDescriptors: keepOriginalSortDescriptors) self.refresh() } // public func resetPredicate() { self.refresh(using: self.initialPredicate, keepOriginalPredicate: false) } public func resetSortDescriptors() { self.refresh(using: self.initialSortDescriptors, keepOriginalSortDescriptors: false) } public func resetPredicateAndSortDescriptors() { self.refresh(using: self.initialPredicate, sortDescriptors: self.initialSortDescriptors, keepOriginalPredicate: false, keepOriginalSortDescriptors: false) } } extension FetchRequestController { public func filter(using predicate: Predicate<Entity>) { self.refresh(using: predicate, keepOriginalPredicate: true) } public func filter(using predicateClosure: () -> Predicate<Entity>) { self.refresh(using: predicateClosure(), keepOriginalPredicate: true) } public func filter(using rawValue: NSPredicate) { self.refresh(using: Predicate<Entity>(rawValue: rawValue), keepOriginalPredicate: true) } public func resetFilter() { self.resetPredicate() } public func reset() { self.resetPredicateAndSortDescriptors() } } extension FetchRequestController { fileprivate func assignPredicate(_ predicate: Predicate<Entity>?, keepOriginalPredicate: Bool) { let newPredicate: Predicate<Entity>? if keepOriginalPredicate { if let initialPredicate = self.initialPredicate { if let predicate = predicate { newPredicate = CompoundPredicate<Entity>(type: .and, subpredicates: [initialPredicate, predicate]) } else { newPredicate = initialPredicate } } else { newPredicate = predicate } } else { newPredicate = predicate } self.rawValue.fetchRequest.predicate = newPredicate?.rawValue } fileprivate func assignSortDescriptors(_ sortDescriptors: [SortDescriptor<Entity>]?, keepOriginalSortDescriptors: Bool) { let newSortDescriptors: [SortDescriptor<Entity>]? if keepOriginalSortDescriptors { if let initialSortDescriptors = self.initialSortDescriptors { if let sortDescriptors = sortDescriptors { var tempSortDescriptors = initialSortDescriptors tempSortDescriptors += sortDescriptors newSortDescriptors = tempSortDescriptors } else { newSortDescriptors = initialSortDescriptors } } else { newSortDescriptors = sortDescriptors } } else { newSortDescriptors = sortDescriptors } self.rawValue.fetchRequest.sortDescriptors = newSortDescriptors?.map { $0.rawValue } } }
mit
gurinderhans/SwiftFSWatcher
src/SwiftFSWatcher/SwiftFSWatcherTests/SwiftFSWatcherTests.swift
1
796
// // SwiftFSWatcherTests.swift // SwiftFSWatcherTests // // Created by Gurinder Hans on 4/9/16. // Copyright © 2016 Gurinder Hans. All rights reserved. // import XCTest @testable import SwiftFSWatcher class SwiftFSWatcherTests: 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. } }
mit
ccqpein/Arithmetic-Exercises
Date-Arithmetic/DA.swift
1
2428
let monthDay:[Int] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,] let monthDayL:[Int] = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,] let yzero = 2000 func leapYear(_ y:Int) -> Bool { if (y % 4 == 0) && (y % 400 == 0 || y % 100 != 0) { return true } else { return false } } struct Date { var d:Int var m:Int var y:Int } // Can use switch to make algorithm add date by year (now is by month) // Todo: make this function have ability to decrease the date if input the num is negetive func addDate(_ days:Int, _ input:Date) -> (reDate:Date, daysLeft:Int) { guard days > 0 else { print("sorry, days number is nagetive, try to use \"reduceDate\"") return (input, 0) } var monthTable:[Int] = leapYear(input.y) ? monthDayL : monthDay let sumDays:Int = days + input.d var reDate:Date = input var daysLeft:Int = 0 if sumDays > monthTable[input.m - 1] { reDate.m += 1 daysLeft = sumDays - monthTable[input.m - 1] - 1 reDate.d = 1 if reDate.m > 12 { reDate.y += 1 reDate.m -= 12 } } else { reDate.d = sumDays } return (reDate, daysLeft) } func reduceDate(_ days:Int, _ input:Date) -> (reDate:Date, daysLeft:Int) { guard days < 0 else { print("sorry, days number is positive, try to use \"addDate\"") return (input, 0) } var monthTable:[Int] = leapYear(input.y) ? monthDayL : monthDay let sumDays:Int = days + input.d //sumdays may negative var reDate:Date = input var daysLeft = 0 if sumDays > 0 { reDate.d = sumDays }else{ reDate.m -= 1 if reDate.m < 1 { reDate.y -= 1 reDate.m = 12 } daysLeft = sumDays reDate.d = monthTable[reDate.m - 1] } return (reDate, daysLeft) } func main(_ days:Int, dateInput date:Date) -> Date { var daysLeft = days var reDate = date var f:((Int, Date) -> (Date, Int))? if days < 0 { f = reduceDate }else { f = addDate } while daysLeft != 0 { (reDate, daysLeft) = f!(daysLeft, reDate) } return reDate } let testa = Date(d:25, m:2, y:2004) let testb = Date(d:25, m:12, y:2004) let testc = Date(d:1, m:1, y:2005) //print(main(370, dateInput:testa)) //print(main(7, dateInput:testb))
apache-2.0
zxwWei/SwfitZeng
XWWeibo接收数据/XWWeibo/Classes/Model(模型)/Home(首页)/View/Cell/XWPictureView.swift
1
7432
// // XWPictureView.swift // GZWeibo05 // // Created by apple1 on 15/11/1. // Copyright © 2015年 zhangping. All rights reserved. // // MARK : - git clone https://github.com/December-XP/swiftweibo05.git 下载地址 import UIKit import SDWebImage let XWPictureViewCellNSNotification = "XWPictureViewCellNSNotification" let XWPictureViewCellSelectedPictureUrlKey = "XWPictureViewCellSelectedPictureUrlKey" let XWPictureViewCellSelectedIndexPathKey = "XWPictureViewCellSelectedIndexPathKey" class XWPictureView: UICollectionView { // MARK: - 微博模型 相当于重写setter var status: XWSatus? { didSet{ //print(status?.realPictureUrls?.count) reloadData() } } // 这个方法是 sizeToFit调用的,而且 返回的 CGSize 系统会设置为当前view的size override func sizeThatFits(size: CGSize) -> CGSize { return collectionViewSize() } // MARK: - 根据微博模型,计算配图的尺寸 让cell获得配图的大小 func collectionViewSize() -> CGSize { // 设置itemSize let itemSize = CGSize(width: 90, height: 90) layout.itemSize = itemSize layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 /// 列数 let column = 3 /// 间距 let margin: CGFloat = 10 // 获取微博里的图片个数来计算size 可以为0 let count = status?.realPictureUrls?.count ?? 0 if count == 0 { return CGSizeZero } if count == 1 { // 当时一张图片的时候,有些图片大,有些小,所以要根据图片的本来大小来调节 // 获取图片url let urlStr = status!.realPictureUrls![0].absoluteString var size = CGSizeMake(150, 120) // 获得图片 if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlStr) { size = image.size } // 让cell和collectionView一样大 if (size.width < 40){ size.width = 40 } layout.itemSize = size return size } layout.minimumLineSpacing = 10 layout.minimumInteritemSpacing = 10 if count == 4 { let width = 2 * itemSize.width + margin return CGSizeMake(width, width) } // 剩下 2, 3, 5, 6, 7, 8, 9 // 计算行数: 公式: 行数 = (图片数量 + 列数 -1) / 列数 let row = (count + column - 1) / column // 宽度公式: 宽度 = (列数 * item的宽度) + (列数 - 1) * 间距 let widht = (CGFloat(column) * itemSize.width) + (CGFloat(column) - 1) * margin // 高度公式: 高度 = (行数 * item的高度) + (行数 - 1) * 间距 let height = (CGFloat(row) * itemSize.height) + (CGFloat(row) - 1) * margin return CGSizeMake(widht, height) } // MARK: - collection Layout private var layout = UICollectionViewFlowLayout() // MARK: - 构造方法 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // layout 需在外面定义,不要使用 init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) init() { super.init(frame: CGRectZero, collectionViewLayout:layout) backgroundColor = UIColor.clearColor() // 数据源代理 dataSource = self delegate = self // 注册cell registerClass(XWPictureViewCell.self, forCellWithReuseIdentifier: "cell") // 准备UI // prepareUI() } } // MARK: 数据源方法 延伸 代理延伸 extension XWPictureView: UICollectionViewDataSource , UICollectionViewDelegate{ func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return status?.realPictureUrls?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! XWPictureViewCell // realPictureUrls里面有着转发微博和原创微博的图片数 cell.imgUrl = status?.realPictureUrls?[indexPath.item] return cell } // 当点击cell的时候调用 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // 记录index sttus是从cell处传过来的 let userInfo: [String: AnyObject] = [ XWPictureViewCellSelectedIndexPathKey : indexPath.item, //MARK: - bug 注意属性间的转换∫ XWPictureViewCellSelectedPictureUrlKey : status!.realLargePictureUrls! ] // 发送通知 将通知发送到homeVC NSNotificationCenter.defaultCenter().postNotificationName(XWPictureViewCellNSNotification, object: self, userInfo: userInfo) } } // MARK: - 自定义cell 用来显示图片 class XWPictureViewCell: UICollectionViewCell{ // MARK: - 属性图片路径 NSURL? 要为空 var imgUrl: NSURL? { didSet{ // 不要用错方法 picture.sd_setImageWithURL(imgUrl) let gif = (imgUrl!.absoluteString as NSString ) .pathExtension.lowercaseString == "gif" gifImageView.hidden = !gif } } // MARK: - 构造方法 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) prepareUI() } // MARK : - 准备UI func prepareUI() { contentView.addSubview(picture) contentView.addSubview(gifImageView) gifImageView.translatesAutoresizingMaskIntoConstraints = false // 添加约束 充满子控件 picture.ff_Fill(contentView) let views = ["gif":gifImageView] contentView.addConstraints(NSLayoutConstraint .constraintsWithVisualFormat("H:[gif]-4-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) contentView.addConstraints(NSLayoutConstraint .constraintsWithVisualFormat("V:[gif]-4-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) // gifImageView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: contentView, size: nil) } // MARK: - 懒加载 /// 其他图片不需要缓存 设置其适配属性 private lazy var picture: UIImageView = { let imageView = UIImageView () imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true return imageView }() /// gif图标 private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif")) }
apache-2.0
eldesperado/SpareTimeAlarmApp
SpareTimeMusicApp/UIColor+AlarmApp.swift
1
3956
// // UIColor+AlarmApp.swift // // Generated by Zeplin on 8/11/15. // Copyright (c) 2015 Pham Nguyen Nhat Trung. All rights reserved. // import UIKit extension UIColor { class func untMarineColor() -> UIColor { return UIColor(red: 9.0 / 255.0, green: 39.0 / 255.0, blue: 73.0 / 255.0, alpha: 1.0) } class func untAzulColor() -> UIColor { return UIColor(red: 43.0 / 255.0, green: 100.0 / 255.0, blue: 243.0 / 255.0, alpha: 1.0) } class func untCoralColor() -> UIColor { return UIColor(red: 247.0 / 255.0, green: 70.0 / 255.0, blue: 70.0 / 255.0, alpha: 1.0) } class func untOrangeYellowColor() -> UIColor { return UIColor(red: 255.0 / 255.0, green: 160.0 / 255.0, blue: 0.0, alpha: 1.0) } class func untWhiteColor() -> UIColor { return UIColor(white: 255.0 / 255.0, alpha: 1.0) } class func untLightWhiteColor() -> UIColor { return UIColor(white: 255.0 / 255.0, alpha: 0.15) } class func untTranswhiteColor() -> UIColor { return UIColor(white: 215.0 / 255.0, alpha: 0.0) } class func untLightishBlueColor() -> UIColor { return UIColor(red: 66.0 / 255.0, green: 121.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0) } class func untTransparentColor() -> UIColor { return UIColor(white: 255.0 / 255.0, alpha: 0.0) } class func untDeepSkyBlueColor() -> UIColor { return UIColor(red: 11.0 / 255.0, green: 118.0 / 255.0, blue: 241.0 / 255.0, alpha: 1.0) } class func untDustyOrangeColor() -> UIColor { return UIColor(red: 237.0 / 255.0, green: 111.0 / 255.0, blue: 75.0 / 255.0, alpha: 1.0) } class func untGreyishBrownColor() -> UIColor { return UIColor(white: 67.0 / 255.0, alpha: 1.0) } class func untBlackColor() -> UIColor { return UIColor(white: 33.0 / 255.0, alpha: 1.0) } class func untGrayColor() -> UIColor { return UIColor(white: 229.0 / 255.0, alpha: 1.0) } class func untSkyBlueColor() -> UIColor { return UIColor(red: 109.0 / 255.0, green: 173.0 / 255.0, blue: 248.0 / 255.0, alpha: 1.0) } // Method found from: https://github.com/yeahdongcn/UIColor-Hex-Swift/blob/master/UIColorExtension.swift public convenience init(rgba: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if rgba.hasPrefix("#") { let index = rgba.startIndex.advancedBy(1) let hex = rgba.substringFromIndex(index) let scanner = NSScanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexLongLong(&hexValue) { switch (hex.characters.count) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8", terminator: "") } } else { print("Scan hex error") } } else { print("Invalid RGB string, missing '#' as prefix", terminator: "") } self.init(red:red, green:green, blue:blue, alpha:alpha) } }
mit